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