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