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