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