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