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