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