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