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