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