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