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