xref: /qemu/hw/ppc/spapr_pci.c (revision bf8d4924)
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 <libfdt.h>
39 #include "trace.h"
40 #include "qemu/error-report.h"
41 #include "qapi/qmp/qerror.h"
42 
43 #include "hw/pci/pci_bridge.h"
44 #include "hw/pci/pci_bus.h"
45 #include "hw/ppc/spapr_drc.h"
46 #include "sysemu/device_tree.h"
47 #include "sysemu/kvm.h"
48 
49 #include "hw/vfio/vfio.h"
50 
51 /* Copied from the kernel arch/powerpc/platforms/pseries/msi.c */
52 #define RTAS_QUERY_FN           0
53 #define RTAS_CHANGE_FN          1
54 #define RTAS_RESET_FN           2
55 #define RTAS_CHANGE_MSI_FN      3
56 #define RTAS_CHANGE_MSIX_FN     4
57 
58 /* Interrupt types to return on RTAS_CHANGE_* */
59 #define RTAS_TYPE_MSI           1
60 #define RTAS_TYPE_MSIX          2
61 
62 #define FDT_NAME_MAX          128
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         xics_spapr_free(spapr->xics, 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 = xics_spapr_alloc_block(spapr->xics, 0, 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         xics_spapr_free(spapr->xics, 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  * For MSI-X, the vector number is encoded as a part of the address,
725  * data is set to 0.
726  * For MSI, the vector number is encoded in least bits in data.
727  */
728 static void spapr_msi_write(void *opaque, hwaddr addr,
729                             uint64_t data, unsigned size)
730 {
731     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
732     uint32_t irq = data;
733 
734     trace_spapr_pci_msi_write(addr, data, irq);
735 
736     qemu_irq_pulse(xics_get_qirq(spapr->xics, irq));
737 }
738 
739 static const MemoryRegionOps spapr_msi_ops = {
740     /* There is no .read as the read result is undefined by PCI spec */
741     .read = NULL,
742     .write = spapr_msi_write,
743     .endianness = DEVICE_LITTLE_ENDIAN
744 };
745 
746 /*
747  * PHB PCI device
748  */
749 static AddressSpace *spapr_pci_dma_iommu(PCIBus *bus, void *opaque, int devfn)
750 {
751     sPAPRPHBState *phb = opaque;
752 
753     return &phb->iommu_as;
754 }
755 
756 static char *spapr_phb_vfio_get_loc_code(sPAPRPHBState *sphb,  PCIDevice *pdev)
757 {
758     char *path = NULL, *buf = NULL, *host = NULL;
759 
760     /* Get the PCI VFIO host id */
761     host = object_property_get_str(OBJECT(pdev), "host", NULL);
762     if (!host) {
763         goto err_out;
764     }
765 
766     /* Construct the path of the file that will give us the DT location */
767     path = g_strdup_printf("/sys/bus/pci/devices/%s/devspec", host);
768     g_free(host);
769     if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) {
770         goto err_out;
771     }
772     g_free(path);
773 
774     /* Construct and read from host device tree the loc-code */
775     path = g_strdup_printf("/proc/device-tree%s/ibm,loc-code", buf);
776     g_free(buf);
777     if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) {
778         goto err_out;
779     }
780     return buf;
781 
782 err_out:
783     g_free(path);
784     return NULL;
785 }
786 
787 static char *spapr_phb_get_loc_code(sPAPRPHBState *sphb, PCIDevice *pdev)
788 {
789     char *buf;
790     const char *devtype = "qemu";
791     uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));
792 
793     if (object_dynamic_cast(OBJECT(pdev), "vfio-pci")) {
794         buf = spapr_phb_vfio_get_loc_code(sphb, pdev);
795         if (buf) {
796             return buf;
797         }
798         devtype = "vfio";
799     }
800     /*
801      * For emulated devices and VFIO-failure case, make up
802      * the loc-code.
803      */
804     buf = g_strdup_printf("%s_%s:%04x:%02x:%02x.%x",
805                           devtype, pdev->name, sphb->index, busnr,
806                           PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
807     return buf;
808 }
809 
810 /* Macros to operate with address in OF binding to PCI */
811 #define b_x(x, p, l)    (((x) & ((1<<(l))-1)) << (p))
812 #define b_n(x)          b_x((x), 31, 1) /* 0 if relocatable */
813 #define b_p(x)          b_x((x), 30, 1) /* 1 if prefetchable */
814 #define b_t(x)          b_x((x), 29, 1) /* 1 if the address is aliased */
815 #define b_ss(x)         b_x((x), 24, 2) /* the space code */
816 #define b_bbbbbbbb(x)   b_x((x), 16, 8) /* bus number */
817 #define b_ddddd(x)      b_x((x), 11, 5) /* device number */
818 #define b_fff(x)        b_x((x), 8, 3)  /* function number */
819 #define b_rrrrrrrr(x)   b_x((x), 0, 8)  /* register number */
820 
821 /* for 'reg'/'assigned-addresses' OF properties */
822 #define RESOURCE_CELLS_SIZE 2
823 #define RESOURCE_CELLS_ADDRESS 3
824 
825 typedef struct ResourceFields {
826     uint32_t phys_hi;
827     uint32_t phys_mid;
828     uint32_t phys_lo;
829     uint32_t size_hi;
830     uint32_t size_lo;
831 } QEMU_PACKED ResourceFields;
832 
833 typedef struct ResourceProps {
834     ResourceFields reg[8];
835     ResourceFields assigned[7];
836     uint32_t reg_len;
837     uint32_t assigned_len;
838 } ResourceProps;
839 
840 /* fill in the 'reg'/'assigned-resources' OF properties for
841  * a PCI device. 'reg' describes resource requirements for a
842  * device's IO/MEM regions, 'assigned-addresses' describes the
843  * actual resource assignments.
844  *
845  * the properties are arrays of ('phys-addr', 'size') pairs describing
846  * the addressable regions of the PCI device, where 'phys-addr' is a
847  * RESOURCE_CELLS_ADDRESS-tuple of 32-bit integers corresponding to
848  * (phys.hi, phys.mid, phys.lo), and 'size' is a
849  * RESOURCE_CELLS_SIZE-tuple corresponding to (size.hi, size.lo).
850  *
851  * phys.hi = 0xYYXXXXZZ, where:
852  *   0xYY = npt000ss
853  *          |||   |
854  *          |||   +-- space code
855  *          |||               |
856  *          |||               +  00 if configuration space
857  *          |||               +  01 if IO region,
858  *          |||               +  10 if 32-bit MEM region
859  *          |||               +  11 if 64-bit MEM region
860  *          |||
861  *          ||+------ for non-relocatable IO: 1 if aliased
862  *          ||        for relocatable IO: 1 if below 64KB
863  *          ||        for MEM: 1 if below 1MB
864  *          |+------- 1 if region is prefetchable
865  *          +-------- 1 if region is non-relocatable
866  *   0xXXXX = bbbbbbbb dddddfff, encoding bus, slot, and function
867  *            bits respectively
868  *   0xZZ = rrrrrrrr, the register number of the BAR corresponding
869  *          to the region
870  *
871  * phys.mid and phys.lo correspond respectively to the hi/lo portions
872  * of the actual address of the region.
873  *
874  * how the phys-addr/size values are used differ slightly between
875  * 'reg' and 'assigned-addresses' properties. namely, 'reg' has
876  * an additional description for the config space region of the
877  * device, and in the case of QEMU has n=0 and phys.mid=phys.lo=0
878  * to describe the region as relocatable, with an address-mapping
879  * that corresponds directly to the PHB's address space for the
880  * resource. 'assigned-addresses' always has n=1 set with an absolute
881  * address assigned for the resource. in general, 'assigned-addresses'
882  * won't be populated, since addresses for PCI devices are generally
883  * unmapped initially and left to the guest to assign.
884  *
885  * note also that addresses defined in these properties are, at least
886  * for PAPR guests, relative to the PHBs IO/MEM windows, and
887  * correspond directly to the addresses in the BARs.
888  *
889  * in accordance with PCI Bus Binding to Open Firmware,
890  * IEEE Std 1275-1994, section 4.1.1, as implemented by PAPR+ v2.7,
891  * Appendix C.
892  */
893 static void populate_resource_props(PCIDevice *d, ResourceProps *rp)
894 {
895     int bus_num = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(d))));
896     uint32_t dev_id = (b_bbbbbbbb(bus_num) |
897                        b_ddddd(PCI_SLOT(d->devfn)) |
898                        b_fff(PCI_FUNC(d->devfn)));
899     ResourceFields *reg, *assigned;
900     int i, reg_idx = 0, assigned_idx = 0;
901 
902     /* config space region */
903     reg = &rp->reg[reg_idx++];
904     reg->phys_hi = cpu_to_be32(dev_id);
905     reg->phys_mid = 0;
906     reg->phys_lo = 0;
907     reg->size_hi = 0;
908     reg->size_lo = 0;
909 
910     for (i = 0; i < PCI_NUM_REGIONS; i++) {
911         if (!d->io_regions[i].size) {
912             continue;
913         }
914 
915         reg = &rp->reg[reg_idx++];
916 
917         reg->phys_hi = cpu_to_be32(dev_id | b_rrrrrrrr(pci_bar(d, i)));
918         if (d->io_regions[i].type & PCI_BASE_ADDRESS_SPACE_IO) {
919             reg->phys_hi |= cpu_to_be32(b_ss(1));
920         } else if (d->io_regions[i].type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
921             reg->phys_hi |= cpu_to_be32(b_ss(3));
922         } else {
923             reg->phys_hi |= cpu_to_be32(b_ss(2));
924         }
925         reg->phys_mid = 0;
926         reg->phys_lo = 0;
927         reg->size_hi = cpu_to_be32(d->io_regions[i].size >> 32);
928         reg->size_lo = cpu_to_be32(d->io_regions[i].size);
929 
930         if (d->io_regions[i].addr == PCI_BAR_UNMAPPED) {
931             continue;
932         }
933 
934         assigned = &rp->assigned[assigned_idx++];
935         assigned->phys_hi = cpu_to_be32(reg->phys_hi | b_n(1));
936         assigned->phys_mid = cpu_to_be32(d->io_regions[i].addr >> 32);
937         assigned->phys_lo = cpu_to_be32(d->io_regions[i].addr);
938         assigned->size_hi = reg->size_hi;
939         assigned->size_lo = reg->size_lo;
940     }
941 
942     rp->reg_len = reg_idx * sizeof(ResourceFields);
943     rp->assigned_len = assigned_idx * sizeof(ResourceFields);
944 }
945 
946 static uint32_t spapr_phb_get_pci_drc_index(sPAPRPHBState *phb,
947                                             PCIDevice *pdev);
948 
949 static int spapr_populate_pci_child_dt(PCIDevice *dev, void *fdt, int offset,
950                                        sPAPRPHBState *sphb)
951 {
952     ResourceProps rp;
953     bool is_bridge = false;
954     int pci_status, err;
955     char *buf = NULL;
956     uint32_t drc_index = spapr_phb_get_pci_drc_index(sphb, dev);
957     uint32_t max_msi, max_msix;
958 
959     if (pci_default_read_config(dev, PCI_HEADER_TYPE, 1) ==
960         PCI_HEADER_TYPE_BRIDGE) {
961         is_bridge = true;
962     }
963 
964     /* in accordance with PAPR+ v2.7 13.6.3, Table 181 */
965     _FDT(fdt_setprop_cell(fdt, offset, "vendor-id",
966                           pci_default_read_config(dev, PCI_VENDOR_ID, 2)));
967     _FDT(fdt_setprop_cell(fdt, offset, "device-id",
968                           pci_default_read_config(dev, PCI_DEVICE_ID, 2)));
969     _FDT(fdt_setprop_cell(fdt, offset, "revision-id",
970                           pci_default_read_config(dev, PCI_REVISION_ID, 1)));
971     _FDT(fdt_setprop_cell(fdt, offset, "class-code",
972                           pci_default_read_config(dev, PCI_CLASS_PROG, 3)));
973     if (pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)) {
974         _FDT(fdt_setprop_cell(fdt, offset, "interrupts",
975                  pci_default_read_config(dev, PCI_INTERRUPT_PIN, 1)));
976     }
977 
978     if (!is_bridge) {
979         _FDT(fdt_setprop_cell(fdt, offset, "min-grant",
980             pci_default_read_config(dev, PCI_MIN_GNT, 1)));
981         _FDT(fdt_setprop_cell(fdt, offset, "max-latency",
982             pci_default_read_config(dev, PCI_MAX_LAT, 1)));
983     }
984 
985     if (pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)) {
986         _FDT(fdt_setprop_cell(fdt, offset, "subsystem-id",
987                  pci_default_read_config(dev, PCI_SUBSYSTEM_ID, 2)));
988     }
989 
990     if (pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)) {
991         _FDT(fdt_setprop_cell(fdt, offset, "subsystem-vendor-id",
992                  pci_default_read_config(dev, PCI_SUBSYSTEM_VENDOR_ID, 2)));
993     }
994 
995     _FDT(fdt_setprop_cell(fdt, offset, "cache-line-size",
996         pci_default_read_config(dev, PCI_CACHE_LINE_SIZE, 1)));
997 
998     /* the following fdt cells are masked off the pci status register */
999     pci_status = pci_default_read_config(dev, PCI_STATUS, 2);
1000     _FDT(fdt_setprop_cell(fdt, offset, "devsel-speed",
1001                           PCI_STATUS_DEVSEL_MASK & pci_status));
1002 
1003     if (pci_status & PCI_STATUS_FAST_BACK) {
1004         _FDT(fdt_setprop(fdt, offset, "fast-back-to-back", NULL, 0));
1005     }
1006     if (pci_status & PCI_STATUS_66MHZ) {
1007         _FDT(fdt_setprop(fdt, offset, "66mhz-capable", NULL, 0));
1008     }
1009     if (pci_status & PCI_STATUS_UDF) {
1010         _FDT(fdt_setprop(fdt, offset, "udf-supported", NULL, 0));
1011     }
1012 
1013     /* NOTE: this is normally generated by firmware via path/unit name,
1014      * but in our case we must set it manually since it does not get
1015      * processed by OF beforehand
1016      */
1017     _FDT(fdt_setprop_string(fdt, offset, "name", "pci"));
1018     buf = spapr_phb_get_loc_code(sphb, dev);
1019     if (!buf) {
1020         error_report("Failed setting the ibm,loc-code");
1021         return -1;
1022     }
1023 
1024     err = fdt_setprop_string(fdt, offset, "ibm,loc-code", buf);
1025     g_free(buf);
1026     if (err < 0) {
1027         return err;
1028     }
1029 
1030     if (drc_index) {
1031         _FDT(fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index));
1032     }
1033 
1034     _FDT(fdt_setprop_cell(fdt, offset, "#address-cells",
1035                           RESOURCE_CELLS_ADDRESS));
1036     _FDT(fdt_setprop_cell(fdt, offset, "#size-cells",
1037                           RESOURCE_CELLS_SIZE));
1038 
1039     max_msi = msi_nr_vectors_allocated(dev);
1040     if (max_msi) {
1041         _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi", max_msi));
1042     }
1043     max_msix = dev->msix_entries_nr;
1044     if (max_msix) {
1045         _FDT(fdt_setprop_cell(fdt, offset, "ibm,req#msi-x", max_msix));
1046     }
1047 
1048     populate_resource_props(dev, &rp);
1049     _FDT(fdt_setprop(fdt, offset, "reg", (uint8_t *)rp.reg, rp.reg_len));
1050     _FDT(fdt_setprop(fdt, offset, "assigned-addresses",
1051                      (uint8_t *)rp.assigned, rp.assigned_len));
1052 
1053     return 0;
1054 }
1055 
1056 /* create OF node for pci device and required OF DT properties */
1057 static int spapr_create_pci_child_dt(sPAPRPHBState *phb, PCIDevice *dev,
1058                                      void *fdt, int node_offset)
1059 {
1060     int offset, ret;
1061     int slot = PCI_SLOT(dev->devfn);
1062     int func = PCI_FUNC(dev->devfn);
1063     char nodename[FDT_NAME_MAX];
1064 
1065     if (func != 0) {
1066         snprintf(nodename, FDT_NAME_MAX, "pci@%x,%x", slot, func);
1067     } else {
1068         snprintf(nodename, FDT_NAME_MAX, "pci@%x", slot);
1069     }
1070     offset = fdt_add_subnode(fdt, node_offset, nodename);
1071     ret = spapr_populate_pci_child_dt(dev, fdt, offset, phb);
1072 
1073     g_assert(!ret);
1074     if (ret) {
1075         return 0;
1076     }
1077     return offset;
1078 }
1079 
1080 static void spapr_phb_add_pci_device(sPAPRDRConnector *drc,
1081                                      sPAPRPHBState *phb,
1082                                      PCIDevice *pdev,
1083                                      Error **errp)
1084 {
1085     sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1086     DeviceState *dev = DEVICE(pdev);
1087     void *fdt = NULL;
1088     int fdt_start_offset = 0, fdt_size;
1089 
1090     if (object_dynamic_cast(OBJECT(pdev), "vfio-pci")) {
1091         sPAPRTCETable *tcet = spapr_tce_find_by_liobn(phb->dma_liobn);
1092 
1093         spapr_tce_set_need_vfio(tcet, true);
1094     }
1095 
1096     fdt = create_device_tree(&fdt_size);
1097     fdt_start_offset = spapr_create_pci_child_dt(phb, pdev, fdt, 0);
1098     if (!fdt_start_offset) {
1099         error_setg(errp, "Failed to create pci child device tree node");
1100         goto out;
1101     }
1102 
1103     drck->attach(drc, DEVICE(pdev),
1104                  fdt, fdt_start_offset, !dev->hotplugged, errp);
1105 out:
1106     if (*errp) {
1107         g_free(fdt);
1108     }
1109 }
1110 
1111 static void spapr_phb_remove_pci_device_cb(DeviceState *dev, void *opaque)
1112 {
1113     /* some version guests do not wait for completion of a device
1114      * cleanup (generally done asynchronously by the kernel) before
1115      * signaling to QEMU that the device is safe, but instead sleep
1116      * for some 'safe' period of time. unfortunately on a busy host
1117      * this sleep isn't guaranteed to be long enough, resulting in
1118      * bad things like IRQ lines being left asserted during final
1119      * device removal. to deal with this we call reset just prior
1120      * to finalizing the device, which will put the device back into
1121      * an 'idle' state, as the device cleanup code expects.
1122      */
1123     pci_device_reset(PCI_DEVICE(dev));
1124     object_unparent(OBJECT(dev));
1125 }
1126 
1127 static void spapr_phb_remove_pci_device(sPAPRDRConnector *drc,
1128                                         sPAPRPHBState *phb,
1129                                         PCIDevice *pdev,
1130                                         Error **errp)
1131 {
1132     sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1133 
1134     drck->detach(drc, DEVICE(pdev), spapr_phb_remove_pci_device_cb, phb, errp);
1135 }
1136 
1137 static sPAPRDRConnector *spapr_phb_get_pci_func_drc(sPAPRPHBState *phb,
1138                                                     uint32_t busnr,
1139                                                     int32_t devfn)
1140 {
1141     return spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_PCI,
1142                                     (phb->index << 16) |
1143                                     (busnr << 8) |
1144                                     devfn);
1145 }
1146 
1147 static sPAPRDRConnector *spapr_phb_get_pci_drc(sPAPRPHBState *phb,
1148                                                PCIDevice *pdev)
1149 {
1150     uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));
1151     return spapr_phb_get_pci_func_drc(phb, busnr, pdev->devfn);
1152 }
1153 
1154 static uint32_t spapr_phb_get_pci_drc_index(sPAPRPHBState *phb,
1155                                             PCIDevice *pdev)
1156 {
1157     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1158     sPAPRDRConnectorClass *drck;
1159 
1160     if (!drc) {
1161         return 0;
1162     }
1163 
1164     drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1165     return drck->get_index(drc);
1166 }
1167 
1168 static void spapr_phb_hot_plug_child(HotplugHandler *plug_handler,
1169                                      DeviceState *plugged_dev, Error **errp)
1170 {
1171     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1172     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1173     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1174     Error *local_err = NULL;
1175     PCIBus *bus = PCI_BUS(qdev_get_parent_bus(DEVICE(pdev)));
1176     uint32_t slotnr = PCI_SLOT(pdev->devfn);
1177 
1178     /* if DR is disabled we don't need to do anything in the case of
1179      * hotplug or coldplug callbacks
1180      */
1181     if (!phb->dr_enabled) {
1182         /* if this is a hotplug operation initiated by the user
1183          * we need to let them know it's not enabled
1184          */
1185         if (plugged_dev->hotplugged) {
1186             error_setg(errp, QERR_BUS_NO_HOTPLUG,
1187                        object_get_typename(OBJECT(phb)));
1188         }
1189         return;
1190     }
1191 
1192     g_assert(drc);
1193 
1194     /* Following the QEMU convention used for PCIe multifunction
1195      * hotplug, we do not allow functions to be hotplugged to a
1196      * slot that already has function 0 present
1197      */
1198     if (plugged_dev->hotplugged && bus->devices[PCI_DEVFN(slotnr, 0)] &&
1199         PCI_FUNC(pdev->devfn) != 0) {
1200         error_setg(errp, "PCI: slot %d function 0 already ocuppied by %s,"
1201                    " additional functions can no longer be exposed to guest.",
1202                    slotnr, bus->devices[PCI_DEVFN(slotnr, 0)]->name);
1203         return;
1204     }
1205 
1206     spapr_phb_add_pci_device(drc, phb, pdev, &local_err);
1207     if (local_err) {
1208         error_propagate(errp, local_err);
1209         return;
1210     }
1211 
1212     /* If this is function 0, signal hotplug for all the device functions.
1213      * Otherwise defer sending the hotplug event.
1214      */
1215     if (plugged_dev->hotplugged && PCI_FUNC(pdev->devfn) == 0) {
1216         int i;
1217 
1218         for (i = 0; i < 8; i++) {
1219             sPAPRDRConnector *func_drc;
1220             sPAPRDRConnectorClass *func_drck;
1221             sPAPRDREntitySense state;
1222 
1223             func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1224                                                   PCI_DEVFN(slotnr, i));
1225             func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1226             func_drck->entity_sense(func_drc, &state);
1227 
1228             if (state == SPAPR_DR_ENTITY_SENSE_PRESENT) {
1229                 spapr_hotplug_req_add_by_index(func_drc);
1230             }
1231         }
1232     }
1233 }
1234 
1235 static void spapr_phb_hot_unplug_child(HotplugHandler *plug_handler,
1236                                        DeviceState *plugged_dev, Error **errp)
1237 {
1238     sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));
1239     PCIDevice *pdev = PCI_DEVICE(plugged_dev);
1240     sPAPRDRConnectorClass *drck;
1241     sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);
1242     Error *local_err = NULL;
1243 
1244     if (!phb->dr_enabled) {
1245         error_setg(errp, QERR_BUS_NO_HOTPLUG,
1246                    object_get_typename(OBJECT(phb)));
1247         return;
1248     }
1249 
1250     g_assert(drc);
1251 
1252     drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);
1253     if (!drck->release_pending(drc)) {
1254         PCIBus *bus = PCI_BUS(qdev_get_parent_bus(DEVICE(pdev)));
1255         uint32_t slotnr = PCI_SLOT(pdev->devfn);
1256         sPAPRDRConnector *func_drc;
1257         sPAPRDRConnectorClass *func_drck;
1258         sPAPRDREntitySense state;
1259         int i;
1260 
1261         /* ensure any other present functions are pending unplug */
1262         if (PCI_FUNC(pdev->devfn) == 0) {
1263             for (i = 1; i < 8; i++) {
1264                 func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1265                                                       PCI_DEVFN(slotnr, i));
1266                 func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1267                 func_drck->entity_sense(func_drc, &state);
1268                 if (state == SPAPR_DR_ENTITY_SENSE_PRESENT
1269                     && !func_drck->release_pending(func_drc)) {
1270                     error_setg(errp,
1271                                "PCI: slot %d, function %d still present. "
1272                                "Must unplug all non-0 functions first.",
1273                                slotnr, i);
1274                     return;
1275                 }
1276             }
1277         }
1278 
1279         spapr_phb_remove_pci_device(drc, phb, pdev, &local_err);
1280         if (local_err) {
1281             error_propagate(errp, local_err);
1282             return;
1283         }
1284 
1285         /* if this isn't func 0, defer unplug event. otherwise signal removal
1286          * for all present functions
1287          */
1288         if (PCI_FUNC(pdev->devfn) == 0) {
1289             for (i = 7; i >= 0; i--) {
1290                 func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),
1291                                                       PCI_DEVFN(slotnr, i));
1292                 func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);
1293                 func_drck->entity_sense(func_drc, &state);
1294                 if (state == SPAPR_DR_ENTITY_SENSE_PRESENT) {
1295                     spapr_hotplug_req_remove_by_index(func_drc);
1296                 }
1297             }
1298         }
1299     }
1300 }
1301 
1302 static void spapr_phb_realize(DeviceState *dev, Error **errp)
1303 {
1304     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
1305     SysBusDevice *s = SYS_BUS_DEVICE(dev);
1306     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);
1307     PCIHostState *phb = PCI_HOST_BRIDGE(s);
1308     char *namebuf;
1309     int i;
1310     PCIBus *bus;
1311     uint64_t msi_window_size = 4096;
1312     sPAPRTCETable *tcet;
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_spapr_alloc_block(spapr->xics, 0, 1, true, false,
1446                                      &local_err);
1447         if (local_err) {
1448             error_propagate(errp, local_err);
1449             error_prepend(errp, "can't allocate LSIs: ");
1450             return;
1451         }
1452 
1453         sphb->lsi_table[i].irq = irq;
1454     }
1455 
1456     /* allocate connectors for child PCI devices */
1457     if (sphb->dr_enabled) {
1458         for (i = 0; i < PCI_SLOT_MAX * 8; i++) {
1459             spapr_dr_connector_new(OBJECT(phb),
1460                                    SPAPR_DR_CONNECTOR_TYPE_PCI,
1461                                    (sphb->index << 16) | i);
1462         }
1463     }
1464 
1465     tcet = spapr_tce_new_table(DEVICE(sphb), sphb->dma_liobn);
1466     if (!tcet) {
1467         error_setg(errp, "Unable to create TCE table for %s",
1468                    sphb->dtbusname);
1469         return;
1470     }
1471 
1472     memory_region_add_subregion_overlap(&sphb->iommu_root, 0,
1473                                         spapr_tce_get_iommu(tcet), 0);
1474 
1475     sphb->msi = g_hash_table_new_full(g_int_hash, g_int_equal, g_free, g_free);
1476 }
1477 
1478 static int spapr_phb_children_reset(Object *child, void *opaque)
1479 {
1480     DeviceState *dev = (DeviceState *) object_dynamic_cast(child, TYPE_DEVICE);
1481 
1482     if (dev) {
1483         device_reset(dev);
1484     }
1485 
1486     return 0;
1487 }
1488 
1489 void spapr_phb_dma_reset(sPAPRPHBState *sphb)
1490 {
1491     sPAPRTCETable *tcet = spapr_tce_find_by_liobn(sphb->dma_liobn);
1492 
1493     if (tcet && tcet->nb_table) {
1494         spapr_tce_table_disable(tcet);
1495     }
1496 
1497     /* Register default 32bit DMA window */
1498     spapr_tce_table_enable(tcet, SPAPR_TCE_PAGE_SHIFT, sphb->dma_win_addr,
1499                            sphb->dma_win_size >> SPAPR_TCE_PAGE_SHIFT);
1500 }
1501 
1502 static void spapr_phb_reset(DeviceState *qdev)
1503 {
1504     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(qdev);
1505 
1506     spapr_phb_dma_reset(sphb);
1507 
1508     /* Reset the IOMMU state */
1509     object_child_foreach(OBJECT(qdev), spapr_phb_children_reset, NULL);
1510 
1511     if (spapr_phb_eeh_available(SPAPR_PCI_HOST_BRIDGE(qdev))) {
1512         spapr_phb_vfio_reset(qdev);
1513     }
1514 }
1515 
1516 static Property spapr_phb_properties[] = {
1517     DEFINE_PROP_UINT32("index", sPAPRPHBState, index, -1),
1518     DEFINE_PROP_UINT64("buid", sPAPRPHBState, buid, -1),
1519     DEFINE_PROP_UINT32("liobn", sPAPRPHBState, dma_liobn, -1),
1520     DEFINE_PROP_UINT64("mem_win_addr", sPAPRPHBState, mem_win_addr, -1),
1521     DEFINE_PROP_UINT64("mem_win_size", sPAPRPHBState, mem_win_size,
1522                        SPAPR_PCI_MMIO_WIN_SIZE),
1523     DEFINE_PROP_UINT64("io_win_addr", sPAPRPHBState, io_win_addr, -1),
1524     DEFINE_PROP_UINT64("io_win_size", sPAPRPHBState, io_win_size,
1525                        SPAPR_PCI_IO_WIN_SIZE),
1526     DEFINE_PROP_BOOL("dynamic-reconfiguration", sPAPRPHBState, dr_enabled,
1527                      true),
1528     /* Default DMA window is 0..1GB */
1529     DEFINE_PROP_UINT64("dma_win_addr", sPAPRPHBState, dma_win_addr, 0),
1530     DEFINE_PROP_UINT64("dma_win_size", sPAPRPHBState, dma_win_size, 0x40000000),
1531     DEFINE_PROP_END_OF_LIST(),
1532 };
1533 
1534 static const VMStateDescription vmstate_spapr_pci_lsi = {
1535     .name = "spapr_pci/lsi",
1536     .version_id = 1,
1537     .minimum_version_id = 1,
1538     .fields = (VMStateField[]) {
1539         VMSTATE_UINT32_EQUAL(irq, struct spapr_pci_lsi),
1540 
1541         VMSTATE_END_OF_LIST()
1542     },
1543 };
1544 
1545 static const VMStateDescription vmstate_spapr_pci_msi = {
1546     .name = "spapr_pci/msi",
1547     .version_id = 1,
1548     .minimum_version_id = 1,
1549     .fields = (VMStateField []) {
1550         VMSTATE_UINT32(key, spapr_pci_msi_mig),
1551         VMSTATE_UINT32(value.first_irq, spapr_pci_msi_mig),
1552         VMSTATE_UINT32(value.num, spapr_pci_msi_mig),
1553         VMSTATE_END_OF_LIST()
1554     },
1555 };
1556 
1557 static void spapr_pci_pre_save(void *opaque)
1558 {
1559     sPAPRPHBState *sphb = opaque;
1560     GHashTableIter iter;
1561     gpointer key, value;
1562     int i;
1563 
1564     g_free(sphb->msi_devs);
1565     sphb->msi_devs = NULL;
1566     sphb->msi_devs_num = g_hash_table_size(sphb->msi);
1567     if (!sphb->msi_devs_num) {
1568         return;
1569     }
1570     sphb->msi_devs = g_malloc(sphb->msi_devs_num * sizeof(spapr_pci_msi_mig));
1571 
1572     g_hash_table_iter_init(&iter, sphb->msi);
1573     for (i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {
1574         sphb->msi_devs[i].key = *(uint32_t *) key;
1575         sphb->msi_devs[i].value = *(spapr_pci_msi *) value;
1576     }
1577 }
1578 
1579 static int spapr_pci_post_load(void *opaque, int version_id)
1580 {
1581     sPAPRPHBState *sphb = opaque;
1582     gpointer key, value;
1583     int i;
1584 
1585     for (i = 0; i < sphb->msi_devs_num; ++i) {
1586         key = g_memdup(&sphb->msi_devs[i].key,
1587                        sizeof(sphb->msi_devs[i].key));
1588         value = g_memdup(&sphb->msi_devs[i].value,
1589                          sizeof(sphb->msi_devs[i].value));
1590         g_hash_table_insert(sphb->msi, key, value);
1591     }
1592     g_free(sphb->msi_devs);
1593     sphb->msi_devs = NULL;
1594     sphb->msi_devs_num = 0;
1595 
1596     return 0;
1597 }
1598 
1599 static const VMStateDescription vmstate_spapr_pci = {
1600     .name = "spapr_pci",
1601     .version_id = 2,
1602     .minimum_version_id = 2,
1603     .pre_save = spapr_pci_pre_save,
1604     .post_load = spapr_pci_post_load,
1605     .fields = (VMStateField[]) {
1606         VMSTATE_UINT64_EQUAL(buid, sPAPRPHBState),
1607         VMSTATE_UINT32_EQUAL(dma_liobn, sPAPRPHBState),
1608         VMSTATE_UINT64_EQUAL(mem_win_addr, sPAPRPHBState),
1609         VMSTATE_UINT64_EQUAL(mem_win_size, sPAPRPHBState),
1610         VMSTATE_UINT64_EQUAL(io_win_addr, sPAPRPHBState),
1611         VMSTATE_UINT64_EQUAL(io_win_size, sPAPRPHBState),
1612         VMSTATE_STRUCT_ARRAY(lsi_table, sPAPRPHBState, PCI_NUM_PINS, 0,
1613                              vmstate_spapr_pci_lsi, struct spapr_pci_lsi),
1614         VMSTATE_INT32(msi_devs_num, sPAPRPHBState),
1615         VMSTATE_STRUCT_VARRAY_ALLOC(msi_devs, sPAPRPHBState, msi_devs_num, 0,
1616                                     vmstate_spapr_pci_msi, spapr_pci_msi_mig),
1617         VMSTATE_END_OF_LIST()
1618     },
1619 };
1620 
1621 static const char *spapr_phb_root_bus_path(PCIHostState *host_bridge,
1622                                            PCIBus *rootbus)
1623 {
1624     sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(host_bridge);
1625 
1626     return sphb->dtbusname;
1627 }
1628 
1629 static void spapr_phb_class_init(ObjectClass *klass, void *data)
1630 {
1631     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(klass);
1632     DeviceClass *dc = DEVICE_CLASS(klass);
1633     HotplugHandlerClass *hp = HOTPLUG_HANDLER_CLASS(klass);
1634 
1635     hc->root_bus_path = spapr_phb_root_bus_path;
1636     dc->realize = spapr_phb_realize;
1637     dc->props = spapr_phb_properties;
1638     dc->reset = spapr_phb_reset;
1639     dc->vmsd = &vmstate_spapr_pci;
1640     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1641     hp->plug = spapr_phb_hot_plug_child;
1642     hp->unplug = spapr_phb_hot_unplug_child;
1643 }
1644 
1645 static const TypeInfo spapr_phb_info = {
1646     .name          = TYPE_SPAPR_PCI_HOST_BRIDGE,
1647     .parent        = TYPE_PCI_HOST_BRIDGE,
1648     .instance_size = sizeof(sPAPRPHBState),
1649     .class_init    = spapr_phb_class_init,
1650     .interfaces    = (InterfaceInfo[]) {
1651         { TYPE_HOTPLUG_HANDLER },
1652         { }
1653     }
1654 };
1655 
1656 PCIHostState *spapr_create_phb(sPAPRMachineState *spapr, int index)
1657 {
1658     DeviceState *dev;
1659 
1660     dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);
1661     qdev_prop_set_uint32(dev, "index", index);
1662     qdev_init_nofail(dev);
1663 
1664     return PCI_HOST_BRIDGE(dev);
1665 }
1666 
1667 typedef struct sPAPRFDT {
1668     void *fdt;
1669     int node_off;
1670     sPAPRPHBState *sphb;
1671 } sPAPRFDT;
1672 
1673 static void spapr_populate_pci_devices_dt(PCIBus *bus, PCIDevice *pdev,
1674                                           void *opaque)
1675 {
1676     PCIBus *sec_bus;
1677     sPAPRFDT *p = opaque;
1678     int offset;
1679     sPAPRFDT s_fdt;
1680 
1681     offset = spapr_create_pci_child_dt(p->sphb, pdev, p->fdt, p->node_off);
1682     if (!offset) {
1683         error_report("Failed to create pci child device tree node");
1684         return;
1685     }
1686 
1687     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
1688          PCI_HEADER_TYPE_BRIDGE)) {
1689         return;
1690     }
1691 
1692     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
1693     if (!sec_bus) {
1694         return;
1695     }
1696 
1697     s_fdt.fdt = p->fdt;
1698     s_fdt.node_off = offset;
1699     s_fdt.sphb = p->sphb;
1700     pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
1701                         spapr_populate_pci_devices_dt,
1702                         &s_fdt);
1703 }
1704 
1705 static void spapr_phb_pci_enumerate_bridge(PCIBus *bus, PCIDevice *pdev,
1706                                            void *opaque)
1707 {
1708     unsigned int *bus_no = opaque;
1709     unsigned int primary = *bus_no;
1710     unsigned int subordinate = 0xff;
1711     PCIBus *sec_bus = NULL;
1712 
1713     if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
1714          PCI_HEADER_TYPE_BRIDGE)) {
1715         return;
1716     }
1717 
1718     (*bus_no)++;
1719     pci_default_write_config(pdev, PCI_PRIMARY_BUS, primary, 1);
1720     pci_default_write_config(pdev, PCI_SECONDARY_BUS, *bus_no, 1);
1721     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
1722 
1723     sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
1724     if (!sec_bus) {
1725         return;
1726     }
1727 
1728     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, subordinate, 1);
1729     pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
1730                         spapr_phb_pci_enumerate_bridge, bus_no);
1731     pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, *bus_no, 1);
1732 }
1733 
1734 static void spapr_phb_pci_enumerate(sPAPRPHBState *phb)
1735 {
1736     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
1737     unsigned int bus_no = 0;
1738 
1739     pci_for_each_device(bus, pci_bus_num(bus),
1740                         spapr_phb_pci_enumerate_bridge,
1741                         &bus_no);
1742 
1743 }
1744 
1745 int spapr_populate_pci_dt(sPAPRPHBState *phb,
1746                           uint32_t xics_phandle,
1747                           void *fdt)
1748 {
1749     int bus_off, i, j, ret;
1750     char nodename[FDT_NAME_MAX];
1751     uint32_t bus_range[] = { cpu_to_be32(0), cpu_to_be32(0xff) };
1752     const uint64_t mmiosize = memory_region_size(&phb->memwindow);
1753     const uint64_t w32max = (1ULL << 32) - SPAPR_PCI_MEM_WIN_BUS_OFFSET;
1754     const uint64_t w32size = MIN(w32max, mmiosize);
1755     const uint64_t w64size = (mmiosize > w32size) ? (mmiosize - w32size) : 0;
1756     struct {
1757         uint32_t hi;
1758         uint64_t child;
1759         uint64_t parent;
1760         uint64_t size;
1761     } QEMU_PACKED ranges[] = {
1762         {
1763             cpu_to_be32(b_ss(1)), cpu_to_be64(0),
1764             cpu_to_be64(phb->io_win_addr),
1765             cpu_to_be64(memory_region_size(&phb->iospace)),
1766         },
1767         {
1768             cpu_to_be32(b_ss(2)), cpu_to_be64(SPAPR_PCI_MEM_WIN_BUS_OFFSET),
1769             cpu_to_be64(phb->mem_win_addr),
1770             cpu_to_be64(w32size),
1771         },
1772         {
1773             cpu_to_be32(b_ss(3)), cpu_to_be64(1ULL << 32),
1774             cpu_to_be64(phb->mem_win_addr + w32size),
1775             cpu_to_be64(w64size)
1776         },
1777     };
1778     const unsigned sizeof_ranges = (w64size ? 3 : 2) * sizeof(ranges[0]);
1779     uint64_t bus_reg[] = { cpu_to_be64(phb->buid), 0 };
1780     uint32_t interrupt_map_mask[] = {
1781         cpu_to_be32(b_ddddd(-1)|b_fff(0)), 0x0, 0x0, cpu_to_be32(-1)};
1782     uint32_t interrupt_map[PCI_SLOT_MAX * PCI_NUM_PINS][7];
1783     sPAPRTCETable *tcet;
1784     PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;
1785     sPAPRFDT s_fdt;
1786 
1787     /* Start populating the FDT */
1788     snprintf(nodename, FDT_NAME_MAX, "pci@%" PRIx64, phb->buid);
1789     bus_off = fdt_add_subnode(fdt, 0, nodename);
1790     if (bus_off < 0) {
1791         return bus_off;
1792     }
1793 
1794     /* Write PHB properties */
1795     _FDT(fdt_setprop_string(fdt, bus_off, "device_type", "pci"));
1796     _FDT(fdt_setprop_string(fdt, bus_off, "compatible", "IBM,Logical_PHB"));
1797     _FDT(fdt_setprop_cell(fdt, bus_off, "#address-cells", 0x3));
1798     _FDT(fdt_setprop_cell(fdt, bus_off, "#size-cells", 0x2));
1799     _FDT(fdt_setprop_cell(fdt, bus_off, "#interrupt-cells", 0x1));
1800     _FDT(fdt_setprop(fdt, bus_off, "used-by-rtas", NULL, 0));
1801     _FDT(fdt_setprop(fdt, bus_off, "bus-range", &bus_range, sizeof(bus_range)));
1802     _FDT(fdt_setprop(fdt, bus_off, "ranges", &ranges, sizeof_ranges));
1803     _FDT(fdt_setprop(fdt, bus_off, "reg", &bus_reg, sizeof(bus_reg)));
1804     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pci-config-space-type", 0x1));
1805     _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pe-total-#msi", XICS_IRQS_SPAPR));
1806 
1807     /* Build the interrupt-map, this must matches what is done
1808      * in pci_spapr_map_irq
1809      */
1810     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map-mask",
1811                      &interrupt_map_mask, sizeof(interrupt_map_mask)));
1812     for (i = 0; i < PCI_SLOT_MAX; i++) {
1813         for (j = 0; j < PCI_NUM_PINS; j++) {
1814             uint32_t *irqmap = interrupt_map[i*PCI_NUM_PINS + j];
1815             int lsi_num = pci_spapr_swizzle(i, j);
1816 
1817             irqmap[0] = cpu_to_be32(b_ddddd(i)|b_fff(0));
1818             irqmap[1] = 0;
1819             irqmap[2] = 0;
1820             irqmap[3] = cpu_to_be32(j+1);
1821             irqmap[4] = cpu_to_be32(xics_phandle);
1822             irqmap[5] = cpu_to_be32(phb->lsi_table[lsi_num].irq);
1823             irqmap[6] = cpu_to_be32(0x8);
1824         }
1825     }
1826     /* Write interrupt map */
1827     _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map,
1828                      sizeof(interrupt_map)));
1829 
1830     tcet = spapr_tce_find_by_liobn(phb->dma_liobn);
1831     if (!tcet) {
1832         return -1;
1833     }
1834     spapr_dma_dt(fdt, bus_off, "ibm,dma-window",
1835                  tcet->liobn, tcet->bus_offset,
1836                  tcet->nb_table << tcet->page_shift);
1837 
1838     /* Walk the bridges and program the bus numbers*/
1839     spapr_phb_pci_enumerate(phb);
1840     _FDT(fdt_setprop_cell(fdt, bus_off, "qemu,phb-enumerated", 0x1));
1841 
1842     /* Populate tree nodes with PCI devices attached */
1843     s_fdt.fdt = fdt;
1844     s_fdt.node_off = bus_off;
1845     s_fdt.sphb = phb;
1846     pci_for_each_device(bus, pci_bus_num(bus),
1847                         spapr_populate_pci_devices_dt,
1848                         &s_fdt);
1849 
1850     ret = spapr_drc_populate_dt(fdt, bus_off, OBJECT(phb),
1851                                 SPAPR_DR_CONNECTOR_TYPE_PCI);
1852     if (ret) {
1853         return ret;
1854     }
1855 
1856     return 0;
1857 }
1858 
1859 void spapr_pci_rtas_init(void)
1860 {
1861     spapr_rtas_register(RTAS_READ_PCI_CONFIG, "read-pci-config",
1862                         rtas_read_pci_config);
1863     spapr_rtas_register(RTAS_WRITE_PCI_CONFIG, "write-pci-config",
1864                         rtas_write_pci_config);
1865     spapr_rtas_register(RTAS_IBM_READ_PCI_CONFIG, "ibm,read-pci-config",
1866                         rtas_ibm_read_pci_config);
1867     spapr_rtas_register(RTAS_IBM_WRITE_PCI_CONFIG, "ibm,write-pci-config",
1868                         rtas_ibm_write_pci_config);
1869     if (msi_nonbroken) {
1870         spapr_rtas_register(RTAS_IBM_QUERY_INTERRUPT_SOURCE_NUMBER,
1871                             "ibm,query-interrupt-source-number",
1872                             rtas_ibm_query_interrupt_source_number);
1873         spapr_rtas_register(RTAS_IBM_CHANGE_MSI, "ibm,change-msi",
1874                             rtas_ibm_change_msi);
1875     }
1876 
1877     spapr_rtas_register(RTAS_IBM_SET_EEH_OPTION,
1878                         "ibm,set-eeh-option",
1879                         rtas_ibm_set_eeh_option);
1880     spapr_rtas_register(RTAS_IBM_GET_CONFIG_ADDR_INFO2,
1881                         "ibm,get-config-addr-info2",
1882                         rtas_ibm_get_config_addr_info2);
1883     spapr_rtas_register(RTAS_IBM_READ_SLOT_RESET_STATE2,
1884                         "ibm,read-slot-reset-state2",
1885                         rtas_ibm_read_slot_reset_state2);
1886     spapr_rtas_register(RTAS_IBM_SET_SLOT_RESET,
1887                         "ibm,set-slot-reset",
1888                         rtas_ibm_set_slot_reset);
1889     spapr_rtas_register(RTAS_IBM_CONFIGURE_PE,
1890                         "ibm,configure-pe",
1891                         rtas_ibm_configure_pe);
1892     spapr_rtas_register(RTAS_IBM_SLOT_ERROR_DETAIL,
1893                         "ibm,slot-error-detail",
1894                         rtas_ibm_slot_error_detail);
1895 }
1896 
1897 static void spapr_pci_register_types(void)
1898 {
1899     type_register_static(&spapr_phb_info);
1900 }
1901 
1902 type_init(spapr_pci_register_types)
1903 
1904 static int spapr_switch_one_vga(DeviceState *dev, void *opaque)
1905 {
1906     bool be = *(bool *)opaque;
1907 
1908     if (object_dynamic_cast(OBJECT(dev), "VGA")
1909         || object_dynamic_cast(OBJECT(dev), "secondary-vga")) {
1910         object_property_set_bool(OBJECT(dev), be, "big-endian-framebuffer",
1911                                  &error_abort);
1912     }
1913     return 0;
1914 }
1915 
1916 void spapr_pci_switch_vga(bool big_endian)
1917 {
1918     sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());
1919     sPAPRPHBState *sphb;
1920 
1921     /*
1922      * For backward compatibility with existing guests, we switch
1923      * the endianness of the VGA controller when changing the guest
1924      * interrupt mode
1925      */
1926     QLIST_FOREACH(sphb, &spapr->phbs, list) {
1927         BusState *bus = &PCI_HOST_BRIDGE(sphb)->bus->qbus;
1928         qbus_walk_children(bus, spapr_switch_one_vga, NULL, NULL, NULL,
1929                            &big_endian);
1930     }
1931 }
1932