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