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