xref: /openbmc/qemu/hw/pci/pci.c (revision 0ec8384f)
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(const 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     GPtrArray *pci_nic_models;
1793     PCIBus *bus;
1794     PCIDevice *pci_dev;
1795     DeviceState *dev;
1796     int devfn;
1797     int i;
1798     int dom, busnr;
1799     unsigned slot;
1800 
1801     if (nd->model && !strcmp(nd->model, "virtio")) {
1802         g_free(nd->model);
1803         nd->model = g_strdup("virtio-net-pci");
1804     }
1805 
1806     pci_nic_models = qemu_get_nic_models(TYPE_PCI_DEVICE);
1807 
1808     if (qemu_show_nic_models(nd->model, (const char **)pci_nic_models->pdata)) {
1809         exit(0);
1810     }
1811 
1812     i = qemu_find_nic_model(nd, (const char **)pci_nic_models->pdata,
1813                             default_model);
1814     if (i < 0) {
1815         exit(1);
1816     }
1817 
1818     if (!rootbus) {
1819         error_report("No primary PCI bus");
1820         exit(1);
1821     }
1822 
1823     assert(!rootbus->parent_dev);
1824 
1825     if (!devaddr) {
1826         devfn = -1;
1827         busnr = 0;
1828     } else {
1829         if (pci_parse_devaddr(devaddr, &dom, &busnr, &slot, NULL) < 0) {
1830             error_report("Invalid PCI device address %s for device %s",
1831                          devaddr, nd->model);
1832             exit(1);
1833         }
1834 
1835         if (dom != 0) {
1836             error_report("No support for non-zero PCI domains");
1837             exit(1);
1838         }
1839 
1840         devfn = PCI_DEVFN(slot, 0);
1841     }
1842 
1843     bus = pci_find_bus_nr(rootbus, busnr);
1844     if (!bus) {
1845         error_report("Invalid PCI device address %s for device %s",
1846                      devaddr, nd->model);
1847         exit(1);
1848     }
1849 
1850     pci_dev = pci_new(devfn, nd->model);
1851     dev = &pci_dev->qdev;
1852     qdev_set_nic_properties(dev, nd);
1853     pci_realize_and_unref(pci_dev, bus, &error_fatal);
1854     g_ptr_array_free(pci_nic_models, true);
1855     return pci_dev;
1856 }
1857 
1858 PCIDevice *pci_vga_init(PCIBus *bus)
1859 {
1860     vga_interface_created = true;
1861     switch (vga_interface_type) {
1862     case VGA_CIRRUS:
1863         return pci_create_simple(bus, -1, "cirrus-vga");
1864     case VGA_QXL:
1865         return pci_create_simple(bus, -1, "qxl-vga");
1866     case VGA_STD:
1867         return pci_create_simple(bus, -1, "VGA");
1868     case VGA_VMWARE:
1869         return pci_create_simple(bus, -1, "vmware-svga");
1870     case VGA_VIRTIO:
1871         return pci_create_simple(bus, -1, "virtio-vga");
1872     case VGA_NONE:
1873     default: /* Other non-PCI types. Checking for unsupported types is already
1874                 done in vl.c. */
1875         return NULL;
1876     }
1877 }
1878 
1879 /* Whether a given bus number is in range of the secondary
1880  * bus of the given bridge device. */
1881 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1882 {
1883     return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1884              PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1885         dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1886         bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1887 }
1888 
1889 /* Whether a given bus number is in a range of a root bus */
1890 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1891 {
1892     int i;
1893 
1894     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1895         PCIDevice *dev = bus->devices[i];
1896 
1897         if (dev && IS_PCI_BRIDGE(dev)) {
1898             if (pci_secondary_bus_in_range(dev, bus_num)) {
1899                 return true;
1900             }
1901         }
1902     }
1903 
1904     return false;
1905 }
1906 
1907 PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1908 {
1909     PCIBus *sec;
1910 
1911     if (!bus) {
1912         return NULL;
1913     }
1914 
1915     if (pci_bus_num(bus) == bus_num) {
1916         return bus;
1917     }
1918 
1919     /* Consider all bus numbers in range for the host pci bridge. */
1920     if (!pci_bus_is_root(bus) &&
1921         !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1922         return NULL;
1923     }
1924 
1925     /* try child bus */
1926     for (; bus; bus = sec) {
1927         QLIST_FOREACH(sec, &bus->child, sibling) {
1928             if (pci_bus_num(sec) == bus_num) {
1929                 return sec;
1930             }
1931             /* PXB buses assumed to be children of bus 0 */
1932             if (pci_bus_is_root(sec)) {
1933                 if (pci_root_bus_in_range(sec, bus_num)) {
1934                     break;
1935                 }
1936             } else {
1937                 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1938                     break;
1939                 }
1940             }
1941         }
1942     }
1943 
1944     return NULL;
1945 }
1946 
1947 void pci_for_each_bus_depth_first(PCIBus *bus, pci_bus_ret_fn begin,
1948                                   pci_bus_fn end, void *parent_state)
1949 {
1950     PCIBus *sec;
1951     void *state;
1952 
1953     if (!bus) {
1954         return;
1955     }
1956 
1957     if (begin) {
1958         state = begin(bus, parent_state);
1959     } else {
1960         state = parent_state;
1961     }
1962 
1963     QLIST_FOREACH(sec, &bus->child, sibling) {
1964         pci_for_each_bus_depth_first(sec, begin, end, state);
1965     }
1966 
1967     if (end) {
1968         end(bus, state);
1969     }
1970 }
1971 
1972 
1973 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1974 {
1975     bus = pci_find_bus_nr(bus, bus_num);
1976 
1977     if (!bus)
1978         return NULL;
1979 
1980     return bus->devices[devfn];
1981 }
1982 
1983 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
1984 {
1985     PCIDevice *pci_dev = (PCIDevice *)qdev;
1986     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1987     ObjectClass *klass = OBJECT_CLASS(pc);
1988     Error *local_err = NULL;
1989     bool is_default_rom;
1990     uint16_t class_id;
1991 
1992     if (pci_dev->romsize != -1 && !is_power_of_2(pci_dev->romsize)) {
1993         error_setg(errp, "ROM size %u is not a power of two", pci_dev->romsize);
1994         return;
1995     }
1996 
1997     /* initialize cap_present for pci_is_express() and pci_config_size(),
1998      * Note that hybrid PCIs are not set automatically and need to manage
1999      * QEMU_PCI_CAP_EXPRESS manually */
2000     if (object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE) &&
2001        !object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE)) {
2002         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2003     }
2004 
2005     if (object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE)) {
2006         pci_dev->cap_present |= QEMU_PCIE_CAP_CXL;
2007     }
2008 
2009     pci_dev = do_pci_register_device(pci_dev,
2010                                      object_get_typename(OBJECT(qdev)),
2011                                      pci_dev->devfn, errp);
2012     if (pci_dev == NULL)
2013         return;
2014 
2015     if (pc->realize) {
2016         pc->realize(pci_dev, &local_err);
2017         if (local_err) {
2018             error_propagate(errp, local_err);
2019             do_pci_unregister_device(pci_dev);
2020             return;
2021         }
2022     }
2023 
2024     if (pci_dev->failover_pair_id) {
2025         if (!pci_bus_is_express(pci_get_bus(pci_dev))) {
2026             error_setg(errp, "failover primary device must be on "
2027                              "PCIExpress bus");
2028             pci_qdev_unrealize(DEVICE(pci_dev));
2029             return;
2030         }
2031         class_id = pci_get_word(pci_dev->config + PCI_CLASS_DEVICE);
2032         if (class_id != PCI_CLASS_NETWORK_ETHERNET) {
2033             error_setg(errp, "failover primary device is not an "
2034                              "Ethernet device");
2035             pci_qdev_unrealize(DEVICE(pci_dev));
2036             return;
2037         }
2038         if ((pci_dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)
2039             || (PCI_FUNC(pci_dev->devfn) != 0)) {
2040             error_setg(errp, "failover: primary device must be in its own "
2041                               "PCI slot");
2042             pci_qdev_unrealize(DEVICE(pci_dev));
2043             return;
2044         }
2045         qdev->allow_unplug_during_migration = true;
2046     }
2047 
2048     /* rom loading */
2049     is_default_rom = false;
2050     if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2051         pci_dev->romfile = g_strdup(pc->romfile);
2052         is_default_rom = true;
2053     }
2054 
2055     pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2056     if (local_err) {
2057         error_propagate(errp, local_err);
2058         pci_qdev_unrealize(DEVICE(pci_dev));
2059         return;
2060     }
2061 
2062     pci_set_power(pci_dev, true);
2063 
2064     pci_dev->msi_trigger = pci_msi_trigger;
2065 }
2066 
2067 PCIDevice *pci_new_multifunction(int devfn, bool multifunction,
2068                                  const char *name)
2069 {
2070     DeviceState *dev;
2071 
2072     dev = qdev_new(name);
2073     qdev_prop_set_int32(dev, "addr", devfn);
2074     qdev_prop_set_bit(dev, "multifunction", multifunction);
2075     return PCI_DEVICE(dev);
2076 }
2077 
2078 PCIDevice *pci_new(int devfn, const char *name)
2079 {
2080     return pci_new_multifunction(devfn, false, name);
2081 }
2082 
2083 bool pci_realize_and_unref(PCIDevice *dev, PCIBus *bus, Error **errp)
2084 {
2085     return qdev_realize_and_unref(&dev->qdev, &bus->qbus, errp);
2086 }
2087 
2088 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2089                                            bool multifunction,
2090                                            const char *name)
2091 {
2092     PCIDevice *dev = pci_new_multifunction(devfn, multifunction, name);
2093     pci_realize_and_unref(dev, bus, &error_fatal);
2094     return dev;
2095 }
2096 
2097 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2098 {
2099     return pci_create_simple_multifunction(bus, devfn, false, name);
2100 }
2101 
2102 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2103 {
2104     int offset = PCI_CONFIG_HEADER_SIZE;
2105     int i;
2106     for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2107         if (pdev->used[i])
2108             offset = i + 1;
2109         else if (i - offset + 1 == size)
2110             return offset;
2111     }
2112     return 0;
2113 }
2114 
2115 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2116                                         uint8_t *prev_p)
2117 {
2118     uint8_t next, prev;
2119 
2120     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2121         return 0;
2122 
2123     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2124          prev = next + PCI_CAP_LIST_NEXT)
2125         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2126             break;
2127 
2128     if (prev_p)
2129         *prev_p = prev;
2130     return next;
2131 }
2132 
2133 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2134 {
2135     uint8_t next, prev, found = 0;
2136 
2137     if (!(pdev->used[offset])) {
2138         return 0;
2139     }
2140 
2141     assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2142 
2143     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2144          prev = next + PCI_CAP_LIST_NEXT) {
2145         if (next <= offset && next > found) {
2146             found = next;
2147         }
2148     }
2149     return found;
2150 }
2151 
2152 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2153    This is needed for an option rom which is used for more than one device. */
2154 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, uint32_t size)
2155 {
2156     uint16_t vendor_id;
2157     uint16_t device_id;
2158     uint16_t rom_vendor_id;
2159     uint16_t rom_device_id;
2160     uint16_t rom_magic;
2161     uint16_t pcir_offset;
2162     uint8_t checksum;
2163 
2164     /* Words in rom data are little endian (like in PCI configuration),
2165        so they can be read / written with pci_get_word / pci_set_word. */
2166 
2167     /* Only a valid rom will be patched. */
2168     rom_magic = pci_get_word(ptr);
2169     if (rom_magic != 0xaa55) {
2170         PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2171         return;
2172     }
2173     pcir_offset = pci_get_word(ptr + 0x18);
2174     if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2175         PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2176         return;
2177     }
2178 
2179     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2180     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2181     rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2182     rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2183 
2184     PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2185                 vendor_id, device_id, rom_vendor_id, rom_device_id);
2186 
2187     checksum = ptr[6];
2188 
2189     if (vendor_id != rom_vendor_id) {
2190         /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2191         checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2192         checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2193         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2194         ptr[6] = checksum;
2195         pci_set_word(ptr + pcir_offset + 4, vendor_id);
2196     }
2197 
2198     if (device_id != rom_device_id) {
2199         /* Patch device id and checksum (at offset 6 for etherboot roms). */
2200         checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2201         checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2202         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2203         ptr[6] = checksum;
2204         pci_set_word(ptr + pcir_offset + 6, device_id);
2205     }
2206 }
2207 
2208 /* Add an option rom for the device */
2209 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2210                                Error **errp)
2211 {
2212     int64_t size;
2213     char *path;
2214     void *ptr;
2215     char name[32];
2216     const VMStateDescription *vmsd;
2217 
2218     if (!pdev->romfile)
2219         return;
2220     if (strlen(pdev->romfile) == 0)
2221         return;
2222 
2223     if (!pdev->rom_bar) {
2224         /*
2225          * Load rom via fw_cfg instead of creating a rom bar,
2226          * for 0.11 compatibility.
2227          */
2228         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2229 
2230         /*
2231          * Hot-plugged devices can't use the option ROM
2232          * if the rom bar is disabled.
2233          */
2234         if (DEVICE(pdev)->hotplugged) {
2235             error_setg(errp, "Hot-plugged device without ROM bar"
2236                        " can't have an option ROM");
2237             return;
2238         }
2239 
2240         if (class == 0x0300) {
2241             rom_add_vga(pdev->romfile);
2242         } else {
2243             rom_add_option(pdev->romfile, -1);
2244         }
2245         return;
2246     }
2247 
2248     path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2249     if (path == NULL) {
2250         path = g_strdup(pdev->romfile);
2251     }
2252 
2253     size = get_image_size(path);
2254     if (size < 0) {
2255         error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2256         g_free(path);
2257         return;
2258     } else if (size == 0) {
2259         error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2260         g_free(path);
2261         return;
2262     } else if (size > 2 * GiB) {
2263         error_setg(errp, "romfile \"%s\" too large (size cannot exceed 2 GiB)",
2264                    pdev->romfile);
2265         g_free(path);
2266         return;
2267     }
2268     if (pdev->romsize != -1) {
2269         if (size > pdev->romsize) {
2270             error_setg(errp, "romfile \"%s\" (%u bytes) is too large for ROM size %u",
2271                        pdev->romfile, (uint32_t)size, pdev->romsize);
2272             g_free(path);
2273             return;
2274         }
2275     } else {
2276         pdev->romsize = pow2ceil(size);
2277     }
2278 
2279     vmsd = qdev_get_vmsd(DEVICE(pdev));
2280 
2281     if (vmsd) {
2282         snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2283     } else {
2284         snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2285     }
2286     pdev->has_rom = true;
2287     memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, pdev->romsize, &error_fatal);
2288     ptr = memory_region_get_ram_ptr(&pdev->rom);
2289     if (load_image_size(path, ptr, size) < 0) {
2290         error_setg(errp, "failed to load romfile \"%s\"", pdev->romfile);
2291         g_free(path);
2292         return;
2293     }
2294     g_free(path);
2295 
2296     if (is_default_rom) {
2297         /* Only the default rom images will be patched (if needed). */
2298         pci_patch_ids(pdev, ptr, size);
2299     }
2300 
2301     pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2302 }
2303 
2304 static void pci_del_option_rom(PCIDevice *pdev)
2305 {
2306     if (!pdev->has_rom)
2307         return;
2308 
2309     vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2310     pdev->has_rom = false;
2311 }
2312 
2313 /*
2314  * On success, pci_add_capability() returns a positive value
2315  * that the offset of the pci capability.
2316  * On failure, it sets an error and returns a negative error
2317  * code.
2318  */
2319 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2320                        uint8_t offset, uint8_t size,
2321                        Error **errp)
2322 {
2323     uint8_t *config;
2324     int i, overlapping_cap;
2325 
2326     if (!offset) {
2327         offset = pci_find_space(pdev, size);
2328         /* out of PCI config space is programming error */
2329         assert(offset);
2330     } else {
2331         /* Verify that capabilities don't overlap.  Note: device assignment
2332          * depends on this check to verify that the device is not broken.
2333          * Should never trigger for emulated devices, but it's helpful
2334          * for debugging these. */
2335         for (i = offset; i < offset + size; i++) {
2336             overlapping_cap = pci_find_capability_at_offset(pdev, i);
2337             if (overlapping_cap) {
2338                 error_setg(errp, "%s:%02x:%02x.%x "
2339                            "Attempt to add PCI capability %x at offset "
2340                            "%x overlaps existing capability %x at offset %x",
2341                            pci_root_bus_path(pdev), pci_dev_bus_num(pdev),
2342                            PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2343                            cap_id, offset, overlapping_cap, i);
2344                 return -EINVAL;
2345             }
2346         }
2347     }
2348 
2349     config = pdev->config + offset;
2350     config[PCI_CAP_LIST_ID] = cap_id;
2351     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2352     pdev->config[PCI_CAPABILITY_LIST] = offset;
2353     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2354     memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2355     /* Make capability read-only by default */
2356     memset(pdev->wmask + offset, 0, size);
2357     /* Check capability by default */
2358     memset(pdev->cmask + offset, 0xFF, size);
2359     return offset;
2360 }
2361 
2362 /* Unlink capability from the pci config space. */
2363 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2364 {
2365     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2366     if (!offset)
2367         return;
2368     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2369     /* Make capability writable again */
2370     memset(pdev->wmask + offset, 0xff, size);
2371     memset(pdev->w1cmask + offset, 0, size);
2372     /* Clear cmask as device-specific registers can't be checked */
2373     memset(pdev->cmask + offset, 0, size);
2374     memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2375 
2376     if (!pdev->config[PCI_CAPABILITY_LIST])
2377         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2378 }
2379 
2380 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2381 {
2382     return pci_find_capability_list(pdev, cap_id, NULL);
2383 }
2384 
2385 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2386 {
2387     PCIDevice *d = (PCIDevice *)dev;
2388     const char *name = NULL;
2389     const pci_class_desc *desc =  pci_class_descriptions;
2390     int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2391 
2392     while (desc->desc &&
2393           (class & ~desc->fw_ign_bits) !=
2394           (desc->class & ~desc->fw_ign_bits)) {
2395         desc++;
2396     }
2397 
2398     if (desc->desc) {
2399         name = desc->fw_name;
2400     }
2401 
2402     if (name) {
2403         pstrcpy(buf, len, name);
2404     } else {
2405         snprintf(buf, len, "pci%04x,%04x",
2406                  pci_get_word(d->config + PCI_VENDOR_ID),
2407                  pci_get_word(d->config + PCI_DEVICE_ID));
2408     }
2409 
2410     return buf;
2411 }
2412 
2413 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2414 {
2415     PCIDevice *d = (PCIDevice *)dev;
2416     char name[33];
2417     int has_func = !!PCI_FUNC(d->devfn);
2418 
2419     return g_strdup_printf("%s@%x%s%.*x",
2420                            pci_dev_fw_name(dev, name, sizeof(name)),
2421                            PCI_SLOT(d->devfn),
2422                            has_func ? "," : "",
2423                            has_func,
2424                            PCI_FUNC(d->devfn));
2425 }
2426 
2427 static char *pcibus_get_dev_path(DeviceState *dev)
2428 {
2429     PCIDevice *d = container_of(dev, PCIDevice, qdev);
2430     PCIDevice *t;
2431     int slot_depth;
2432     /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2433      * 00 is added here to make this format compatible with
2434      * domain:Bus:Slot.Func for systems without nested PCI bridges.
2435      * Slot.Function list specifies the slot and function numbers for all
2436      * devices on the path from root to the specific device. */
2437     const char *root_bus_path;
2438     int root_bus_len;
2439     char slot[] = ":SS.F";
2440     int slot_len = sizeof slot - 1 /* For '\0' */;
2441     int path_len;
2442     char *path, *p;
2443     int s;
2444 
2445     root_bus_path = pci_root_bus_path(d);
2446     root_bus_len = strlen(root_bus_path);
2447 
2448     /* Calculate # of slots on path between device and root. */;
2449     slot_depth = 0;
2450     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2451         ++slot_depth;
2452     }
2453 
2454     path_len = root_bus_len + slot_len * slot_depth;
2455 
2456     /* Allocate memory, fill in the terminating null byte. */
2457     path = g_malloc(path_len + 1 /* For '\0' */);
2458     path[path_len] = '\0';
2459 
2460     memcpy(path, root_bus_path, root_bus_len);
2461 
2462     /* Fill in slot numbers. We walk up from device to root, so need to print
2463      * them in the reverse order, last to first. */
2464     p = path + path_len;
2465     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2466         p -= slot_len;
2467         s = snprintf(slot, sizeof slot, ":%02x.%x",
2468                      PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2469         assert(s == slot_len);
2470         memcpy(p, slot, slot_len);
2471     }
2472 
2473     return path;
2474 }
2475 
2476 static int pci_qdev_find_recursive(PCIBus *bus,
2477                                    const char *id, PCIDevice **pdev)
2478 {
2479     DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2480     if (!qdev) {
2481         return -ENODEV;
2482     }
2483 
2484     /* roughly check if given qdev is pci device */
2485     if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2486         *pdev = PCI_DEVICE(qdev);
2487         return 0;
2488     }
2489     return -EINVAL;
2490 }
2491 
2492 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2493 {
2494     PCIHostState *host_bridge;
2495     int rc = -ENODEV;
2496 
2497     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2498         int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2499         if (!tmp) {
2500             rc = 0;
2501             break;
2502         }
2503         if (tmp != -ENODEV) {
2504             rc = tmp;
2505         }
2506     }
2507 
2508     return rc;
2509 }
2510 
2511 MemoryRegion *pci_address_space(PCIDevice *dev)
2512 {
2513     return pci_get_bus(dev)->address_space_mem;
2514 }
2515 
2516 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2517 {
2518     return pci_get_bus(dev)->address_space_io;
2519 }
2520 
2521 static void pci_device_class_init(ObjectClass *klass, void *data)
2522 {
2523     DeviceClass *k = DEVICE_CLASS(klass);
2524 
2525     k->realize = pci_qdev_realize;
2526     k->unrealize = pci_qdev_unrealize;
2527     k->bus_type = TYPE_PCI_BUS;
2528     device_class_set_props(k, pci_props);
2529 }
2530 
2531 static void pci_device_class_base_init(ObjectClass *klass, void *data)
2532 {
2533     if (!object_class_is_abstract(klass)) {
2534         ObjectClass *conventional =
2535             object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE);
2536         ObjectClass *pcie =
2537             object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE);
2538         ObjectClass *cxl =
2539             object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE);
2540         assert(conventional || pcie || cxl);
2541     }
2542 }
2543 
2544 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2545 {
2546     PCIBus *bus = pci_get_bus(dev);
2547     PCIBus *iommu_bus = bus;
2548     uint8_t devfn = dev->devfn;
2549 
2550     while (iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2551         PCIBus *parent_bus = pci_get_bus(iommu_bus->parent_dev);
2552 
2553         /*
2554          * The requester ID of the provided device may be aliased, as seen from
2555          * the IOMMU, due to topology limitations.  The IOMMU relies on a
2556          * requester ID to provide a unique AddressSpace for devices, but
2557          * conventional PCI buses pre-date such concepts.  Instead, the PCIe-
2558          * to-PCI bridge creates and accepts transactions on behalf of down-
2559          * stream devices.  When doing so, all downstream devices are masked
2560          * (aliased) behind a single requester ID.  The requester ID used
2561          * depends on the format of the bridge devices.  Proper PCIe-to-PCI
2562          * bridges, with a PCIe capability indicating such, follow the
2563          * guidelines of chapter 2.3 of the PCIe-to-PCI/X bridge specification,
2564          * where the bridge uses the seconary bus as the bridge portion of the
2565          * requester ID and devfn of 00.0.  For other bridges, typically those
2566          * found on the root complex such as the dmi-to-pci-bridge, we follow
2567          * the convention of typical bare-metal hardware, which uses the
2568          * requester ID of the bridge itself.  There are device specific
2569          * exceptions to these rules, but these are the defaults that the
2570          * Linux kernel uses when determining DMA aliases itself and believed
2571          * to be true for the bare metal equivalents of the devices emulated
2572          * in QEMU.
2573          */
2574         if (!pci_bus_is_express(iommu_bus)) {
2575             PCIDevice *parent = iommu_bus->parent_dev;
2576 
2577             if (pci_is_express(parent) &&
2578                 pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
2579                 devfn = PCI_DEVFN(0, 0);
2580                 bus = iommu_bus;
2581             } else {
2582                 devfn = parent->devfn;
2583                 bus = parent_bus;
2584             }
2585         }
2586 
2587         iommu_bus = parent_bus;
2588     }
2589     if (!pci_bus_bypass_iommu(bus) && iommu_bus && iommu_bus->iommu_fn) {
2590         return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, devfn);
2591     }
2592     return &address_space_memory;
2593 }
2594 
2595 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2596 {
2597     bus->iommu_fn = fn;
2598     bus->iommu_opaque = opaque;
2599 }
2600 
2601 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2602 {
2603     Range *range = opaque;
2604     uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2605     int i;
2606 
2607     if (!(cmd & PCI_COMMAND_MEMORY)) {
2608         return;
2609     }
2610 
2611     if (IS_PCI_BRIDGE(dev)) {
2612         pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2613         pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2614 
2615         base = MAX(base, 0x1ULL << 32);
2616 
2617         if (limit >= base) {
2618             Range pref_range;
2619             range_set_bounds(&pref_range, base, limit);
2620             range_extend(range, &pref_range);
2621         }
2622     }
2623     for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2624         PCIIORegion *r = &dev->io_regions[i];
2625         pcibus_t lob, upb;
2626         Range region_range;
2627 
2628         if (!r->size ||
2629             (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2630             !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2631             continue;
2632         }
2633 
2634         lob = pci_bar_address(dev, i, r->type, r->size);
2635         upb = lob + r->size - 1;
2636         if (lob == PCI_BAR_UNMAPPED) {
2637             continue;
2638         }
2639 
2640         lob = MAX(lob, 0x1ULL << 32);
2641 
2642         if (upb >= lob) {
2643             range_set_bounds(&region_range, lob, upb);
2644             range_extend(range, &region_range);
2645         }
2646     }
2647 }
2648 
2649 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2650 {
2651     range_make_empty(range);
2652     pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2653 }
2654 
2655 static bool pcie_has_upstream_port(PCIDevice *dev)
2656 {
2657     PCIDevice *parent_dev = pci_bridge_get_device(pci_get_bus(dev));
2658 
2659     /* Device associated with an upstream port.
2660      * As there are several types of these, it's easier to check the
2661      * parent device: upstream ports are always connected to
2662      * root or downstream ports.
2663      */
2664     return parent_dev &&
2665         pci_is_express(parent_dev) &&
2666         parent_dev->exp.exp_cap &&
2667         (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2668          pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2669 }
2670 
2671 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2672 {
2673     PCIBus *bus = pci_get_bus(pci_dev);
2674 
2675     if(pcie_has_upstream_port(pci_dev)) {
2676         /* With an upstream PCIe port, we only support 1 device at slot 0 */
2677         return bus->devices[0];
2678     } else {
2679         /* Other bus types might support multiple devices at slots 0-31 */
2680         return bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2681     }
2682 }
2683 
2684 MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2685 {
2686     MSIMessage msg;
2687     if (msix_enabled(dev)) {
2688         msg = msix_get_message(dev, vector);
2689     } else if (msi_enabled(dev)) {
2690         msg = msi_get_message(dev, vector);
2691     } else {
2692         /* Should never happen */
2693         error_report("%s: unknown interrupt type", __func__);
2694         abort();
2695     }
2696     return msg;
2697 }
2698 
2699 void pci_set_power(PCIDevice *d, bool state)
2700 {
2701     if (d->has_power == state) {
2702         return;
2703     }
2704 
2705     d->has_power = state;
2706     pci_update_mappings(d);
2707     memory_region_set_enabled(&d->bus_master_enable_region,
2708                               (pci_get_word(d->config + PCI_COMMAND)
2709                                & PCI_COMMAND_MASTER) && d->has_power);
2710     if (!d->has_power) {
2711         pci_device_reset(d);
2712     }
2713 }
2714 
2715 static const TypeInfo pci_device_type_info = {
2716     .name = TYPE_PCI_DEVICE,
2717     .parent = TYPE_DEVICE,
2718     .instance_size = sizeof(PCIDevice),
2719     .abstract = true,
2720     .class_size = sizeof(PCIDeviceClass),
2721     .class_init = pci_device_class_init,
2722     .class_base_init = pci_device_class_base_init,
2723 };
2724 
2725 static void pci_register_types(void)
2726 {
2727     type_register_static(&pci_bus_info);
2728     type_register_static(&pcie_bus_info);
2729     type_register_static(&cxl_bus_info);
2730     type_register_static(&conventional_pci_interface_info);
2731     type_register_static(&cxl_interface_info);
2732     type_register_static(&pcie_interface_info);
2733     type_register_static(&pci_device_type_info);
2734 }
2735 
2736 type_init(pci_register_types)
2737