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