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