xref: /openbmc/qemu/hw/pci/pci.c (revision d3860a57)
1 /*
2  * QEMU PCI bus manager
3  *
4  * Copyright (c) 2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/datadir.h"
27 #include "qemu/units.h"
28 #include "hw/irq.h"
29 #include "hw/pci/pci.h"
30 #include "hw/pci/pci_bridge.h"
31 #include "hw/pci/pci_bus.h"
32 #include "hw/pci/pci_host.h"
33 #include "hw/qdev-properties.h"
34 #include "hw/qdev-properties-system.h"
35 #include "migration/qemu-file-types.h"
36 #include "migration/vmstate.h"
37 #include "net/net.h"
38 #include "sysemu/numa.h"
39 #include "sysemu/sysemu.h"
40 #include "hw/loader.h"
41 #include "qemu/error-report.h"
42 #include "qemu/range.h"
43 #include "trace.h"
44 #include "hw/pci/msi.h"
45 #include "hw/pci/msix.h"
46 #include "hw/hotplug.h"
47 #include "hw/boards.h"
48 #include "qapi/error.h"
49 #include "qemu/cutils.h"
50 #include "pci-internal.h"
51 
52 #include "hw/xen/xen.h"
53 #include "hw/i386/kvm/xen_evtchn.h"
54 
55 //#define DEBUG_PCI
56 #ifdef DEBUG_PCI
57 # define PCI_DPRINTF(format, ...)       printf(format, ## __VA_ARGS__)
58 #else
59 # define PCI_DPRINTF(format, ...)       do { } while (0)
60 #endif
61 
62 bool pci_available = true;
63 
64 static char *pcibus_get_dev_path(DeviceState *dev);
65 static char *pcibus_get_fw_dev_path(DeviceState *dev);
66 static void pcibus_reset(BusState *qbus);
67 
68 static Property pci_props[] = {
69     DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
70     DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
71     DEFINE_PROP_UINT32("romsize", PCIDevice, romsize, -1),
72     DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
73     DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
74                     QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
75     DEFINE_PROP_BIT("x-pcie-lnksta-dllla", PCIDevice, cap_present,
76                     QEMU_PCIE_LNKSTA_DLLLA_BITNR, true),
77     DEFINE_PROP_BIT("x-pcie-extcap-init", PCIDevice, cap_present,
78                     QEMU_PCIE_EXTCAP_INIT_BITNR, true),
79     DEFINE_PROP_STRING("failover_pair_id", PCIDevice,
80                        failover_pair_id),
81     DEFINE_PROP_UINT32("acpi-index",  PCIDevice, acpi_index, 0),
82     DEFINE_PROP_END_OF_LIST()
83 };
84 
85 static const VMStateDescription vmstate_pcibus = {
86     .name = "PCIBUS",
87     .version_id = 1,
88     .minimum_version_id = 1,
89     .fields = (VMStateField[]) {
90         VMSTATE_INT32_EQUAL(nirq, PCIBus, NULL),
91         VMSTATE_VARRAY_INT32(irq_count, PCIBus,
92                              nirq, 0, vmstate_info_int32,
93                              int32_t),
94         VMSTATE_END_OF_LIST()
95     }
96 };
97 
98 static void pci_init_bus_master(PCIDevice *pci_dev)
99 {
100     AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);
101 
102     memory_region_init_alias(&pci_dev->bus_master_enable_region,
103                              OBJECT(pci_dev), "bus master",
104                              dma_as->root, 0, memory_region_size(dma_as->root));
105     memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
106     memory_region_add_subregion(&pci_dev->bus_master_container_region, 0,
107                                 &pci_dev->bus_master_enable_region);
108 }
109 
110 static void pcibus_machine_done(Notifier *notifier, void *data)
111 {
112     PCIBus *bus = container_of(notifier, PCIBus, machine_done);
113     int i;
114 
115     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
116         if (bus->devices[i]) {
117             pci_init_bus_master(bus->devices[i]);
118         }
119     }
120 }
121 
122 static void pci_bus_realize(BusState *qbus, Error **errp)
123 {
124     PCIBus *bus = PCI_BUS(qbus);
125 
126     bus->machine_done.notify = pcibus_machine_done;
127     qemu_add_machine_init_done_notifier(&bus->machine_done);
128 
129     vmstate_register(NULL, VMSTATE_INSTANCE_ID_ANY, &vmstate_pcibus, bus);
130 }
131 
132 static void pcie_bus_realize(BusState *qbus, Error **errp)
133 {
134     PCIBus *bus = PCI_BUS(qbus);
135     Error *local_err = NULL;
136 
137     pci_bus_realize(qbus, &local_err);
138     if (local_err) {
139         error_propagate(errp, local_err);
140         return;
141     }
142 
143     /*
144      * A PCI-E bus can support extended config space if it's the root
145      * bus, or if the bus/bridge above it does as well
146      */
147     if (pci_bus_is_root(bus)) {
148         bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
149     } else {
150         PCIBus *parent_bus = pci_get_bus(bus->parent_dev);
151 
152         if (pci_bus_allows_extended_config_space(parent_bus)) {
153             bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
154         }
155     }
156 }
157 
158 static void pci_bus_unrealize(BusState *qbus)
159 {
160     PCIBus *bus = PCI_BUS(qbus);
161 
162     qemu_remove_machine_init_done_notifier(&bus->machine_done);
163 
164     vmstate_unregister(NULL, &vmstate_pcibus, bus);
165 }
166 
167 static int pcibus_num(PCIBus *bus)
168 {
169     if (pci_bus_is_root(bus)) {
170         return 0; /* pci host bridge */
171     }
172     return bus->parent_dev->config[PCI_SECONDARY_BUS];
173 }
174 
175 static uint16_t pcibus_numa_node(PCIBus *bus)
176 {
177     return NUMA_NODE_UNASSIGNED;
178 }
179 
180 static void pci_bus_class_init(ObjectClass *klass, void *data)
181 {
182     BusClass *k = BUS_CLASS(klass);
183     PCIBusClass *pbc = PCI_BUS_CLASS(klass);
184 
185     k->print_dev = pcibus_dev_print;
186     k->get_dev_path = pcibus_get_dev_path;
187     k->get_fw_dev_path = pcibus_get_fw_dev_path;
188     k->realize = pci_bus_realize;
189     k->unrealize = pci_bus_unrealize;
190     k->reset = pcibus_reset;
191 
192     pbc->bus_num = pcibus_num;
193     pbc->numa_node = pcibus_numa_node;
194 }
195 
196 static const TypeInfo pci_bus_info = {
197     .name = TYPE_PCI_BUS,
198     .parent = TYPE_BUS,
199     .instance_size = sizeof(PCIBus),
200     .class_size = sizeof(PCIBusClass),
201     .class_init = pci_bus_class_init,
202 };
203 
204 static const TypeInfo cxl_interface_info = {
205     .name          = INTERFACE_CXL_DEVICE,
206     .parent        = TYPE_INTERFACE,
207 };
208 
209 static const TypeInfo pcie_interface_info = {
210     .name          = INTERFACE_PCIE_DEVICE,
211     .parent        = TYPE_INTERFACE,
212 };
213 
214 static const TypeInfo conventional_pci_interface_info = {
215     .name          = INTERFACE_CONVENTIONAL_PCI_DEVICE,
216     .parent        = TYPE_INTERFACE,
217 };
218 
219 static void pcie_bus_class_init(ObjectClass *klass, void *data)
220 {
221     BusClass *k = BUS_CLASS(klass);
222 
223     k->realize = pcie_bus_realize;
224 }
225 
226 static const TypeInfo pcie_bus_info = {
227     .name = TYPE_PCIE_BUS,
228     .parent = TYPE_PCI_BUS,
229     .class_init = pcie_bus_class_init,
230 };
231 
232 static const TypeInfo cxl_bus_info = {
233     .name       = TYPE_CXL_BUS,
234     .parent     = TYPE_PCIE_BUS,
235     .class_init = pcie_bus_class_init,
236 };
237 
238 static void pci_update_mappings(PCIDevice *d);
239 static void pci_irq_handler(void *opaque, int irq_num, int level);
240 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
241 static void pci_del_option_rom(PCIDevice *pdev);
242 
243 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
244 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
245 
246 PCIHostStateList pci_host_bridges;
247 
248 int pci_bar(PCIDevice *d, int reg)
249 {
250     uint8_t type;
251 
252     /* PCIe virtual functions do not have their own BARs */
253     assert(!pci_is_vf(d));
254 
255     if (reg != PCI_ROM_SLOT)
256         return PCI_BASE_ADDRESS_0 + reg * 4;
257 
258     type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
259     return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
260 }
261 
262 static inline int pci_irq_state(PCIDevice *d, int irq_num)
263 {
264         return (d->irq_state >> irq_num) & 0x1;
265 }
266 
267 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
268 {
269         d->irq_state &= ~(0x1 << irq_num);
270         d->irq_state |= level << irq_num;
271 }
272 
273 static void pci_bus_change_irq_level(PCIBus *bus, int irq_num, int change)
274 {
275     assert(irq_num >= 0);
276     assert(irq_num < bus->nirq);
277     bus->irq_count[irq_num] += change;
278     bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
279 }
280 
281 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
282 {
283     PCIBus *bus;
284     for (;;) {
285         int dev_irq = irq_num;
286         bus = pci_get_bus(pci_dev);
287         assert(bus->map_irq);
288         irq_num = bus->map_irq(pci_dev, irq_num);
289         trace_pci_route_irq(dev_irq, DEVICE(pci_dev)->canonical_path, irq_num,
290                             pci_bus_is_root(bus) ? "root-complex"
291                                     : DEVICE(bus->parent_dev)->canonical_path);
292         if (bus->set_irq)
293             break;
294         pci_dev = bus->parent_dev;
295     }
296     pci_bus_change_irq_level(bus, irq_num, change);
297 }
298 
299 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
300 {
301     assert(irq_num >= 0);
302     assert(irq_num < bus->nirq);
303     return !!bus->irq_count[irq_num];
304 }
305 
306 /* Update interrupt status bit in config space on interrupt
307  * state change. */
308 static void pci_update_irq_status(PCIDevice *dev)
309 {
310     if (dev->irq_state) {
311         dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
312     } else {
313         dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
314     }
315 }
316 
317 void pci_device_deassert_intx(PCIDevice *dev)
318 {
319     int i;
320     for (i = 0; i < PCI_NUM_PINS; ++i) {
321         pci_irq_handler(dev, i, 0);
322     }
323 }
324 
325 static void pci_msi_trigger(PCIDevice *dev, MSIMessage msg)
326 {
327     MemTxAttrs attrs = {};
328 
329     /*
330      * Xen uses the high bits of the address to contain some of the bits
331      * of the PIRQ#. Therefore we can't just send the write cycle and
332      * trust that it's caught by the APIC at 0xfee00000 because the
333      * target of the write might be e.g. 0x0x1000fee46000 for PIRQ#4166.
334      * So we intercept the delivery here instead of in kvm_send_msi().
335      */
336     if (xen_mode == XEN_EMULATE &&
337         xen_evtchn_deliver_pirq_msi(msg.address, msg.data)) {
338         return;
339     }
340     attrs.requester_id = pci_requester_id(dev);
341     address_space_stl_le(&dev->bus_master_as, msg.address, msg.data,
342                          attrs, NULL);
343 }
344 
345 static void pci_reset_regions(PCIDevice *dev)
346 {
347     int r;
348     if (pci_is_vf(dev)) {
349         return;
350     }
351 
352     for (r = 0; r < PCI_NUM_REGIONS; ++r) {
353         PCIIORegion *region = &dev->io_regions[r];
354         if (!region->size) {
355             continue;
356         }
357 
358         if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
359             region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
360             pci_set_quad(dev->config + pci_bar(dev, r), region->type);
361         } else {
362             pci_set_long(dev->config + pci_bar(dev, r), region->type);
363         }
364     }
365 }
366 
367 static void pci_do_device_reset(PCIDevice *dev)
368 {
369     pci_device_deassert_intx(dev);
370     assert(dev->irq_state == 0);
371 
372     /* Clear all writable bits */
373     pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
374                                  pci_get_word(dev->wmask + PCI_COMMAND) |
375                                  pci_get_word(dev->w1cmask + PCI_COMMAND));
376     pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
377                                  pci_get_word(dev->wmask + PCI_STATUS) |
378                                  pci_get_word(dev->w1cmask + PCI_STATUS));
379     /* Some devices make bits of PCI_INTERRUPT_LINE read only */
380     pci_byte_test_and_clear_mask(dev->config + PCI_INTERRUPT_LINE,
381                               pci_get_word(dev->wmask + PCI_INTERRUPT_LINE) |
382                               pci_get_word(dev->w1cmask + PCI_INTERRUPT_LINE));
383     dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
384     pci_reset_regions(dev);
385     pci_update_mappings(dev);
386 
387     msi_reset(dev);
388     msix_reset(dev);
389 }
390 
391 /*
392  * This function is called on #RST and FLR.
393  * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
394  */
395 void pci_device_reset(PCIDevice *dev)
396 {
397     device_cold_reset(&dev->qdev);
398     pci_do_device_reset(dev);
399 }
400 
401 /*
402  * Trigger pci bus reset under a given bus.
403  * Called via bus_cold_reset on RST# assert, after the devices
404  * have been reset device_cold_reset-ed already.
405  */
406 static void pcibus_reset(BusState *qbus)
407 {
408     PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
409     int i;
410 
411     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
412         if (bus->devices[i]) {
413             pci_do_device_reset(bus->devices[i]);
414         }
415     }
416 
417     for (i = 0; i < bus->nirq; i++) {
418         assert(bus->irq_count[i] == 0);
419     }
420 }
421 
422 static void pci_host_bus_register(DeviceState *host)
423 {
424     PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
425 
426     QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
427 }
428 
429 static void pci_host_bus_unregister(DeviceState *host)
430 {
431     PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
432 
433     QLIST_REMOVE(host_bridge, next);
434 }
435 
436 PCIBus *pci_device_root_bus(const PCIDevice *d)
437 {
438     PCIBus *bus = pci_get_bus(d);
439 
440     while (!pci_bus_is_root(bus)) {
441         d = bus->parent_dev;
442         assert(d != NULL);
443 
444         bus = pci_get_bus(d);
445     }
446 
447     return bus;
448 }
449 
450 const char *pci_root_bus_path(PCIDevice *dev)
451 {
452     PCIBus *rootbus = pci_device_root_bus(dev);
453     PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
454     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
455 
456     assert(host_bridge->bus == rootbus);
457 
458     if (hc->root_bus_path) {
459         return (*hc->root_bus_path)(host_bridge, rootbus);
460     }
461 
462     return rootbus->qbus.name;
463 }
464 
465 bool pci_bus_bypass_iommu(PCIBus *bus)
466 {
467     PCIBus *rootbus = bus;
468     PCIHostState *host_bridge;
469 
470     if (!pci_bus_is_root(bus)) {
471         rootbus = pci_device_root_bus(bus->parent_dev);
472     }
473 
474     host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
475 
476     assert(host_bridge->bus == rootbus);
477 
478     return host_bridge->bypass_iommu;
479 }
480 
481 static void pci_root_bus_internal_init(PCIBus *bus, DeviceState *parent,
482                                        MemoryRegion *address_space_mem,
483                                        MemoryRegion *address_space_io,
484                                        uint8_t devfn_min)
485 {
486     assert(PCI_FUNC(devfn_min) == 0);
487     bus->devfn_min = devfn_min;
488     bus->slot_reserved_mask = 0x0;
489     bus->address_space_mem = address_space_mem;
490     bus->address_space_io = address_space_io;
491     bus->flags |= PCI_BUS_IS_ROOT;
492 
493     /* host bridge */
494     QLIST_INIT(&bus->child);
495 
496     pci_host_bus_register(parent);
497 }
498 
499 static void pci_bus_uninit(PCIBus *bus)
500 {
501     pci_host_bus_unregister(BUS(bus)->parent);
502 }
503 
504 bool pci_bus_is_express(const PCIBus *bus)
505 {
506     return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
507 }
508 
509 void pci_root_bus_init(PCIBus *bus, size_t bus_size, DeviceState *parent,
510                        const char *name,
511                        MemoryRegion *address_space_mem,
512                        MemoryRegion *address_space_io,
513                        uint8_t devfn_min, const char *typename)
514 {
515     qbus_init(bus, bus_size, typename, parent, name);
516     pci_root_bus_internal_init(bus, parent, address_space_mem,
517                                address_space_io, devfn_min);
518 }
519 
520 PCIBus *pci_root_bus_new(DeviceState *parent, const char *name,
521                          MemoryRegion *address_space_mem,
522                          MemoryRegion *address_space_io,
523                          uint8_t devfn_min, const char *typename)
524 {
525     PCIBus *bus;
526 
527     bus = PCI_BUS(qbus_new(typename, parent, name));
528     pci_root_bus_internal_init(bus, parent, address_space_mem,
529                                address_space_io, devfn_min);
530     return bus;
531 }
532 
533 void pci_root_bus_cleanup(PCIBus *bus)
534 {
535     pci_bus_uninit(bus);
536     /* the caller of the unplug hotplug handler will delete this device */
537     qbus_unrealize(BUS(bus));
538 }
539 
540 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq,
541                   void *irq_opaque, int nirq)
542 {
543     bus->set_irq = set_irq;
544     bus->irq_opaque = irq_opaque;
545     bus->nirq = nirq;
546     bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
547 }
548 
549 void pci_bus_map_irqs(PCIBus *bus, pci_map_irq_fn map_irq)
550 {
551     bus->map_irq = map_irq;
552 }
553 
554 void pci_bus_irqs_cleanup(PCIBus *bus)
555 {
556     bus->set_irq = NULL;
557     bus->map_irq = NULL;
558     bus->irq_opaque = NULL;
559     bus->nirq = 0;
560     g_free(bus->irq_count);
561 }
562 
563 PCIBus *pci_register_root_bus(DeviceState *parent, const char *name,
564                               pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
565                               void *irq_opaque,
566                               MemoryRegion *address_space_mem,
567                               MemoryRegion *address_space_io,
568                               uint8_t devfn_min, int nirq,
569                               const char *typename)
570 {
571     PCIBus *bus;
572 
573     bus = pci_root_bus_new(parent, name, address_space_mem,
574                            address_space_io, devfn_min, typename);
575     pci_bus_irqs(bus, set_irq, irq_opaque, nirq);
576     pci_bus_map_irqs(bus, map_irq);
577     return bus;
578 }
579 
580 void pci_unregister_root_bus(PCIBus *bus)
581 {
582     pci_bus_irqs_cleanup(bus);
583     pci_root_bus_cleanup(bus);
584 }
585 
586 int pci_bus_num(PCIBus *s)
587 {
588     return PCI_BUS_GET_CLASS(s)->bus_num(s);
589 }
590 
591 /* Returns the min and max bus numbers of a PCI bus hierarchy */
592 void pci_bus_range(PCIBus *bus, int *min_bus, int *max_bus)
593 {
594     int i;
595     *min_bus = *max_bus = pci_bus_num(bus);
596 
597     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
598         PCIDevice *dev = bus->devices[i];
599 
600         if (dev && IS_PCI_BRIDGE(dev)) {
601             *min_bus = MIN(*min_bus, dev->config[PCI_SECONDARY_BUS]);
602             *max_bus = MAX(*max_bus, dev->config[PCI_SUBORDINATE_BUS]);
603         }
604     }
605 }
606 
607 int pci_bus_numa_node(PCIBus *bus)
608 {
609     return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
610 }
611 
612 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size,
613                                  const VMStateField *field)
614 {
615     PCIDevice *s = container_of(pv, PCIDevice, config);
616     uint8_t *config;
617     int i;
618 
619     assert(size == pci_config_size(s));
620     config = g_malloc(size);
621 
622     qemu_get_buffer(f, config, size);
623     for (i = 0; i < size; ++i) {
624         if ((config[i] ^ s->config[i]) &
625             s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
626             error_report("%s: Bad config data: i=0x%x read: %x device: %x "
627                          "cmask: %x wmask: %x w1cmask:%x", __func__,
628                          i, config[i], s->config[i],
629                          s->cmask[i], s->wmask[i], s->w1cmask[i]);
630             g_free(config);
631             return -EINVAL;
632         }
633     }
634     memcpy(s->config, config, size);
635 
636     pci_update_mappings(s);
637     if (IS_PCI_BRIDGE(s)) {
638         pci_bridge_update_mappings(PCI_BRIDGE(s));
639     }
640 
641     memory_region_set_enabled(&s->bus_master_enable_region,
642                               pci_get_word(s->config + PCI_COMMAND)
643                               & PCI_COMMAND_MASTER);
644 
645     g_free(config);
646     return 0;
647 }
648 
649 /* just put buffer */
650 static int put_pci_config_device(QEMUFile *f, void *pv, size_t size,
651                                  const VMStateField *field, JSONWriter *vmdesc)
652 {
653     const uint8_t **v = pv;
654     assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
655     qemu_put_buffer(f, *v, size);
656 
657     return 0;
658 }
659 
660 static VMStateInfo vmstate_info_pci_config = {
661     .name = "pci config",
662     .get  = get_pci_config_device,
663     .put  = put_pci_config_device,
664 };
665 
666 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size,
667                              const VMStateField *field)
668 {
669     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
670     uint32_t irq_state[PCI_NUM_PINS];
671     int i;
672     for (i = 0; i < PCI_NUM_PINS; ++i) {
673         irq_state[i] = qemu_get_be32(f);
674         if (irq_state[i] != 0x1 && irq_state[i] != 0) {
675             fprintf(stderr, "irq state %d: must be 0 or 1.\n",
676                     irq_state[i]);
677             return -EINVAL;
678         }
679     }
680 
681     for (i = 0; i < PCI_NUM_PINS; ++i) {
682         pci_set_irq_state(s, i, irq_state[i]);
683     }
684 
685     return 0;
686 }
687 
688 static int put_pci_irq_state(QEMUFile *f, void *pv, size_t size,
689                              const VMStateField *field, JSONWriter *vmdesc)
690 {
691     int i;
692     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
693 
694     for (i = 0; i < PCI_NUM_PINS; ++i) {
695         qemu_put_be32(f, pci_irq_state(s, i));
696     }
697 
698     return 0;
699 }
700 
701 static VMStateInfo vmstate_info_pci_irq_state = {
702     .name = "pci irq state",
703     .get  = get_pci_irq_state,
704     .put  = put_pci_irq_state,
705 };
706 
707 static bool migrate_is_pcie(void *opaque, int version_id)
708 {
709     return pci_is_express((PCIDevice *)opaque);
710 }
711 
712 static bool migrate_is_not_pcie(void *opaque, int version_id)
713 {
714     return !pci_is_express((PCIDevice *)opaque);
715 }
716 
717 const VMStateDescription vmstate_pci_device = {
718     .name = "PCIDevice",
719     .version_id = 2,
720     .minimum_version_id = 1,
721     .fields = (VMStateField[]) {
722         VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
723         VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
724                                    migrate_is_not_pcie,
725                                    0, vmstate_info_pci_config,
726                                    PCI_CONFIG_SPACE_SIZE),
727         VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
728                                    migrate_is_pcie,
729                                    0, vmstate_info_pci_config,
730                                    PCIE_CONFIG_SPACE_SIZE),
731         VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
732                                    vmstate_info_pci_irq_state,
733                                    PCI_NUM_PINS * sizeof(int32_t)),
734         VMSTATE_END_OF_LIST()
735     }
736 };
737 
738 
739 void pci_device_save(PCIDevice *s, QEMUFile *f)
740 {
741     /* Clear interrupt status bit: it is implicit
742      * in irq_state which we are saving.
743      * This makes us compatible with old devices
744      * which never set or clear this bit. */
745     s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
746     vmstate_save_state(f, &vmstate_pci_device, s, NULL);
747     /* Restore the interrupt status bit. */
748     pci_update_irq_status(s);
749 }
750 
751 int pci_device_load(PCIDevice *s, QEMUFile *f)
752 {
753     int ret;
754     ret = vmstate_load_state(f, &vmstate_pci_device, s, s->version_id);
755     /* Restore the interrupt status bit. */
756     pci_update_irq_status(s);
757     return ret;
758 }
759 
760 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
761 {
762     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
763                  pci_default_sub_vendor_id);
764     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
765                  pci_default_sub_device_id);
766 }
767 
768 /*
769  * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
770  *       [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
771  */
772 static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
773                              unsigned int *slotp, unsigned int *funcp)
774 {
775     const char *p;
776     char *e;
777     unsigned long val;
778     unsigned long dom = 0, bus = 0;
779     unsigned int slot = 0;
780     unsigned int func = 0;
781 
782     p = addr;
783     val = strtoul(p, &e, 16);
784     if (e == p)
785         return -1;
786     if (*e == ':') {
787         bus = val;
788         p = e + 1;
789         val = strtoul(p, &e, 16);
790         if (e == p)
791             return -1;
792         if (*e == ':') {
793             dom = bus;
794             bus = val;
795             p = e + 1;
796             val = strtoul(p, &e, 16);
797             if (e == p)
798                 return -1;
799         }
800     }
801 
802     slot = val;
803 
804     if (funcp != NULL) {
805         if (*e != '.')
806             return -1;
807 
808         p = e + 1;
809         val = strtoul(p, &e, 16);
810         if (e == p)
811             return -1;
812 
813         func = val;
814     }
815 
816     /* if funcp == NULL func is 0 */
817     if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
818         return -1;
819 
820     if (*e)
821         return -1;
822 
823     *domp = dom;
824     *busp = bus;
825     *slotp = slot;
826     if (funcp != NULL)
827         *funcp = func;
828     return 0;
829 }
830 
831 static void pci_init_cmask(PCIDevice *dev)
832 {
833     pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
834     pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
835     dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
836     dev->cmask[PCI_REVISION_ID] = 0xff;
837     dev->cmask[PCI_CLASS_PROG] = 0xff;
838     pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
839     dev->cmask[PCI_HEADER_TYPE] = 0xff;
840     dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
841 }
842 
843 static void pci_init_wmask(PCIDevice *dev)
844 {
845     int config_size = pci_config_size(dev);
846 
847     dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
848     dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
849     pci_set_word(dev->wmask + PCI_COMMAND,
850                  PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
851                  PCI_COMMAND_INTX_DISABLE);
852     pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
853 
854     memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
855            config_size - PCI_CONFIG_HEADER_SIZE);
856 }
857 
858 static void pci_init_w1cmask(PCIDevice *dev)
859 {
860     /*
861      * Note: It's okay to set w1cmask even for readonly bits as
862      * long as their value is hardwired to 0.
863      */
864     pci_set_word(dev->w1cmask + PCI_STATUS,
865                  PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
866                  PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
867                  PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
868 }
869 
870 static void pci_init_mask_bridge(PCIDevice *d)
871 {
872     /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
873        PCI_SEC_LETENCY_TIMER */
874     memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
875 
876     /* base and limit */
877     d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
878     d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
879     pci_set_word(d->wmask + PCI_MEMORY_BASE,
880                  PCI_MEMORY_RANGE_MASK & 0xffff);
881     pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
882                  PCI_MEMORY_RANGE_MASK & 0xffff);
883     pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
884                  PCI_PREF_RANGE_MASK & 0xffff);
885     pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
886                  PCI_PREF_RANGE_MASK & 0xffff);
887 
888     /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
889     memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
890 
891     /* Supported memory and i/o types */
892     d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
893     d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
894     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
895                                PCI_PREF_RANGE_TYPE_64);
896     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
897                                PCI_PREF_RANGE_TYPE_64);
898 
899     /*
900      * TODO: Bridges default to 10-bit VGA decoding but we currently only
901      * implement 16-bit decoding (no alias support).
902      */
903     pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
904                  PCI_BRIDGE_CTL_PARITY |
905                  PCI_BRIDGE_CTL_SERR |
906                  PCI_BRIDGE_CTL_ISA |
907                  PCI_BRIDGE_CTL_VGA |
908                  PCI_BRIDGE_CTL_VGA_16BIT |
909                  PCI_BRIDGE_CTL_MASTER_ABORT |
910                  PCI_BRIDGE_CTL_BUS_RESET |
911                  PCI_BRIDGE_CTL_FAST_BACK |
912                  PCI_BRIDGE_CTL_DISCARD |
913                  PCI_BRIDGE_CTL_SEC_DISCARD |
914                  PCI_BRIDGE_CTL_DISCARD_SERR);
915     /* Below does not do anything as we never set this bit, put here for
916      * completeness. */
917     pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
918                  PCI_BRIDGE_CTL_DISCARD_STATUS);
919     d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
920     d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
921     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
922                                PCI_PREF_RANGE_TYPE_MASK);
923     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
924                                PCI_PREF_RANGE_TYPE_MASK);
925 }
926 
927 static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
928 {
929     uint8_t slot = PCI_SLOT(dev->devfn);
930     uint8_t func;
931 
932     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
933         dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
934     }
935 
936     /*
937      * With SR/IOV and ARI, a device at function 0 need not be a multifunction
938      * device, as it may just be a VF that ended up with function 0 in
939      * the legacy PCI interpretation. Avoid failing in such cases:
940      */
941     if (pci_is_vf(dev) &&
942         dev->exp.sriov_vf.pf->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
943         return;
944     }
945 
946     /*
947      * multifunction bit is interpreted in two ways as follows.
948      *   - all functions must set the bit to 1.
949      *     Example: Intel X53
950      *   - function 0 must set the bit, but the rest function (> 0)
951      *     is allowed to leave the bit to 0.
952      *     Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
953      *
954      * So OS (at least Linux) checks the bit of only function 0,
955      * and doesn't see the bit of function > 0.
956      *
957      * The below check allows both interpretation.
958      */
959     if (PCI_FUNC(dev->devfn)) {
960         PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
961         if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
962             /* function 0 should set multifunction bit */
963             error_setg(errp, "PCI: single function device can't be populated "
964                        "in function %x.%x", slot, PCI_FUNC(dev->devfn));
965             return;
966         }
967         return;
968     }
969 
970     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
971         return;
972     }
973     /* function 0 indicates single function, so function > 0 must be NULL */
974     for (func = 1; func < PCI_FUNC_MAX; ++func) {
975         if (bus->devices[PCI_DEVFN(slot, func)]) {
976             error_setg(errp, "PCI: %x.0 indicates single function, "
977                        "but %x.%x is already populated.",
978                        slot, slot, func);
979             return;
980         }
981     }
982 }
983 
984 static void pci_config_alloc(PCIDevice *pci_dev)
985 {
986     int config_size = pci_config_size(pci_dev);
987 
988     pci_dev->config = g_malloc0(config_size);
989     pci_dev->cmask = g_malloc0(config_size);
990     pci_dev->wmask = g_malloc0(config_size);
991     pci_dev->w1cmask = g_malloc0(config_size);
992     pci_dev->used = g_malloc0(config_size);
993 }
994 
995 static void pci_config_free(PCIDevice *pci_dev)
996 {
997     g_free(pci_dev->config);
998     g_free(pci_dev->cmask);
999     g_free(pci_dev->wmask);
1000     g_free(pci_dev->w1cmask);
1001     g_free(pci_dev->used);
1002 }
1003 
1004 static void do_pci_unregister_device(PCIDevice *pci_dev)
1005 {
1006     pci_get_bus(pci_dev)->devices[pci_dev->devfn] = NULL;
1007     pci_config_free(pci_dev);
1008 
1009     if (xen_mode == XEN_EMULATE) {
1010         xen_evtchn_remove_pci_device(pci_dev);
1011     }
1012     if (memory_region_is_mapped(&pci_dev->bus_master_enable_region)) {
1013         memory_region_del_subregion(&pci_dev->bus_master_container_region,
1014                                     &pci_dev->bus_master_enable_region);
1015     }
1016     address_space_destroy(&pci_dev->bus_master_as);
1017 }
1018 
1019 /* Extract PCIReqIDCache into BDF format */
1020 static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
1021 {
1022     uint8_t bus_n;
1023     uint16_t result;
1024 
1025     switch (cache->type) {
1026     case PCI_REQ_ID_BDF:
1027         result = pci_get_bdf(cache->dev);
1028         break;
1029     case PCI_REQ_ID_SECONDARY_BUS:
1030         bus_n = pci_dev_bus_num(cache->dev);
1031         result = PCI_BUILD_BDF(bus_n, 0);
1032         break;
1033     default:
1034         error_report("Invalid PCI requester ID cache type: %d",
1035                      cache->type);
1036         exit(1);
1037         break;
1038     }
1039 
1040     return result;
1041 }
1042 
1043 /* Parse bridges up to the root complex and return requester ID
1044  * cache for specific device.  For full PCIe topology, the cache
1045  * result would be exactly the same as getting BDF of the device.
1046  * However, several tricks are required when system mixed up with
1047  * legacy PCI devices and PCIe-to-PCI bridges.
1048  *
1049  * Here we cache the proxy device (and type) not requester ID since
1050  * bus number might change from time to time.
1051  */
1052 static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
1053 {
1054     PCIDevice *parent;
1055     PCIReqIDCache cache = {
1056         .dev = dev,
1057         .type = PCI_REQ_ID_BDF,
1058     };
1059 
1060     while (!pci_bus_is_root(pci_get_bus(dev))) {
1061         /* We are under PCI/PCIe bridges */
1062         parent = pci_get_bus(dev)->parent_dev;
1063         if (pci_is_express(parent)) {
1064             if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
1065                 /* When we pass through PCIe-to-PCI/PCIX bridges, we
1066                  * override the requester ID using secondary bus
1067                  * number of parent bridge with zeroed devfn
1068                  * (pcie-to-pci bridge spec chap 2.3). */
1069                 cache.type = PCI_REQ_ID_SECONDARY_BUS;
1070                 cache.dev = dev;
1071             }
1072         } else {
1073             /* Legacy PCI, override requester ID with the bridge's
1074              * BDF upstream.  When the root complex connects to
1075              * legacy PCI devices (including buses), it can only
1076              * obtain requester ID info from directly attached
1077              * devices.  If devices are attached under bridges, only
1078              * the requester ID of the bridge that is directly
1079              * attached to the root complex can be recognized. */
1080             cache.type = PCI_REQ_ID_BDF;
1081             cache.dev = parent;
1082         }
1083         dev = parent;
1084     }
1085 
1086     return cache;
1087 }
1088 
1089 uint16_t pci_requester_id(PCIDevice *dev)
1090 {
1091     return pci_req_id_cache_extract(&dev->requester_id_cache);
1092 }
1093 
1094 static bool pci_bus_devfn_available(PCIBus *bus, int devfn)
1095 {
1096     return !(bus->devices[devfn]);
1097 }
1098 
1099 static bool pci_bus_devfn_reserved(PCIBus *bus, int devfn)
1100 {
1101     return bus->slot_reserved_mask & (1UL << PCI_SLOT(devfn));
1102 }
1103 
1104 /* -1 for devfn means auto assign */
1105 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev,
1106                                          const char *name, int devfn,
1107                                          Error **errp)
1108 {
1109     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1110     PCIConfigReadFunc *config_read = pc->config_read;
1111     PCIConfigWriteFunc *config_write = pc->config_write;
1112     Error *local_err = NULL;
1113     DeviceState *dev = DEVICE(pci_dev);
1114     PCIBus *bus = pci_get_bus(pci_dev);
1115     bool is_bridge = IS_PCI_BRIDGE(pci_dev);
1116 
1117     /* Only pci bridges can be attached to extra PCI root buses */
1118     if (pci_bus_is_root(bus) && bus->parent_dev && !is_bridge) {
1119         error_setg(errp,
1120                    "PCI: Only PCI/PCIe bridges can be plugged into %s",
1121                     bus->parent_dev->name);
1122         return NULL;
1123     }
1124 
1125     if (devfn < 0) {
1126         for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
1127             devfn += PCI_FUNC_MAX) {
1128             if (pci_bus_devfn_available(bus, devfn) &&
1129                    !pci_bus_devfn_reserved(bus, devfn)) {
1130                 goto found;
1131             }
1132         }
1133         error_setg(errp, "PCI: no slot/function available for %s, all in use "
1134                    "or reserved", name);
1135         return NULL;
1136     found: ;
1137     } else if (pci_bus_devfn_reserved(bus, devfn)) {
1138         error_setg(errp, "PCI: slot %d function %d not available for %s,"
1139                    " reserved",
1140                    PCI_SLOT(devfn), PCI_FUNC(devfn), name);
1141         return NULL;
1142     } else if (!pci_bus_devfn_available(bus, devfn)) {
1143         error_setg(errp, "PCI: slot %d function %d not available for %s,"
1144                    " in use by %s,id=%s",
1145                    PCI_SLOT(devfn), PCI_FUNC(devfn), name,
1146                    bus->devices[devfn]->name, bus->devices[devfn]->qdev.id);
1147         return NULL;
1148     } else if (dev->hotplugged &&
1149                !pci_is_vf(pci_dev) &&
1150                pci_get_function_0(pci_dev)) {
1151         error_setg(errp, "PCI: slot %d function 0 already occupied by %s,"
1152                    " new func %s cannot be exposed to guest.",
1153                    PCI_SLOT(pci_get_function_0(pci_dev)->devfn),
1154                    pci_get_function_0(pci_dev)->name,
1155                    name);
1156 
1157        return NULL;
1158     }
1159 
1160     pci_dev->devfn = devfn;
1161     pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
1162     pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
1163 
1164     memory_region_init(&pci_dev->bus_master_container_region, OBJECT(pci_dev),
1165                        "bus master container", UINT64_MAX);
1166     address_space_init(&pci_dev->bus_master_as,
1167                        &pci_dev->bus_master_container_region, pci_dev->name);
1168 
1169     if (phase_check(PHASE_MACHINE_READY)) {
1170         pci_init_bus_master(pci_dev);
1171     }
1172     pci_dev->irq_state = 0;
1173     pci_config_alloc(pci_dev);
1174 
1175     pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
1176     pci_config_set_device_id(pci_dev->config, pc->device_id);
1177     pci_config_set_revision(pci_dev->config, pc->revision);
1178     pci_config_set_class(pci_dev->config, pc->class_id);
1179 
1180     if (!is_bridge) {
1181         if (pc->subsystem_vendor_id || pc->subsystem_id) {
1182             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
1183                          pc->subsystem_vendor_id);
1184             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
1185                          pc->subsystem_id);
1186         } else {
1187             pci_set_default_subsystem_id(pci_dev);
1188         }
1189     } else {
1190         /* subsystem_vendor_id/subsystem_id are only for header type 0 */
1191         assert(!pc->subsystem_vendor_id);
1192         assert(!pc->subsystem_id);
1193     }
1194     pci_init_cmask(pci_dev);
1195     pci_init_wmask(pci_dev);
1196     pci_init_w1cmask(pci_dev);
1197     if (is_bridge) {
1198         pci_init_mask_bridge(pci_dev);
1199     }
1200     pci_init_multifunction(bus, pci_dev, &local_err);
1201     if (local_err) {
1202         error_propagate(errp, local_err);
1203         do_pci_unregister_device(pci_dev);
1204         return NULL;
1205     }
1206 
1207     if (!config_read)
1208         config_read = pci_default_read_config;
1209     if (!config_write)
1210         config_write = pci_default_write_config;
1211     pci_dev->config_read = config_read;
1212     pci_dev->config_write = config_write;
1213     bus->devices[devfn] = pci_dev;
1214     pci_dev->version_id = 2; /* Current pci device vmstate version */
1215     return pci_dev;
1216 }
1217 
1218 static void pci_unregister_io_regions(PCIDevice *pci_dev)
1219 {
1220     PCIIORegion *r;
1221     int i;
1222 
1223     for(i = 0; i < PCI_NUM_REGIONS; i++) {
1224         r = &pci_dev->io_regions[i];
1225         if (!r->size || r->addr == PCI_BAR_UNMAPPED)
1226             continue;
1227         memory_region_del_subregion(r->address_space, r->memory);
1228     }
1229 
1230     pci_unregister_vga(pci_dev);
1231 }
1232 
1233 static void pci_qdev_unrealize(DeviceState *dev)
1234 {
1235     PCIDevice *pci_dev = PCI_DEVICE(dev);
1236     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1237 
1238     pci_unregister_io_regions(pci_dev);
1239     pci_del_option_rom(pci_dev);
1240 
1241     if (pc->exit) {
1242         pc->exit(pci_dev);
1243     }
1244 
1245     pci_device_deassert_intx(pci_dev);
1246     do_pci_unregister_device(pci_dev);
1247 
1248     pci_dev->msi_trigger = NULL;
1249 }
1250 
1251 void pci_register_bar(PCIDevice *pci_dev, int region_num,
1252                       uint8_t type, MemoryRegion *memory)
1253 {
1254     PCIIORegion *r;
1255     uint32_t addr; /* offset in pci config space */
1256     uint64_t wmask;
1257     pcibus_t size = memory_region_size(memory);
1258     uint8_t hdr_type;
1259 
1260     assert(!pci_is_vf(pci_dev)); /* VFs must use pcie_sriov_vf_register_bar */
1261     assert(region_num >= 0);
1262     assert(region_num < PCI_NUM_REGIONS);
1263     assert(is_power_of_2(size));
1264 
1265     /* A PCI bridge device (with Type 1 header) may only have at most 2 BARs */
1266     hdr_type =
1267         pci_dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1268     assert(hdr_type != PCI_HEADER_TYPE_BRIDGE || region_num < 2);
1269 
1270     r = &pci_dev->io_regions[region_num];
1271     r->addr = PCI_BAR_UNMAPPED;
1272     r->size = size;
1273     r->type = type;
1274     r->memory = memory;
1275     r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO
1276                         ? pci_get_bus(pci_dev)->address_space_io
1277                         : pci_get_bus(pci_dev)->address_space_mem;
1278 
1279     wmask = ~(size - 1);
1280     if (region_num == PCI_ROM_SLOT) {
1281         /* ROM enable bit is writable */
1282         wmask |= PCI_ROM_ADDRESS_ENABLE;
1283     }
1284 
1285     addr = pci_bar(pci_dev, region_num);
1286     pci_set_long(pci_dev->config + addr, type);
1287 
1288     if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1289         r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1290         pci_set_quad(pci_dev->wmask + addr, wmask);
1291         pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1292     } else {
1293         pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1294         pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1295     }
1296 }
1297 
1298 static void pci_update_vga(PCIDevice *pci_dev)
1299 {
1300     uint16_t cmd;
1301 
1302     if (!pci_dev->has_vga) {
1303         return;
1304     }
1305 
1306     cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1307 
1308     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1309                               cmd & PCI_COMMAND_MEMORY);
1310     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1311                               cmd & PCI_COMMAND_IO);
1312     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1313                               cmd & PCI_COMMAND_IO);
1314 }
1315 
1316 void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1317                       MemoryRegion *io_lo, MemoryRegion *io_hi)
1318 {
1319     PCIBus *bus = pci_get_bus(pci_dev);
1320 
1321     assert(!pci_dev->has_vga);
1322 
1323     assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1324     pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1325     memory_region_add_subregion_overlap(bus->address_space_mem,
1326                                         QEMU_PCI_VGA_MEM_BASE, mem, 1);
1327 
1328     assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1329     pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1330     memory_region_add_subregion_overlap(bus->address_space_io,
1331                                         QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1332 
1333     assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1334     pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1335     memory_region_add_subregion_overlap(bus->address_space_io,
1336                                         QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1337     pci_dev->has_vga = true;
1338 
1339     pci_update_vga(pci_dev);
1340 }
1341 
1342 void pci_unregister_vga(PCIDevice *pci_dev)
1343 {
1344     PCIBus *bus = pci_get_bus(pci_dev);
1345 
1346     if (!pci_dev->has_vga) {
1347         return;
1348     }
1349 
1350     memory_region_del_subregion(bus->address_space_mem,
1351                                 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1352     memory_region_del_subregion(bus->address_space_io,
1353                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1354     memory_region_del_subregion(bus->address_space_io,
1355                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1356     pci_dev->has_vga = false;
1357 }
1358 
1359 pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1360 {
1361     return pci_dev->io_regions[region_num].addr;
1362 }
1363 
1364 static pcibus_t pci_config_get_bar_addr(PCIDevice *d, int reg,
1365                                         uint8_t type, pcibus_t size)
1366 {
1367     pcibus_t new_addr;
1368     if (!pci_is_vf(d)) {
1369         int bar = pci_bar(d, reg);
1370         if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1371             new_addr = pci_get_quad(d->config + bar);
1372         } else {
1373             new_addr = pci_get_long(d->config + bar);
1374         }
1375     } else {
1376         PCIDevice *pf = d->exp.sriov_vf.pf;
1377         uint16_t sriov_cap = pf->exp.sriov_cap;
1378         int bar = sriov_cap + PCI_SRIOV_BAR + reg * 4;
1379         uint16_t vf_offset =
1380             pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_OFFSET);
1381         uint16_t vf_stride =
1382             pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_STRIDE);
1383         uint32_t vf_num = (d->devfn - (pf->devfn + vf_offset)) / vf_stride;
1384 
1385         if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1386             new_addr = pci_get_quad(pf->config + bar);
1387         } else {
1388             new_addr = pci_get_long(pf->config + bar);
1389         }
1390         new_addr += vf_num * size;
1391     }
1392     /* The ROM slot has a specific enable bit, keep it intact */
1393     if (reg != PCI_ROM_SLOT) {
1394         new_addr &= ~(size - 1);
1395     }
1396     return new_addr;
1397 }
1398 
1399 pcibus_t pci_bar_address(PCIDevice *d,
1400                          int reg, uint8_t type, pcibus_t size)
1401 {
1402     pcibus_t new_addr, last_addr;
1403     uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1404     Object *machine = qdev_get_machine();
1405     ObjectClass *oc = object_get_class(machine);
1406     MachineClass *mc = MACHINE_CLASS(oc);
1407     bool allow_0_address = mc->pci_allow_0_address;
1408 
1409     if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1410         if (!(cmd & PCI_COMMAND_IO)) {
1411             return PCI_BAR_UNMAPPED;
1412         }
1413         new_addr = pci_config_get_bar_addr(d, reg, type, size);
1414         last_addr = new_addr + size - 1;
1415         /* Check if 32 bit BAR wraps around explicitly.
1416          * TODO: make priorities correct and remove this work around.
1417          */
1418         if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1419             (!allow_0_address && new_addr == 0)) {
1420             return PCI_BAR_UNMAPPED;
1421         }
1422         return new_addr;
1423     }
1424 
1425     if (!(cmd & PCI_COMMAND_MEMORY)) {
1426         return PCI_BAR_UNMAPPED;
1427     }
1428     new_addr = pci_config_get_bar_addr(d, reg, type, size);
1429     /* the ROM slot has a specific enable bit */
1430     if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1431         return PCI_BAR_UNMAPPED;
1432     }
1433     new_addr &= ~(size - 1);
1434     last_addr = new_addr + size - 1;
1435     /* NOTE: we do not support wrapping */
1436     /* XXX: as we cannot support really dynamic
1437        mappings, we handle specific values as invalid
1438        mappings. */
1439     if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1440         (!allow_0_address && new_addr == 0)) {
1441         return PCI_BAR_UNMAPPED;
1442     }
1443 
1444     /* Now pcibus_t is 64bit.
1445      * Check if 32 bit BAR wraps around explicitly.
1446      * Without this, PC ide doesn't work well.
1447      * TODO: remove this work around.
1448      */
1449     if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1450         return PCI_BAR_UNMAPPED;
1451     }
1452 
1453     /*
1454      * OS is allowed to set BAR beyond its addressable
1455      * bits. For example, 32 bit OS can set 64bit bar
1456      * to >4G. Check it. TODO: we might need to support
1457      * it in the future for e.g. PAE.
1458      */
1459     if (last_addr >= HWADDR_MAX) {
1460         return PCI_BAR_UNMAPPED;
1461     }
1462 
1463     return new_addr;
1464 }
1465 
1466 static void pci_update_mappings(PCIDevice *d)
1467 {
1468     PCIIORegion *r;
1469     int i;
1470     pcibus_t new_addr;
1471 
1472     for(i = 0; i < PCI_NUM_REGIONS; i++) {
1473         r = &d->io_regions[i];
1474 
1475         /* this region isn't registered */
1476         if (!r->size)
1477             continue;
1478 
1479         new_addr = pci_bar_address(d, i, r->type, r->size);
1480         if (!d->has_power) {
1481             new_addr = PCI_BAR_UNMAPPED;
1482         }
1483 
1484         /* This bar isn't changed */
1485         if (new_addr == r->addr)
1486             continue;
1487 
1488         /* now do the real mapping */
1489         if (r->addr != PCI_BAR_UNMAPPED) {
1490             trace_pci_update_mappings_del(d->name, pci_dev_bus_num(d),
1491                                           PCI_SLOT(d->devfn),
1492                                           PCI_FUNC(d->devfn),
1493                                           i, r->addr, r->size);
1494             memory_region_del_subregion(r->address_space, r->memory);
1495         }
1496         r->addr = new_addr;
1497         if (r->addr != PCI_BAR_UNMAPPED) {
1498             trace_pci_update_mappings_add(d->name, pci_dev_bus_num(d),
1499                                           PCI_SLOT(d->devfn),
1500                                           PCI_FUNC(d->devfn),
1501                                           i, r->addr, r->size);
1502             memory_region_add_subregion_overlap(r->address_space,
1503                                                 r->addr, r->memory, 1);
1504         }
1505     }
1506 
1507     pci_update_vga(d);
1508 }
1509 
1510 static inline int pci_irq_disabled(PCIDevice *d)
1511 {
1512     return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1513 }
1514 
1515 /* Called after interrupt disabled field update in config space,
1516  * assert/deassert interrupts if necessary.
1517  * Gets original interrupt disable bit value (before update). */
1518 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1519 {
1520     int i, disabled = pci_irq_disabled(d);
1521     if (disabled == was_irq_disabled)
1522         return;
1523     for (i = 0; i < PCI_NUM_PINS; ++i) {
1524         int state = pci_irq_state(d, i);
1525         pci_change_irq_level(d, i, disabled ? -state : state);
1526     }
1527 }
1528 
1529 uint32_t pci_default_read_config(PCIDevice *d,
1530                                  uint32_t address, int len)
1531 {
1532     uint32_t val = 0;
1533 
1534     assert(address + len <= pci_config_size(d));
1535 
1536     if (pci_is_express_downstream_port(d) &&
1537         ranges_overlap(address, len, d->exp.exp_cap + PCI_EXP_LNKSTA, 2)) {
1538         pcie_sync_bridge_lnk(d);
1539     }
1540     memcpy(&val, d->config + address, len);
1541     return le32_to_cpu(val);
1542 }
1543 
1544 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1545 {
1546     int i, was_irq_disabled = pci_irq_disabled(d);
1547     uint32_t val = val_in;
1548 
1549     assert(addr + l <= pci_config_size(d));
1550 
1551     for (i = 0; i < l; val >>= 8, ++i) {
1552         uint8_t wmask = d->wmask[addr + i];
1553         uint8_t w1cmask = d->w1cmask[addr + i];
1554         assert(!(wmask & w1cmask));
1555         d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1556         d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1557     }
1558     if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1559         ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1560         ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1561         range_covers_byte(addr, l, PCI_COMMAND))
1562         pci_update_mappings(d);
1563 
1564     if (range_covers_byte(addr, l, PCI_COMMAND)) {
1565         pci_update_irq_disabled(d, was_irq_disabled);
1566         memory_region_set_enabled(&d->bus_master_enable_region,
1567                                   (pci_get_word(d->config + PCI_COMMAND)
1568                                    & PCI_COMMAND_MASTER) && d->has_power);
1569     }
1570 
1571     msi_write_config(d, addr, val_in, l);
1572     msix_write_config(d, addr, val_in, l);
1573     pcie_sriov_config_write(d, addr, val_in, l);
1574 }
1575 
1576 /***********************************************************/
1577 /* generic PCI irq support */
1578 
1579 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1580 static void pci_irq_handler(void *opaque, int irq_num, int level)
1581 {
1582     PCIDevice *pci_dev = opaque;
1583     int change;
1584 
1585     assert(0 <= irq_num && irq_num < PCI_NUM_PINS);
1586     assert(level == 0 || level == 1);
1587     change = level - pci_irq_state(pci_dev, irq_num);
1588     if (!change)
1589         return;
1590 
1591     pci_set_irq_state(pci_dev, irq_num, level);
1592     pci_update_irq_status(pci_dev);
1593     if (pci_irq_disabled(pci_dev))
1594         return;
1595     pci_change_irq_level(pci_dev, irq_num, change);
1596 }
1597 
1598 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1599 {
1600     int intx = pci_intx(pci_dev);
1601     assert(0 <= intx && intx < PCI_NUM_PINS);
1602 
1603     return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1604 }
1605 
1606 void pci_set_irq(PCIDevice *pci_dev, int level)
1607 {
1608     int intx = pci_intx(pci_dev);
1609     pci_irq_handler(pci_dev, intx, level);
1610 }
1611 
1612 /* Special hooks used by device assignment */
1613 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1614 {
1615     assert(pci_bus_is_root(bus));
1616     bus->route_intx_to_irq = route_intx_to_irq;
1617 }
1618 
1619 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1620 {
1621     PCIBus *bus;
1622 
1623     do {
1624         int dev_irq = pin;
1625         bus = pci_get_bus(dev);
1626         pin = bus->map_irq(dev, pin);
1627         trace_pci_route_irq(dev_irq, DEVICE(dev)->canonical_path, pin,
1628                             pci_bus_is_root(bus) ? "root-complex"
1629                                     : DEVICE(bus->parent_dev)->canonical_path);
1630         dev = bus->parent_dev;
1631     } while (dev);
1632 
1633     if (!bus->route_intx_to_irq) {
1634         error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1635                      object_get_typename(OBJECT(bus->qbus.parent)));
1636         return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1637     }
1638 
1639     return bus->route_intx_to_irq(bus->irq_opaque, pin);
1640 }
1641 
1642 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1643 {
1644     return old->mode != new->mode || old->irq != new->irq;
1645 }
1646 
1647 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1648 {
1649     PCIDevice *dev;
1650     PCIBus *sec;
1651     int i;
1652 
1653     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1654         dev = bus->devices[i];
1655         if (dev && dev->intx_routing_notifier) {
1656             dev->intx_routing_notifier(dev);
1657         }
1658     }
1659 
1660     QLIST_FOREACH(sec, &bus->child, sibling) {
1661         pci_bus_fire_intx_routing_notifier(sec);
1662     }
1663 }
1664 
1665 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1666                                           PCIINTxRoutingNotifier notifier)
1667 {
1668     dev->intx_routing_notifier = notifier;
1669 }
1670 
1671 /*
1672  * PCI-to-PCI bridge specification
1673  * 9.1: Interrupt routing. Table 9-1
1674  *
1675  * the PCI Express Base Specification, Revision 2.1
1676  * 2.2.8.1: INTx interrupt signaling - Rules
1677  *          the Implementation Note
1678  *          Table 2-20
1679  */
1680 /*
1681  * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1682  * 0-origin unlike PCI interrupt pin register.
1683  */
1684 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1685 {
1686     return pci_swizzle(PCI_SLOT(pci_dev->devfn), pin);
1687 }
1688 
1689 /***********************************************************/
1690 /* monitor info on PCI */
1691 
1692 static const pci_class_desc pci_class_descriptions[] =
1693 {
1694     { 0x0001, "VGA controller", "display"},
1695     { 0x0100, "SCSI controller", "scsi"},
1696     { 0x0101, "IDE controller", "ide"},
1697     { 0x0102, "Floppy controller", "fdc"},
1698     { 0x0103, "IPI controller", "ipi"},
1699     { 0x0104, "RAID controller", "raid"},
1700     { 0x0106, "SATA controller"},
1701     { 0x0107, "SAS controller"},
1702     { 0x0180, "Storage controller"},
1703     { 0x0200, "Ethernet controller", "ethernet"},
1704     { 0x0201, "Token Ring controller", "token-ring"},
1705     { 0x0202, "FDDI controller", "fddi"},
1706     { 0x0203, "ATM controller", "atm"},
1707     { 0x0280, "Network controller"},
1708     { 0x0300, "VGA controller", "display", 0x00ff},
1709     { 0x0301, "XGA controller"},
1710     { 0x0302, "3D controller"},
1711     { 0x0380, "Display controller"},
1712     { 0x0400, "Video controller", "video"},
1713     { 0x0401, "Audio controller", "sound"},
1714     { 0x0402, "Phone"},
1715     { 0x0403, "Audio controller", "sound"},
1716     { 0x0480, "Multimedia controller"},
1717     { 0x0500, "RAM controller", "memory"},
1718     { 0x0501, "Flash controller", "flash"},
1719     { 0x0580, "Memory controller"},
1720     { 0x0600, "Host bridge", "host"},
1721     { 0x0601, "ISA bridge", "isa"},
1722     { 0x0602, "EISA bridge", "eisa"},
1723     { 0x0603, "MC bridge", "mca"},
1724     { 0x0604, "PCI bridge", "pci-bridge"},
1725     { 0x0605, "PCMCIA bridge", "pcmcia"},
1726     { 0x0606, "NUBUS bridge", "nubus"},
1727     { 0x0607, "CARDBUS bridge", "cardbus"},
1728     { 0x0608, "RACEWAY bridge"},
1729     { 0x0680, "Bridge"},
1730     { 0x0700, "Serial port", "serial"},
1731     { 0x0701, "Parallel port", "parallel"},
1732     { 0x0800, "Interrupt controller", "interrupt-controller"},
1733     { 0x0801, "DMA controller", "dma-controller"},
1734     { 0x0802, "Timer", "timer"},
1735     { 0x0803, "RTC", "rtc"},
1736     { 0x0900, "Keyboard", "keyboard"},
1737     { 0x0901, "Pen", "pen"},
1738     { 0x0902, "Mouse", "mouse"},
1739     { 0x0A00, "Dock station", "dock", 0x00ff},
1740     { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1741     { 0x0c00, "Firewire controller", "firewire"},
1742     { 0x0c01, "Access bus controller", "access-bus"},
1743     { 0x0c02, "SSA controller", "ssa"},
1744     { 0x0c03, "USB controller", "usb"},
1745     { 0x0c04, "Fibre channel controller", "fibre-channel"},
1746     { 0x0c05, "SMBus"},
1747     { 0, NULL}
1748 };
1749 
1750 void pci_for_each_device_under_bus_reverse(PCIBus *bus,
1751                                            pci_bus_dev_fn fn,
1752                                            void *opaque)
1753 {
1754     PCIDevice *d;
1755     int devfn;
1756 
1757     for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1758         d = bus->devices[ARRAY_SIZE(bus->devices) - 1 - devfn];
1759         if (d) {
1760             fn(bus, d, opaque);
1761         }
1762     }
1763 }
1764 
1765 void pci_for_each_device_reverse(PCIBus *bus, int bus_num,
1766                                  pci_bus_dev_fn fn, void *opaque)
1767 {
1768     bus = pci_find_bus_nr(bus, bus_num);
1769 
1770     if (bus) {
1771         pci_for_each_device_under_bus_reverse(bus, fn, opaque);
1772     }
1773 }
1774 
1775 void pci_for_each_device_under_bus(PCIBus *bus,
1776                                    pci_bus_dev_fn fn, void *opaque)
1777 {
1778     PCIDevice *d;
1779     int devfn;
1780 
1781     for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1782         d = bus->devices[devfn];
1783         if (d) {
1784             fn(bus, d, opaque);
1785         }
1786     }
1787 }
1788 
1789 void pci_for_each_device(PCIBus *bus, int bus_num,
1790                          pci_bus_dev_fn fn, void *opaque)
1791 {
1792     bus = pci_find_bus_nr(bus, bus_num);
1793 
1794     if (bus) {
1795         pci_for_each_device_under_bus(bus, fn, opaque);
1796     }
1797 }
1798 
1799 const pci_class_desc *get_class_desc(int class)
1800 {
1801     const pci_class_desc *desc;
1802 
1803     desc = pci_class_descriptions;
1804     while (desc->desc && class != desc->class) {
1805         desc++;
1806     }
1807 
1808     return desc;
1809 }
1810 
1811 /* Initialize a PCI NIC.  */
1812 PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1813                                const char *default_model,
1814                                const char *default_devaddr)
1815 {
1816     const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1817     GPtrArray *pci_nic_models;
1818     PCIBus *bus;
1819     PCIDevice *pci_dev;
1820     DeviceState *dev;
1821     int devfn;
1822     int i;
1823     int dom, busnr;
1824     unsigned slot;
1825 
1826     if (nd->model && !strcmp(nd->model, "virtio")) {
1827         g_free(nd->model);
1828         nd->model = g_strdup("virtio-net-pci");
1829     }
1830 
1831     pci_nic_models = qemu_get_nic_models(TYPE_PCI_DEVICE);
1832 
1833     if (qemu_show_nic_models(nd->model, (const char **)pci_nic_models->pdata)) {
1834         exit(0);
1835     }
1836 
1837     i = qemu_find_nic_model(nd, (const char **)pci_nic_models->pdata,
1838                             default_model);
1839     if (i < 0) {
1840         exit(1);
1841     }
1842 
1843     if (!rootbus) {
1844         error_report("No primary PCI bus");
1845         exit(1);
1846     }
1847 
1848     assert(!rootbus->parent_dev);
1849 
1850     if (!devaddr) {
1851         devfn = -1;
1852         busnr = 0;
1853     } else {
1854         if (pci_parse_devaddr(devaddr, &dom, &busnr, &slot, NULL) < 0) {
1855             error_report("Invalid PCI device address %s for device %s",
1856                          devaddr, nd->model);
1857             exit(1);
1858         }
1859 
1860         if (dom != 0) {
1861             error_report("No support for non-zero PCI domains");
1862             exit(1);
1863         }
1864 
1865         devfn = PCI_DEVFN(slot, 0);
1866     }
1867 
1868     bus = pci_find_bus_nr(rootbus, busnr);
1869     if (!bus) {
1870         error_report("Invalid PCI device address %s for device %s",
1871                      devaddr, nd->model);
1872         exit(1);
1873     }
1874 
1875     pci_dev = pci_new(devfn, nd->model);
1876     dev = &pci_dev->qdev;
1877     qdev_set_nic_properties(dev, nd);
1878     pci_realize_and_unref(pci_dev, bus, &error_fatal);
1879     g_ptr_array_free(pci_nic_models, true);
1880     return pci_dev;
1881 }
1882 
1883 PCIDevice *pci_vga_init(PCIBus *bus)
1884 {
1885     vga_interface_created = true;
1886     switch (vga_interface_type) {
1887     case VGA_CIRRUS:
1888         return pci_create_simple(bus, -1, "cirrus-vga");
1889     case VGA_QXL:
1890         return pci_create_simple(bus, -1, "qxl-vga");
1891     case VGA_STD:
1892         return pci_create_simple(bus, -1, "VGA");
1893     case VGA_VMWARE:
1894         return pci_create_simple(bus, -1, "vmware-svga");
1895     case VGA_VIRTIO:
1896         return pci_create_simple(bus, -1, "virtio-vga");
1897     case VGA_NONE:
1898     default: /* Other non-PCI types. Checking for unsupported types is already
1899                 done in vl.c. */
1900         return NULL;
1901     }
1902 }
1903 
1904 /* Whether a given bus number is in range of the secondary
1905  * bus of the given bridge device. */
1906 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1907 {
1908     return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1909              PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1910         dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1911         bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1912 }
1913 
1914 /* Whether a given bus number is in a range of a root bus */
1915 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1916 {
1917     int i;
1918 
1919     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1920         PCIDevice *dev = bus->devices[i];
1921 
1922         if (dev && IS_PCI_BRIDGE(dev)) {
1923             if (pci_secondary_bus_in_range(dev, bus_num)) {
1924                 return true;
1925             }
1926         }
1927     }
1928 
1929     return false;
1930 }
1931 
1932 PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1933 {
1934     PCIBus *sec;
1935 
1936     if (!bus) {
1937         return NULL;
1938     }
1939 
1940     if (pci_bus_num(bus) == bus_num) {
1941         return bus;
1942     }
1943 
1944     /* Consider all bus numbers in range for the host pci bridge. */
1945     if (!pci_bus_is_root(bus) &&
1946         !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1947         return NULL;
1948     }
1949 
1950     /* try child bus */
1951     for (; bus; bus = sec) {
1952         QLIST_FOREACH(sec, &bus->child, sibling) {
1953             if (pci_bus_num(sec) == bus_num) {
1954                 return sec;
1955             }
1956             /* PXB buses assumed to be children of bus 0 */
1957             if (pci_bus_is_root(sec)) {
1958                 if (pci_root_bus_in_range(sec, bus_num)) {
1959                     break;
1960                 }
1961             } else {
1962                 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1963                     break;
1964                 }
1965             }
1966         }
1967     }
1968 
1969     return NULL;
1970 }
1971 
1972 void pci_for_each_bus_depth_first(PCIBus *bus, pci_bus_ret_fn begin,
1973                                   pci_bus_fn end, void *parent_state)
1974 {
1975     PCIBus *sec;
1976     void *state;
1977 
1978     if (!bus) {
1979         return;
1980     }
1981 
1982     if (begin) {
1983         state = begin(bus, parent_state);
1984     } else {
1985         state = parent_state;
1986     }
1987 
1988     QLIST_FOREACH(sec, &bus->child, sibling) {
1989         pci_for_each_bus_depth_first(sec, begin, end, state);
1990     }
1991 
1992     if (end) {
1993         end(bus, state);
1994     }
1995 }
1996 
1997 
1998 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1999 {
2000     bus = pci_find_bus_nr(bus, bus_num);
2001 
2002     if (!bus)
2003         return NULL;
2004 
2005     return bus->devices[devfn];
2006 }
2007 
2008 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
2009 {
2010     PCIDevice *pci_dev = (PCIDevice *)qdev;
2011     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
2012     ObjectClass *klass = OBJECT_CLASS(pc);
2013     Error *local_err = NULL;
2014     bool is_default_rom;
2015     uint16_t class_id;
2016 
2017     if (pci_dev->romsize != -1 && !is_power_of_2(pci_dev->romsize)) {
2018         error_setg(errp, "ROM size %u is not a power of two", pci_dev->romsize);
2019         return;
2020     }
2021 
2022     /* initialize cap_present for pci_is_express() and pci_config_size(),
2023      * Note that hybrid PCIs are not set automatically and need to manage
2024      * QEMU_PCI_CAP_EXPRESS manually */
2025     if (object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE) &&
2026        !object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE)) {
2027         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2028     }
2029 
2030     if (object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE)) {
2031         pci_dev->cap_present |= QEMU_PCIE_CAP_CXL;
2032     }
2033 
2034     pci_dev = do_pci_register_device(pci_dev,
2035                                      object_get_typename(OBJECT(qdev)),
2036                                      pci_dev->devfn, errp);
2037     if (pci_dev == NULL)
2038         return;
2039 
2040     if (pc->realize) {
2041         pc->realize(pci_dev, &local_err);
2042         if (local_err) {
2043             error_propagate(errp, local_err);
2044             do_pci_unregister_device(pci_dev);
2045             return;
2046         }
2047     }
2048 
2049     if (pci_dev->failover_pair_id) {
2050         if (!pci_bus_is_express(pci_get_bus(pci_dev))) {
2051             error_setg(errp, "failover primary device must be on "
2052                              "PCIExpress bus");
2053             pci_qdev_unrealize(DEVICE(pci_dev));
2054             return;
2055         }
2056         class_id = pci_get_word(pci_dev->config + PCI_CLASS_DEVICE);
2057         if (class_id != PCI_CLASS_NETWORK_ETHERNET) {
2058             error_setg(errp, "failover primary device is not an "
2059                              "Ethernet device");
2060             pci_qdev_unrealize(DEVICE(pci_dev));
2061             return;
2062         }
2063         if ((pci_dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)
2064             || (PCI_FUNC(pci_dev->devfn) != 0)) {
2065             error_setg(errp, "failover: primary device must be in its own "
2066                               "PCI slot");
2067             pci_qdev_unrealize(DEVICE(pci_dev));
2068             return;
2069         }
2070         qdev->allow_unplug_during_migration = true;
2071     }
2072 
2073     /* rom loading */
2074     is_default_rom = false;
2075     if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2076         pci_dev->romfile = g_strdup(pc->romfile);
2077         is_default_rom = true;
2078     }
2079 
2080     pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2081     if (local_err) {
2082         error_propagate(errp, local_err);
2083         pci_qdev_unrealize(DEVICE(pci_dev));
2084         return;
2085     }
2086 
2087     pci_set_power(pci_dev, true);
2088 
2089     pci_dev->msi_trigger = pci_msi_trigger;
2090 }
2091 
2092 PCIDevice *pci_new_multifunction(int devfn, bool multifunction,
2093                                  const char *name)
2094 {
2095     DeviceState *dev;
2096 
2097     dev = qdev_new(name);
2098     qdev_prop_set_int32(dev, "addr", devfn);
2099     qdev_prop_set_bit(dev, "multifunction", multifunction);
2100     return PCI_DEVICE(dev);
2101 }
2102 
2103 PCIDevice *pci_new(int devfn, const char *name)
2104 {
2105     return pci_new_multifunction(devfn, false, name);
2106 }
2107 
2108 bool pci_realize_and_unref(PCIDevice *dev, PCIBus *bus, Error **errp)
2109 {
2110     return qdev_realize_and_unref(&dev->qdev, &bus->qbus, errp);
2111 }
2112 
2113 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2114                                            bool multifunction,
2115                                            const char *name)
2116 {
2117     PCIDevice *dev = pci_new_multifunction(devfn, multifunction, name);
2118     pci_realize_and_unref(dev, bus, &error_fatal);
2119     return dev;
2120 }
2121 
2122 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2123 {
2124     return pci_create_simple_multifunction(bus, devfn, false, name);
2125 }
2126 
2127 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2128 {
2129     int offset = PCI_CONFIG_HEADER_SIZE;
2130     int i;
2131     for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2132         if (pdev->used[i])
2133             offset = i + 1;
2134         else if (i - offset + 1 == size)
2135             return offset;
2136     }
2137     return 0;
2138 }
2139 
2140 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2141                                         uint8_t *prev_p)
2142 {
2143     uint8_t next, prev;
2144 
2145     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2146         return 0;
2147 
2148     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2149          prev = next + PCI_CAP_LIST_NEXT)
2150         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2151             break;
2152 
2153     if (prev_p)
2154         *prev_p = prev;
2155     return next;
2156 }
2157 
2158 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2159 {
2160     uint8_t next, prev, found = 0;
2161 
2162     if (!(pdev->used[offset])) {
2163         return 0;
2164     }
2165 
2166     assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2167 
2168     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2169          prev = next + PCI_CAP_LIST_NEXT) {
2170         if (next <= offset && next > found) {
2171             found = next;
2172         }
2173     }
2174     return found;
2175 }
2176 
2177 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2178    This is needed for an option rom which is used for more than one device. */
2179 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, uint32_t size)
2180 {
2181     uint16_t vendor_id;
2182     uint16_t device_id;
2183     uint16_t rom_vendor_id;
2184     uint16_t rom_device_id;
2185     uint16_t rom_magic;
2186     uint16_t pcir_offset;
2187     uint8_t checksum;
2188 
2189     /* Words in rom data are little endian (like in PCI configuration),
2190        so they can be read / written with pci_get_word / pci_set_word. */
2191 
2192     /* Only a valid rom will be patched. */
2193     rom_magic = pci_get_word(ptr);
2194     if (rom_magic != 0xaa55) {
2195         PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2196         return;
2197     }
2198     pcir_offset = pci_get_word(ptr + 0x18);
2199     if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2200         PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2201         return;
2202     }
2203 
2204     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2205     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2206     rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2207     rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2208 
2209     PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2210                 vendor_id, device_id, rom_vendor_id, rom_device_id);
2211 
2212     checksum = ptr[6];
2213 
2214     if (vendor_id != rom_vendor_id) {
2215         /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2216         checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2217         checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2218         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2219         ptr[6] = checksum;
2220         pci_set_word(ptr + pcir_offset + 4, vendor_id);
2221     }
2222 
2223     if (device_id != rom_device_id) {
2224         /* Patch device id and checksum (at offset 6 for etherboot roms). */
2225         checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2226         checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2227         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2228         ptr[6] = checksum;
2229         pci_set_word(ptr + pcir_offset + 6, device_id);
2230     }
2231 }
2232 
2233 /* Add an option rom for the device */
2234 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2235                                Error **errp)
2236 {
2237     int64_t size;
2238     char *path;
2239     void *ptr;
2240     char name[32];
2241     const VMStateDescription *vmsd;
2242 
2243     if (!pdev->romfile)
2244         return;
2245     if (strlen(pdev->romfile) == 0)
2246         return;
2247 
2248     if (!pdev->rom_bar) {
2249         /*
2250          * Load rom via fw_cfg instead of creating a rom bar,
2251          * for 0.11 compatibility.
2252          */
2253         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2254 
2255         /*
2256          * Hot-plugged devices can't use the option ROM
2257          * if the rom bar is disabled.
2258          */
2259         if (DEVICE(pdev)->hotplugged) {
2260             error_setg(errp, "Hot-plugged device without ROM bar"
2261                        " can't have an option ROM");
2262             return;
2263         }
2264 
2265         if (class == 0x0300) {
2266             rom_add_vga(pdev->romfile);
2267         } else {
2268             rom_add_option(pdev->romfile, -1);
2269         }
2270         return;
2271     }
2272 
2273     path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2274     if (path == NULL) {
2275         path = g_strdup(pdev->romfile);
2276     }
2277 
2278     size = get_image_size(path);
2279     if (size < 0) {
2280         error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2281         g_free(path);
2282         return;
2283     } else if (size == 0) {
2284         error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2285         g_free(path);
2286         return;
2287     } else if (size > 2 * GiB) {
2288         error_setg(errp, "romfile \"%s\" too large (size cannot exceed 2 GiB)",
2289                    pdev->romfile);
2290         g_free(path);
2291         return;
2292     }
2293     if (pdev->romsize != -1) {
2294         if (size > pdev->romsize) {
2295             error_setg(errp, "romfile \"%s\" (%u bytes) is too large for ROM size %u",
2296                        pdev->romfile, (uint32_t)size, pdev->romsize);
2297             g_free(path);
2298             return;
2299         }
2300     } else {
2301         pdev->romsize = pow2ceil(size);
2302     }
2303 
2304     vmsd = qdev_get_vmsd(DEVICE(pdev));
2305 
2306     if (vmsd) {
2307         snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2308     } else {
2309         snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2310     }
2311     pdev->has_rom = true;
2312     memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, pdev->romsize, &error_fatal);
2313     ptr = memory_region_get_ram_ptr(&pdev->rom);
2314     if (load_image_size(path, ptr, size) < 0) {
2315         error_setg(errp, "failed to load romfile \"%s\"", pdev->romfile);
2316         g_free(path);
2317         return;
2318     }
2319     g_free(path);
2320 
2321     if (is_default_rom) {
2322         /* Only the default rom images will be patched (if needed). */
2323         pci_patch_ids(pdev, ptr, size);
2324     }
2325 
2326     pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2327 }
2328 
2329 static void pci_del_option_rom(PCIDevice *pdev)
2330 {
2331     if (!pdev->has_rom)
2332         return;
2333 
2334     vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2335     pdev->has_rom = false;
2336 }
2337 
2338 /*
2339  * On success, pci_add_capability() returns a positive value
2340  * that the offset of the pci capability.
2341  * On failure, it sets an error and returns a negative error
2342  * code.
2343  */
2344 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2345                        uint8_t offset, uint8_t size,
2346                        Error **errp)
2347 {
2348     uint8_t *config;
2349     int i, overlapping_cap;
2350 
2351     if (!offset) {
2352         offset = pci_find_space(pdev, size);
2353         /* out of PCI config space is programming error */
2354         assert(offset);
2355     } else {
2356         /* Verify that capabilities don't overlap.  Note: device assignment
2357          * depends on this check to verify that the device is not broken.
2358          * Should never trigger for emulated devices, but it's helpful
2359          * for debugging these. */
2360         for (i = offset; i < offset + size; i++) {
2361             overlapping_cap = pci_find_capability_at_offset(pdev, i);
2362             if (overlapping_cap) {
2363                 error_setg(errp, "%s:%02x:%02x.%x "
2364                            "Attempt to add PCI capability %x at offset "
2365                            "%x overlaps existing capability %x at offset %x",
2366                            pci_root_bus_path(pdev), pci_dev_bus_num(pdev),
2367                            PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2368                            cap_id, offset, overlapping_cap, i);
2369                 return -EINVAL;
2370             }
2371         }
2372     }
2373 
2374     config = pdev->config + offset;
2375     config[PCI_CAP_LIST_ID] = cap_id;
2376     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2377     pdev->config[PCI_CAPABILITY_LIST] = offset;
2378     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2379     memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2380     /* Make capability read-only by default */
2381     memset(pdev->wmask + offset, 0, size);
2382     /* Check capability by default */
2383     memset(pdev->cmask + offset, 0xFF, size);
2384     return offset;
2385 }
2386 
2387 /* Unlink capability from the pci config space. */
2388 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2389 {
2390     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2391     if (!offset)
2392         return;
2393     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2394     /* Make capability writable again */
2395     memset(pdev->wmask + offset, 0xff, size);
2396     memset(pdev->w1cmask + offset, 0, size);
2397     /* Clear cmask as device-specific registers can't be checked */
2398     memset(pdev->cmask + offset, 0, size);
2399     memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2400 
2401     if (!pdev->config[PCI_CAPABILITY_LIST])
2402         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2403 }
2404 
2405 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2406 {
2407     return pci_find_capability_list(pdev, cap_id, NULL);
2408 }
2409 
2410 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2411 {
2412     PCIDevice *d = (PCIDevice *)dev;
2413     const char *name = NULL;
2414     const pci_class_desc *desc =  pci_class_descriptions;
2415     int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2416 
2417     while (desc->desc &&
2418           (class & ~desc->fw_ign_bits) !=
2419           (desc->class & ~desc->fw_ign_bits)) {
2420         desc++;
2421     }
2422 
2423     if (desc->desc) {
2424         name = desc->fw_name;
2425     }
2426 
2427     if (name) {
2428         pstrcpy(buf, len, name);
2429     } else {
2430         snprintf(buf, len, "pci%04x,%04x",
2431                  pci_get_word(d->config + PCI_VENDOR_ID),
2432                  pci_get_word(d->config + PCI_DEVICE_ID));
2433     }
2434 
2435     return buf;
2436 }
2437 
2438 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2439 {
2440     PCIDevice *d = (PCIDevice *)dev;
2441     char name[33];
2442     int has_func = !!PCI_FUNC(d->devfn);
2443 
2444     return g_strdup_printf("%s@%x%s%.*x",
2445                            pci_dev_fw_name(dev, name, sizeof(name)),
2446                            PCI_SLOT(d->devfn),
2447                            has_func ? "," : "",
2448                            has_func,
2449                            PCI_FUNC(d->devfn));
2450 }
2451 
2452 static char *pcibus_get_dev_path(DeviceState *dev)
2453 {
2454     PCIDevice *d = container_of(dev, PCIDevice, qdev);
2455     PCIDevice *t;
2456     int slot_depth;
2457     /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2458      * 00 is added here to make this format compatible with
2459      * domain:Bus:Slot.Func for systems without nested PCI bridges.
2460      * Slot.Function list specifies the slot and function numbers for all
2461      * devices on the path from root to the specific device. */
2462     const char *root_bus_path;
2463     int root_bus_len;
2464     char slot[] = ":SS.F";
2465     int slot_len = sizeof slot - 1 /* For '\0' */;
2466     int path_len;
2467     char *path, *p;
2468     int s;
2469 
2470     root_bus_path = pci_root_bus_path(d);
2471     root_bus_len = strlen(root_bus_path);
2472 
2473     /* Calculate # of slots on path between device and root. */;
2474     slot_depth = 0;
2475     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2476         ++slot_depth;
2477     }
2478 
2479     path_len = root_bus_len + slot_len * slot_depth;
2480 
2481     /* Allocate memory, fill in the terminating null byte. */
2482     path = g_malloc(path_len + 1 /* For '\0' */);
2483     path[path_len] = '\0';
2484 
2485     memcpy(path, root_bus_path, root_bus_len);
2486 
2487     /* Fill in slot numbers. We walk up from device to root, so need to print
2488      * them in the reverse order, last to first. */
2489     p = path + path_len;
2490     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2491         p -= slot_len;
2492         s = snprintf(slot, sizeof slot, ":%02x.%x",
2493                      PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2494         assert(s == slot_len);
2495         memcpy(p, slot, slot_len);
2496     }
2497 
2498     return path;
2499 }
2500 
2501 static int pci_qdev_find_recursive(PCIBus *bus,
2502                                    const char *id, PCIDevice **pdev)
2503 {
2504     DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2505     if (!qdev) {
2506         return -ENODEV;
2507     }
2508 
2509     /* roughly check if given qdev is pci device */
2510     if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2511         *pdev = PCI_DEVICE(qdev);
2512         return 0;
2513     }
2514     return -EINVAL;
2515 }
2516 
2517 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2518 {
2519     PCIHostState *host_bridge;
2520     int rc = -ENODEV;
2521 
2522     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2523         int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2524         if (!tmp) {
2525             rc = 0;
2526             break;
2527         }
2528         if (tmp != -ENODEV) {
2529             rc = tmp;
2530         }
2531     }
2532 
2533     return rc;
2534 }
2535 
2536 MemoryRegion *pci_address_space(PCIDevice *dev)
2537 {
2538     return pci_get_bus(dev)->address_space_mem;
2539 }
2540 
2541 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2542 {
2543     return pci_get_bus(dev)->address_space_io;
2544 }
2545 
2546 static void pci_device_class_init(ObjectClass *klass, void *data)
2547 {
2548     DeviceClass *k = DEVICE_CLASS(klass);
2549 
2550     k->realize = pci_qdev_realize;
2551     k->unrealize = pci_qdev_unrealize;
2552     k->bus_type = TYPE_PCI_BUS;
2553     device_class_set_props(k, pci_props);
2554 }
2555 
2556 static void pci_device_class_base_init(ObjectClass *klass, void *data)
2557 {
2558     if (!object_class_is_abstract(klass)) {
2559         ObjectClass *conventional =
2560             object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE);
2561         ObjectClass *pcie =
2562             object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE);
2563         ObjectClass *cxl =
2564             object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE);
2565         assert(conventional || pcie || cxl);
2566     }
2567 }
2568 
2569 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2570 {
2571     PCIBus *bus = pci_get_bus(dev);
2572     PCIBus *iommu_bus = bus;
2573     uint8_t devfn = dev->devfn;
2574 
2575     while (iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2576         PCIBus *parent_bus = pci_get_bus(iommu_bus->parent_dev);
2577 
2578         /*
2579          * The requester ID of the provided device may be aliased, as seen from
2580          * the IOMMU, due to topology limitations.  The IOMMU relies on a
2581          * requester ID to provide a unique AddressSpace for devices, but
2582          * conventional PCI buses pre-date such concepts.  Instead, the PCIe-
2583          * to-PCI bridge creates and accepts transactions on behalf of down-
2584          * stream devices.  When doing so, all downstream devices are masked
2585          * (aliased) behind a single requester ID.  The requester ID used
2586          * depends on the format of the bridge devices.  Proper PCIe-to-PCI
2587          * bridges, with a PCIe capability indicating such, follow the
2588          * guidelines of chapter 2.3 of the PCIe-to-PCI/X bridge specification,
2589          * where the bridge uses the seconary bus as the bridge portion of the
2590          * requester ID and devfn of 00.0.  For other bridges, typically those
2591          * found on the root complex such as the dmi-to-pci-bridge, we follow
2592          * the convention of typical bare-metal hardware, which uses the
2593          * requester ID of the bridge itself.  There are device specific
2594          * exceptions to these rules, but these are the defaults that the
2595          * Linux kernel uses when determining DMA aliases itself and believed
2596          * to be true for the bare metal equivalents of the devices emulated
2597          * in QEMU.
2598          */
2599         if (!pci_bus_is_express(iommu_bus)) {
2600             PCIDevice *parent = iommu_bus->parent_dev;
2601 
2602             if (pci_is_express(parent) &&
2603                 pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
2604                 devfn = PCI_DEVFN(0, 0);
2605                 bus = iommu_bus;
2606             } else {
2607                 devfn = parent->devfn;
2608                 bus = parent_bus;
2609             }
2610         }
2611 
2612         iommu_bus = parent_bus;
2613     }
2614     if (!pci_bus_bypass_iommu(bus) && iommu_bus && iommu_bus->iommu_fn) {
2615         return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, devfn);
2616     }
2617     return &address_space_memory;
2618 }
2619 
2620 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2621 {
2622     bus->iommu_fn = fn;
2623     bus->iommu_opaque = opaque;
2624 }
2625 
2626 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2627 {
2628     Range *range = opaque;
2629     uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2630     int i;
2631 
2632     if (!(cmd & PCI_COMMAND_MEMORY)) {
2633         return;
2634     }
2635 
2636     if (IS_PCI_BRIDGE(dev)) {
2637         pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2638         pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2639 
2640         base = MAX(base, 0x1ULL << 32);
2641 
2642         if (limit >= base) {
2643             Range pref_range;
2644             range_set_bounds(&pref_range, base, limit);
2645             range_extend(range, &pref_range);
2646         }
2647     }
2648     for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2649         PCIIORegion *r = &dev->io_regions[i];
2650         pcibus_t lob, upb;
2651         Range region_range;
2652 
2653         if (!r->size ||
2654             (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2655             !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2656             continue;
2657         }
2658 
2659         lob = pci_bar_address(dev, i, r->type, r->size);
2660         upb = lob + r->size - 1;
2661         if (lob == PCI_BAR_UNMAPPED) {
2662             continue;
2663         }
2664 
2665         lob = MAX(lob, 0x1ULL << 32);
2666 
2667         if (upb >= lob) {
2668             range_set_bounds(&region_range, lob, upb);
2669             range_extend(range, &region_range);
2670         }
2671     }
2672 }
2673 
2674 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2675 {
2676     range_make_empty(range);
2677     pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2678 }
2679 
2680 static bool pcie_has_upstream_port(PCIDevice *dev)
2681 {
2682     PCIDevice *parent_dev = pci_bridge_get_device(pci_get_bus(dev));
2683 
2684     /* Device associated with an upstream port.
2685      * As there are several types of these, it's easier to check the
2686      * parent device: upstream ports are always connected to
2687      * root or downstream ports.
2688      */
2689     return parent_dev &&
2690         pci_is_express(parent_dev) &&
2691         parent_dev->exp.exp_cap &&
2692         (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2693          pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2694 }
2695 
2696 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2697 {
2698     PCIBus *bus = pci_get_bus(pci_dev);
2699 
2700     if(pcie_has_upstream_port(pci_dev)) {
2701         /* With an upstream PCIe port, we only support 1 device at slot 0 */
2702         return bus->devices[0];
2703     } else {
2704         /* Other bus types might support multiple devices at slots 0-31 */
2705         return bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2706     }
2707 }
2708 
2709 MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2710 {
2711     MSIMessage msg;
2712     if (msix_enabled(dev)) {
2713         msg = msix_get_message(dev, vector);
2714     } else if (msi_enabled(dev)) {
2715         msg = msi_get_message(dev, vector);
2716     } else {
2717         /* Should never happen */
2718         error_report("%s: unknown interrupt type", __func__);
2719         abort();
2720     }
2721     return msg;
2722 }
2723 
2724 void pci_set_power(PCIDevice *d, bool state)
2725 {
2726     if (d->has_power == state) {
2727         return;
2728     }
2729 
2730     d->has_power = state;
2731     pci_update_mappings(d);
2732     memory_region_set_enabled(&d->bus_master_enable_region,
2733                               (pci_get_word(d->config + PCI_COMMAND)
2734                                & PCI_COMMAND_MASTER) && d->has_power);
2735     if (!d->has_power) {
2736         pci_device_reset(d);
2737     }
2738 }
2739 
2740 static const TypeInfo pci_device_type_info = {
2741     .name = TYPE_PCI_DEVICE,
2742     .parent = TYPE_DEVICE,
2743     .instance_size = sizeof(PCIDevice),
2744     .abstract = true,
2745     .class_size = sizeof(PCIDeviceClass),
2746     .class_init = pci_device_class_init,
2747     .class_base_init = pci_device_class_base_init,
2748 };
2749 
2750 static void pci_register_types(void)
2751 {
2752     type_register_static(&pci_bus_info);
2753     type_register_static(&pcie_bus_info);
2754     type_register_static(&cxl_bus_info);
2755     type_register_static(&conventional_pci_interface_info);
2756     type_register_static(&cxl_interface_info);
2757     type_register_static(&pcie_interface_info);
2758     type_register_static(&pci_device_type_info);
2759 }
2760 
2761 type_init(pci_register_types)
2762