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