xref: /openbmc/qemu/hw/pci/pci.c (revision 6016b7b4)
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, 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, 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 static inline int pci_intx(PCIDevice *pci_dev)
1501 {
1502     return pci_get_byte(pci_dev->config + PCI_INTERRUPT_PIN) - 1;
1503 }
1504 
1505 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1506 {
1507     int intx = pci_intx(pci_dev);
1508     assert(0 <= intx && intx < PCI_NUM_PINS);
1509 
1510     return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1511 }
1512 
1513 void pci_set_irq(PCIDevice *pci_dev, int level)
1514 {
1515     int intx = pci_intx(pci_dev);
1516     pci_irq_handler(pci_dev, intx, level);
1517 }
1518 
1519 /* Special hooks used by device assignment */
1520 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1521 {
1522     assert(pci_bus_is_root(bus));
1523     bus->route_intx_to_irq = route_intx_to_irq;
1524 }
1525 
1526 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1527 {
1528     PCIBus *bus;
1529 
1530     do {
1531         bus = pci_get_bus(dev);
1532         pin = bus->map_irq(dev, pin);
1533         dev = bus->parent_dev;
1534     } while (dev);
1535 
1536     if (!bus->route_intx_to_irq) {
1537         error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1538                      object_get_typename(OBJECT(bus->qbus.parent)));
1539         return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1540     }
1541 
1542     return bus->route_intx_to_irq(bus->irq_opaque, pin);
1543 }
1544 
1545 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1546 {
1547     return old->mode != new->mode || old->irq != new->irq;
1548 }
1549 
1550 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1551 {
1552     PCIDevice *dev;
1553     PCIBus *sec;
1554     int i;
1555 
1556     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1557         dev = bus->devices[i];
1558         if (dev && dev->intx_routing_notifier) {
1559             dev->intx_routing_notifier(dev);
1560         }
1561     }
1562 
1563     QLIST_FOREACH(sec, &bus->child, sibling) {
1564         pci_bus_fire_intx_routing_notifier(sec);
1565     }
1566 }
1567 
1568 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1569                                           PCIINTxRoutingNotifier notifier)
1570 {
1571     dev->intx_routing_notifier = notifier;
1572 }
1573 
1574 /*
1575  * PCI-to-PCI bridge specification
1576  * 9.1: Interrupt routing. Table 9-1
1577  *
1578  * the PCI Express Base Specification, Revision 2.1
1579  * 2.2.8.1: INTx interrutp signaling - Rules
1580  *          the Implementation Note
1581  *          Table 2-20
1582  */
1583 /*
1584  * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1585  * 0-origin unlike PCI interrupt pin register.
1586  */
1587 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1588 {
1589     return pci_swizzle(PCI_SLOT(pci_dev->devfn), pin);
1590 }
1591 
1592 /***********************************************************/
1593 /* monitor info on PCI */
1594 
1595 typedef struct {
1596     uint16_t class;
1597     const char *desc;
1598     const char *fw_name;
1599     uint16_t fw_ign_bits;
1600 } pci_class_desc;
1601 
1602 static const pci_class_desc pci_class_descriptions[] =
1603 {
1604     { 0x0001, "VGA controller", "display"},
1605     { 0x0100, "SCSI controller", "scsi"},
1606     { 0x0101, "IDE controller", "ide"},
1607     { 0x0102, "Floppy controller", "fdc"},
1608     { 0x0103, "IPI controller", "ipi"},
1609     { 0x0104, "RAID controller", "raid"},
1610     { 0x0106, "SATA controller"},
1611     { 0x0107, "SAS controller"},
1612     { 0x0180, "Storage controller"},
1613     { 0x0200, "Ethernet controller", "ethernet"},
1614     { 0x0201, "Token Ring controller", "token-ring"},
1615     { 0x0202, "FDDI controller", "fddi"},
1616     { 0x0203, "ATM controller", "atm"},
1617     { 0x0280, "Network controller"},
1618     { 0x0300, "VGA controller", "display", 0x00ff},
1619     { 0x0301, "XGA controller"},
1620     { 0x0302, "3D controller"},
1621     { 0x0380, "Display controller"},
1622     { 0x0400, "Video controller", "video"},
1623     { 0x0401, "Audio controller", "sound"},
1624     { 0x0402, "Phone"},
1625     { 0x0403, "Audio controller", "sound"},
1626     { 0x0480, "Multimedia controller"},
1627     { 0x0500, "RAM controller", "memory"},
1628     { 0x0501, "Flash controller", "flash"},
1629     { 0x0580, "Memory controller"},
1630     { 0x0600, "Host bridge", "host"},
1631     { 0x0601, "ISA bridge", "isa"},
1632     { 0x0602, "EISA bridge", "eisa"},
1633     { 0x0603, "MC bridge", "mca"},
1634     { 0x0604, "PCI bridge", "pci-bridge"},
1635     { 0x0605, "PCMCIA bridge", "pcmcia"},
1636     { 0x0606, "NUBUS bridge", "nubus"},
1637     { 0x0607, "CARDBUS bridge", "cardbus"},
1638     { 0x0608, "RACEWAY bridge"},
1639     { 0x0680, "Bridge"},
1640     { 0x0700, "Serial port", "serial"},
1641     { 0x0701, "Parallel port", "parallel"},
1642     { 0x0800, "Interrupt controller", "interrupt-controller"},
1643     { 0x0801, "DMA controller", "dma-controller"},
1644     { 0x0802, "Timer", "timer"},
1645     { 0x0803, "RTC", "rtc"},
1646     { 0x0900, "Keyboard", "keyboard"},
1647     { 0x0901, "Pen", "pen"},
1648     { 0x0902, "Mouse", "mouse"},
1649     { 0x0A00, "Dock station", "dock", 0x00ff},
1650     { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1651     { 0x0c00, "Fireware contorller", "fireware"},
1652     { 0x0c01, "Access bus controller", "access-bus"},
1653     { 0x0c02, "SSA controller", "ssa"},
1654     { 0x0c03, "USB controller", "usb"},
1655     { 0x0c04, "Fibre channel controller", "fibre-channel"},
1656     { 0x0c05, "SMBus"},
1657     { 0, NULL}
1658 };
1659 
1660 void pci_for_each_device_under_bus_reverse(PCIBus *bus,
1661                                            pci_bus_dev_fn fn,
1662                                            void *opaque)
1663 {
1664     PCIDevice *d;
1665     int devfn;
1666 
1667     for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1668         d = bus->devices[ARRAY_SIZE(bus->devices) - 1 - devfn];
1669         if (d) {
1670             fn(bus, d, opaque);
1671         }
1672     }
1673 }
1674 
1675 void pci_for_each_device_reverse(PCIBus *bus, int bus_num,
1676                                  pci_bus_dev_fn fn, void *opaque)
1677 {
1678     bus = pci_find_bus_nr(bus, bus_num);
1679 
1680     if (bus) {
1681         pci_for_each_device_under_bus_reverse(bus, fn, opaque);
1682     }
1683 }
1684 
1685 void pci_for_each_device_under_bus(PCIBus *bus,
1686                                    pci_bus_dev_fn fn, void *opaque)
1687 {
1688     PCIDevice *d;
1689     int devfn;
1690 
1691     for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1692         d = bus->devices[devfn];
1693         if (d) {
1694             fn(bus, d, opaque);
1695         }
1696     }
1697 }
1698 
1699 void pci_for_each_device(PCIBus *bus, int bus_num,
1700                          pci_bus_dev_fn fn, void *opaque)
1701 {
1702     bus = pci_find_bus_nr(bus, bus_num);
1703 
1704     if (bus) {
1705         pci_for_each_device_under_bus(bus, fn, opaque);
1706     }
1707 }
1708 
1709 static const pci_class_desc *get_class_desc(int class)
1710 {
1711     const pci_class_desc *desc;
1712 
1713     desc = pci_class_descriptions;
1714     while (desc->desc && class != desc->class) {
1715         desc++;
1716     }
1717 
1718     return desc;
1719 }
1720 
1721 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num);
1722 
1723 static PciMemoryRegionList *qmp_query_pci_regions(const PCIDevice *dev)
1724 {
1725     PciMemoryRegionList *head = NULL, **tail = &head;
1726     int i;
1727 
1728     for (i = 0; i < PCI_NUM_REGIONS; i++) {
1729         const PCIIORegion *r = &dev->io_regions[i];
1730         PciMemoryRegion *region;
1731 
1732         if (!r->size) {
1733             continue;
1734         }
1735 
1736         region = g_malloc0(sizeof(*region));
1737 
1738         if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1739             region->type = g_strdup("io");
1740         } else {
1741             region->type = g_strdup("memory");
1742             region->has_prefetch = true;
1743             region->prefetch = !!(r->type & PCI_BASE_ADDRESS_MEM_PREFETCH);
1744             region->has_mem_type_64 = true;
1745             region->mem_type_64 = !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
1746         }
1747 
1748         region->bar = i;
1749         region->address = r->addr;
1750         region->size = r->size;
1751 
1752         QAPI_LIST_APPEND(tail, region);
1753     }
1754 
1755     return head;
1756 }
1757 
1758 static PciBridgeInfo *qmp_query_pci_bridge(PCIDevice *dev, PCIBus *bus,
1759                                            int bus_num)
1760 {
1761     PciBridgeInfo *info;
1762     PciMemoryRange *range;
1763 
1764     info = g_new0(PciBridgeInfo, 1);
1765 
1766     info->bus = g_new0(PciBusInfo, 1);
1767     info->bus->number = dev->config[PCI_PRIMARY_BUS];
1768     info->bus->secondary = dev->config[PCI_SECONDARY_BUS];
1769     info->bus->subordinate = dev->config[PCI_SUBORDINATE_BUS];
1770 
1771     range = info->bus->io_range = g_new0(PciMemoryRange, 1);
1772     range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
1773     range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
1774 
1775     range = info->bus->memory_range = g_new0(PciMemoryRange, 1);
1776     range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1777     range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1778 
1779     range = info->bus->prefetchable_range = g_new0(PciMemoryRange, 1);
1780     range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1781     range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1782 
1783     if (dev->config[PCI_SECONDARY_BUS] != 0) {
1784         PCIBus *child_bus = pci_find_bus_nr(bus, dev->config[PCI_SECONDARY_BUS]);
1785         if (child_bus) {
1786             info->has_devices = true;
1787             info->devices = qmp_query_pci_devices(child_bus, dev->config[PCI_SECONDARY_BUS]);
1788         }
1789     }
1790 
1791     return info;
1792 }
1793 
1794 static PciDeviceInfo *qmp_query_pci_device(PCIDevice *dev, PCIBus *bus,
1795                                            int bus_num)
1796 {
1797     const pci_class_desc *desc;
1798     PciDeviceInfo *info;
1799     uint8_t type;
1800     int class;
1801 
1802     info = g_new0(PciDeviceInfo, 1);
1803     info->bus = bus_num;
1804     info->slot = PCI_SLOT(dev->devfn);
1805     info->function = PCI_FUNC(dev->devfn);
1806 
1807     info->class_info = g_new0(PciDeviceClass, 1);
1808     class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1809     info->class_info->q_class = class;
1810     desc = get_class_desc(class);
1811     if (desc->desc) {
1812         info->class_info->has_desc = true;
1813         info->class_info->desc = g_strdup(desc->desc);
1814     }
1815 
1816     info->id = g_new0(PciDeviceId, 1);
1817     info->id->vendor = pci_get_word(dev->config + PCI_VENDOR_ID);
1818     info->id->device = pci_get_word(dev->config + PCI_DEVICE_ID);
1819     info->regions = qmp_query_pci_regions(dev);
1820     info->qdev_id = g_strdup(dev->qdev.id ? dev->qdev.id : "");
1821 
1822     info->irq_pin = dev->config[PCI_INTERRUPT_PIN];
1823     if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1824         info->has_irq = true;
1825         info->irq = dev->config[PCI_INTERRUPT_LINE];
1826     }
1827 
1828     type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1829     if (type == PCI_HEADER_TYPE_BRIDGE) {
1830         info->has_pci_bridge = true;
1831         info->pci_bridge = qmp_query_pci_bridge(dev, bus, bus_num);
1832     } else if (type == PCI_HEADER_TYPE_NORMAL) {
1833         info->id->has_subsystem = info->id->has_subsystem_vendor = true;
1834         info->id->subsystem = pci_get_word(dev->config + PCI_SUBSYSTEM_ID);
1835         info->id->subsystem_vendor =
1836             pci_get_word(dev->config + PCI_SUBSYSTEM_VENDOR_ID);
1837     } else if (type == PCI_HEADER_TYPE_CARDBUS) {
1838         info->id->has_subsystem = info->id->has_subsystem_vendor = true;
1839         info->id->subsystem = pci_get_word(dev->config + PCI_CB_SUBSYSTEM_ID);
1840         info->id->subsystem_vendor =
1841             pci_get_word(dev->config + PCI_CB_SUBSYSTEM_VENDOR_ID);
1842     }
1843 
1844     return info;
1845 }
1846 
1847 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num)
1848 {
1849     PciDeviceInfoList *head = NULL, **tail = &head;
1850     PCIDevice *dev;
1851     int devfn;
1852 
1853     for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1854         dev = bus->devices[devfn];
1855         if (dev) {
1856             QAPI_LIST_APPEND(tail, qmp_query_pci_device(dev, bus, bus_num));
1857         }
1858     }
1859 
1860     return head;
1861 }
1862 
1863 static PciInfo *qmp_query_pci_bus(PCIBus *bus, int bus_num)
1864 {
1865     PciInfo *info = NULL;
1866 
1867     bus = pci_find_bus_nr(bus, bus_num);
1868     if (bus) {
1869         info = g_malloc0(sizeof(*info));
1870         info->bus = bus_num;
1871         info->devices = qmp_query_pci_devices(bus, bus_num);
1872     }
1873 
1874     return info;
1875 }
1876 
1877 PciInfoList *qmp_query_pci(Error **errp)
1878 {
1879     PciInfoList *head = NULL, **tail = &head;
1880     PCIHostState *host_bridge;
1881 
1882     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
1883         QAPI_LIST_APPEND(tail,
1884                          qmp_query_pci_bus(host_bridge->bus,
1885                                            pci_bus_num(host_bridge->bus)));
1886     }
1887 
1888     return head;
1889 }
1890 
1891 /* Initialize a PCI NIC.  */
1892 PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1893                                const char *default_model,
1894                                const char *default_devaddr)
1895 {
1896     const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1897     GSList *list;
1898     GPtrArray *pci_nic_models;
1899     PCIBus *bus;
1900     PCIDevice *pci_dev;
1901     DeviceState *dev;
1902     int devfn;
1903     int i;
1904     int dom, busnr;
1905     unsigned slot;
1906 
1907     if (nd->model && !strcmp(nd->model, "virtio")) {
1908         g_free(nd->model);
1909         nd->model = g_strdup("virtio-net-pci");
1910     }
1911 
1912     list = object_class_get_list_sorted(TYPE_PCI_DEVICE, false);
1913     pci_nic_models = g_ptr_array_new();
1914     while (list) {
1915         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, list->data,
1916                                              TYPE_DEVICE);
1917         GSList *next;
1918         if (test_bit(DEVICE_CATEGORY_NETWORK, dc->categories) &&
1919             dc->user_creatable) {
1920             const char *name = object_class_get_name(list->data);
1921             /*
1922              * A network device might also be something else than a NIC, see
1923              * e.g. the "rocker" device. Thus we have to look for the "netdev"
1924              * property, too. Unfortunately, some devices like virtio-net only
1925              * create this property during instance_init, so we have to create
1926              * a temporary instance here to be able to check it.
1927              */
1928             Object *obj = object_new_with_class(OBJECT_CLASS(dc));
1929             if (object_property_find(obj, "netdev")) {
1930                 g_ptr_array_add(pci_nic_models, (gpointer)name);
1931             }
1932             object_unref(obj);
1933         }
1934         next = list->next;
1935         g_slist_free_1(list);
1936         list = next;
1937     }
1938     g_ptr_array_add(pci_nic_models, NULL);
1939 
1940     if (qemu_show_nic_models(nd->model, (const char **)pci_nic_models->pdata)) {
1941         exit(0);
1942     }
1943 
1944     i = qemu_find_nic_model(nd, (const char **)pci_nic_models->pdata,
1945                             default_model);
1946     if (i < 0) {
1947         exit(1);
1948     }
1949 
1950     if (!rootbus) {
1951         error_report("No primary PCI bus");
1952         exit(1);
1953     }
1954 
1955     assert(!rootbus->parent_dev);
1956 
1957     if (!devaddr) {
1958         devfn = -1;
1959         busnr = 0;
1960     } else {
1961         if (pci_parse_devaddr(devaddr, &dom, &busnr, &slot, NULL) < 0) {
1962             error_report("Invalid PCI device address %s for device %s",
1963                          devaddr, nd->model);
1964             exit(1);
1965         }
1966 
1967         if (dom != 0) {
1968             error_report("No support for non-zero PCI domains");
1969             exit(1);
1970         }
1971 
1972         devfn = PCI_DEVFN(slot, 0);
1973     }
1974 
1975     bus = pci_find_bus_nr(rootbus, busnr);
1976     if (!bus) {
1977         error_report("Invalid PCI device address %s for device %s",
1978                      devaddr, nd->model);
1979         exit(1);
1980     }
1981 
1982     pci_dev = pci_new(devfn, nd->model);
1983     dev = &pci_dev->qdev;
1984     qdev_set_nic_properties(dev, nd);
1985     pci_realize_and_unref(pci_dev, bus, &error_fatal);
1986     g_ptr_array_free(pci_nic_models, true);
1987     return pci_dev;
1988 }
1989 
1990 PCIDevice *pci_vga_init(PCIBus *bus)
1991 {
1992     switch (vga_interface_type) {
1993     case VGA_CIRRUS:
1994         return pci_create_simple(bus, -1, "cirrus-vga");
1995     case VGA_QXL:
1996         return pci_create_simple(bus, -1, "qxl-vga");
1997     case VGA_STD:
1998         return pci_create_simple(bus, -1, "VGA");
1999     case VGA_VMWARE:
2000         return pci_create_simple(bus, -1, "vmware-svga");
2001     case VGA_VIRTIO:
2002         return pci_create_simple(bus, -1, "virtio-vga");
2003     case VGA_NONE:
2004     default: /* Other non-PCI types. Checking for unsupported types is already
2005                 done in vl.c. */
2006         return NULL;
2007     }
2008 }
2009 
2010 /* Whether a given bus number is in range of the secondary
2011  * bus of the given bridge device. */
2012 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
2013 {
2014     return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
2015              PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
2016         dev->config[PCI_SECONDARY_BUS] <= bus_num &&
2017         bus_num <= dev->config[PCI_SUBORDINATE_BUS];
2018 }
2019 
2020 /* Whether a given bus number is in a range of a root bus */
2021 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
2022 {
2023     int i;
2024 
2025     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
2026         PCIDevice *dev = bus->devices[i];
2027 
2028         if (dev && PCI_DEVICE_GET_CLASS(dev)->is_bridge) {
2029             if (pci_secondary_bus_in_range(dev, bus_num)) {
2030                 return true;
2031             }
2032         }
2033     }
2034 
2035     return false;
2036 }
2037 
2038 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
2039 {
2040     PCIBus *sec;
2041 
2042     if (!bus) {
2043         return NULL;
2044     }
2045 
2046     if (pci_bus_num(bus) == bus_num) {
2047         return bus;
2048     }
2049 
2050     /* Consider all bus numbers in range for the host pci bridge. */
2051     if (!pci_bus_is_root(bus) &&
2052         !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
2053         return NULL;
2054     }
2055 
2056     /* try child bus */
2057     for (; bus; bus = sec) {
2058         QLIST_FOREACH(sec, &bus->child, sibling) {
2059             if (pci_bus_num(sec) == bus_num) {
2060                 return sec;
2061             }
2062             /* PXB buses assumed to be children of bus 0 */
2063             if (pci_bus_is_root(sec)) {
2064                 if (pci_root_bus_in_range(sec, bus_num)) {
2065                     break;
2066                 }
2067             } else {
2068                 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
2069                     break;
2070                 }
2071             }
2072         }
2073     }
2074 
2075     return NULL;
2076 }
2077 
2078 void pci_for_each_bus_depth_first(PCIBus *bus, pci_bus_ret_fn begin,
2079                                   pci_bus_fn end, void *parent_state)
2080 {
2081     PCIBus *sec;
2082     void *state;
2083 
2084     if (!bus) {
2085         return;
2086     }
2087 
2088     if (begin) {
2089         state = begin(bus, parent_state);
2090     } else {
2091         state = parent_state;
2092     }
2093 
2094     QLIST_FOREACH(sec, &bus->child, sibling) {
2095         pci_for_each_bus_depth_first(sec, begin, end, state);
2096     }
2097 
2098     if (end) {
2099         end(bus, state);
2100     }
2101 }
2102 
2103 
2104 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
2105 {
2106     bus = pci_find_bus_nr(bus, bus_num);
2107 
2108     if (!bus)
2109         return NULL;
2110 
2111     return bus->devices[devfn];
2112 }
2113 
2114 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
2115 {
2116     PCIDevice *pci_dev = (PCIDevice *)qdev;
2117     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
2118     ObjectClass *klass = OBJECT_CLASS(pc);
2119     Error *local_err = NULL;
2120     bool is_default_rom;
2121     uint16_t class_id;
2122 
2123     if (pci_dev->romsize != -1 && !is_power_of_2(pci_dev->romsize)) {
2124         error_setg(errp, "ROM size %u is not a power of two", pci_dev->romsize);
2125         return;
2126     }
2127 
2128     /* initialize cap_present for pci_is_express() and pci_config_size(),
2129      * Note that hybrid PCIs are not set automatically and need to manage
2130      * QEMU_PCI_CAP_EXPRESS manually */
2131     if (object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE) &&
2132        !object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE)) {
2133         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2134     }
2135 
2136     pci_dev = do_pci_register_device(pci_dev,
2137                                      object_get_typename(OBJECT(qdev)),
2138                                      pci_dev->devfn, errp);
2139     if (pci_dev == NULL)
2140         return;
2141 
2142     if (pc->realize) {
2143         pc->realize(pci_dev, &local_err);
2144         if (local_err) {
2145             error_propagate(errp, local_err);
2146             do_pci_unregister_device(pci_dev);
2147             return;
2148         }
2149     }
2150 
2151     if (pci_dev->failover_pair_id) {
2152         if (!pci_bus_is_express(pci_get_bus(pci_dev))) {
2153             error_setg(errp, "failover primary device must be on "
2154                              "PCIExpress bus");
2155             pci_qdev_unrealize(DEVICE(pci_dev));
2156             return;
2157         }
2158         class_id = pci_get_word(pci_dev->config + PCI_CLASS_DEVICE);
2159         if (class_id != PCI_CLASS_NETWORK_ETHERNET) {
2160             error_setg(errp, "failover primary device is not an "
2161                              "Ethernet device");
2162             pci_qdev_unrealize(DEVICE(pci_dev));
2163             return;
2164         }
2165         if ((pci_dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)
2166             || (PCI_FUNC(pci_dev->devfn) != 0)) {
2167             error_setg(errp, "failover: primary device must be in its own "
2168                               "PCI slot");
2169             pci_qdev_unrealize(DEVICE(pci_dev));
2170             return;
2171         }
2172         qdev->allow_unplug_during_migration = true;
2173     }
2174 
2175     /* rom loading */
2176     is_default_rom = false;
2177     if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2178         pci_dev->romfile = g_strdup(pc->romfile);
2179         is_default_rom = true;
2180     }
2181 
2182     pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2183     if (local_err) {
2184         error_propagate(errp, local_err);
2185         pci_qdev_unrealize(DEVICE(pci_dev));
2186         return;
2187     }
2188 
2189     pci_set_power(pci_dev, true);
2190 }
2191 
2192 PCIDevice *pci_new_multifunction(int devfn, bool multifunction,
2193                                  const char *name)
2194 {
2195     DeviceState *dev;
2196 
2197     dev = qdev_new(name);
2198     qdev_prop_set_int32(dev, "addr", devfn);
2199     qdev_prop_set_bit(dev, "multifunction", multifunction);
2200     return PCI_DEVICE(dev);
2201 }
2202 
2203 PCIDevice *pci_new(int devfn, const char *name)
2204 {
2205     return pci_new_multifunction(devfn, false, name);
2206 }
2207 
2208 bool pci_realize_and_unref(PCIDevice *dev, PCIBus *bus, Error **errp)
2209 {
2210     return qdev_realize_and_unref(&dev->qdev, &bus->qbus, errp);
2211 }
2212 
2213 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2214                                            bool multifunction,
2215                                            const char *name)
2216 {
2217     PCIDevice *dev = pci_new_multifunction(devfn, multifunction, name);
2218     pci_realize_and_unref(dev, bus, &error_fatal);
2219     return dev;
2220 }
2221 
2222 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2223 {
2224     return pci_create_simple_multifunction(bus, devfn, false, name);
2225 }
2226 
2227 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2228 {
2229     int offset = PCI_CONFIG_HEADER_SIZE;
2230     int i;
2231     for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2232         if (pdev->used[i])
2233             offset = i + 1;
2234         else if (i - offset + 1 == size)
2235             return offset;
2236     }
2237     return 0;
2238 }
2239 
2240 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2241                                         uint8_t *prev_p)
2242 {
2243     uint8_t next, prev;
2244 
2245     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2246         return 0;
2247 
2248     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2249          prev = next + PCI_CAP_LIST_NEXT)
2250         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2251             break;
2252 
2253     if (prev_p)
2254         *prev_p = prev;
2255     return next;
2256 }
2257 
2258 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2259 {
2260     uint8_t next, prev, found = 0;
2261 
2262     if (!(pdev->used[offset])) {
2263         return 0;
2264     }
2265 
2266     assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2267 
2268     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2269          prev = next + PCI_CAP_LIST_NEXT) {
2270         if (next <= offset && next > found) {
2271             found = next;
2272         }
2273     }
2274     return found;
2275 }
2276 
2277 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2278    This is needed for an option rom which is used for more than one device. */
2279 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, uint32_t size)
2280 {
2281     uint16_t vendor_id;
2282     uint16_t device_id;
2283     uint16_t rom_vendor_id;
2284     uint16_t rom_device_id;
2285     uint16_t rom_magic;
2286     uint16_t pcir_offset;
2287     uint8_t checksum;
2288 
2289     /* Words in rom data are little endian (like in PCI configuration),
2290        so they can be read / written with pci_get_word / pci_set_word. */
2291 
2292     /* Only a valid rom will be patched. */
2293     rom_magic = pci_get_word(ptr);
2294     if (rom_magic != 0xaa55) {
2295         PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2296         return;
2297     }
2298     pcir_offset = pci_get_word(ptr + 0x18);
2299     if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2300         PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2301         return;
2302     }
2303 
2304     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2305     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2306     rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2307     rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2308 
2309     PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2310                 vendor_id, device_id, rom_vendor_id, rom_device_id);
2311 
2312     checksum = ptr[6];
2313 
2314     if (vendor_id != rom_vendor_id) {
2315         /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2316         checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2317         checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2318         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2319         ptr[6] = checksum;
2320         pci_set_word(ptr + pcir_offset + 4, vendor_id);
2321     }
2322 
2323     if (device_id != rom_device_id) {
2324         /* Patch device id and checksum (at offset 6 for etherboot roms). */
2325         checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2326         checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2327         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2328         ptr[6] = checksum;
2329         pci_set_word(ptr + pcir_offset + 6, device_id);
2330     }
2331 }
2332 
2333 /* Add an option rom for the device */
2334 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2335                                Error **errp)
2336 {
2337     int64_t size;
2338     char *path;
2339     void *ptr;
2340     char name[32];
2341     const VMStateDescription *vmsd;
2342 
2343     if (!pdev->romfile)
2344         return;
2345     if (strlen(pdev->romfile) == 0)
2346         return;
2347 
2348     if (!pdev->rom_bar) {
2349         /*
2350          * Load rom via fw_cfg instead of creating a rom bar,
2351          * for 0.11 compatibility.
2352          */
2353         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2354 
2355         /*
2356          * Hot-plugged devices can't use the option ROM
2357          * if the rom bar is disabled.
2358          */
2359         if (DEVICE(pdev)->hotplugged) {
2360             error_setg(errp, "Hot-plugged device without ROM bar"
2361                        " can't have an option ROM");
2362             return;
2363         }
2364 
2365         if (class == 0x0300) {
2366             rom_add_vga(pdev->romfile);
2367         } else {
2368             rom_add_option(pdev->romfile, -1);
2369         }
2370         return;
2371     }
2372 
2373     path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2374     if (path == NULL) {
2375         path = g_strdup(pdev->romfile);
2376     }
2377 
2378     size = get_image_size(path);
2379     if (size < 0) {
2380         error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2381         g_free(path);
2382         return;
2383     } else if (size == 0) {
2384         error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2385         g_free(path);
2386         return;
2387     } else if (size > 2 * GiB) {
2388         error_setg(errp, "romfile \"%s\" too large (size cannot exceed 2 GiB)",
2389                    pdev->romfile);
2390         g_free(path);
2391         return;
2392     }
2393     if (pdev->romsize != -1) {
2394         if (size > pdev->romsize) {
2395             error_setg(errp, "romfile \"%s\" (%u bytes) is too large for ROM size %u",
2396                        pdev->romfile, (uint32_t)size, pdev->romsize);
2397             g_free(path);
2398             return;
2399         }
2400     } else {
2401         pdev->romsize = pow2ceil(size);
2402     }
2403 
2404     vmsd = qdev_get_vmsd(DEVICE(pdev));
2405 
2406     if (vmsd) {
2407         snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2408     } else {
2409         snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2410     }
2411     pdev->has_rom = true;
2412     memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, pdev->romsize, &error_fatal);
2413     ptr = memory_region_get_ram_ptr(&pdev->rom);
2414     if (load_image_size(path, ptr, size) < 0) {
2415         error_setg(errp, "failed to load romfile \"%s\"", pdev->romfile);
2416         g_free(path);
2417         return;
2418     }
2419     g_free(path);
2420 
2421     if (is_default_rom) {
2422         /* Only the default rom images will be patched (if needed). */
2423         pci_patch_ids(pdev, ptr, size);
2424     }
2425 
2426     pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2427 }
2428 
2429 static void pci_del_option_rom(PCIDevice *pdev)
2430 {
2431     if (!pdev->has_rom)
2432         return;
2433 
2434     vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2435     pdev->has_rom = false;
2436 }
2437 
2438 /*
2439  * On success, pci_add_capability() returns a positive value
2440  * that the offset of the pci capability.
2441  * On failure, it sets an error and returns a negative error
2442  * code.
2443  */
2444 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2445                        uint8_t offset, uint8_t size,
2446                        Error **errp)
2447 {
2448     uint8_t *config;
2449     int i, overlapping_cap;
2450 
2451     if (!offset) {
2452         offset = pci_find_space(pdev, size);
2453         /* out of PCI config space is programming error */
2454         assert(offset);
2455     } else {
2456         /* Verify that capabilities don't overlap.  Note: device assignment
2457          * depends on this check to verify that the device is not broken.
2458          * Should never trigger for emulated devices, but it's helpful
2459          * for debugging these. */
2460         for (i = offset; i < offset + size; i++) {
2461             overlapping_cap = pci_find_capability_at_offset(pdev, i);
2462             if (overlapping_cap) {
2463                 error_setg(errp, "%s:%02x:%02x.%x "
2464                            "Attempt to add PCI capability %x at offset "
2465                            "%x overlaps existing capability %x at offset %x",
2466                            pci_root_bus_path(pdev), pci_dev_bus_num(pdev),
2467                            PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2468                            cap_id, offset, overlapping_cap, i);
2469                 return -EINVAL;
2470             }
2471         }
2472     }
2473 
2474     config = pdev->config + offset;
2475     config[PCI_CAP_LIST_ID] = cap_id;
2476     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2477     pdev->config[PCI_CAPABILITY_LIST] = offset;
2478     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2479     memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2480     /* Make capability read-only by default */
2481     memset(pdev->wmask + offset, 0, size);
2482     /* Check capability by default */
2483     memset(pdev->cmask + offset, 0xFF, size);
2484     return offset;
2485 }
2486 
2487 /* Unlink capability from the pci config space. */
2488 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2489 {
2490     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2491     if (!offset)
2492         return;
2493     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2494     /* Make capability writable again */
2495     memset(pdev->wmask + offset, 0xff, size);
2496     memset(pdev->w1cmask + offset, 0, size);
2497     /* Clear cmask as device-specific registers can't be checked */
2498     memset(pdev->cmask + offset, 0, size);
2499     memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2500 
2501     if (!pdev->config[PCI_CAPABILITY_LIST])
2502         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2503 }
2504 
2505 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2506 {
2507     return pci_find_capability_list(pdev, cap_id, NULL);
2508 }
2509 
2510 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2511 {
2512     PCIDevice *d = (PCIDevice *)dev;
2513     const pci_class_desc *desc;
2514     char ctxt[64];
2515     PCIIORegion *r;
2516     int i, class;
2517 
2518     class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2519     desc = pci_class_descriptions;
2520     while (desc->desc && class != desc->class)
2521         desc++;
2522     if (desc->desc) {
2523         snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2524     } else {
2525         snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2526     }
2527 
2528     monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2529                    "pci id %04x:%04x (sub %04x:%04x)\n",
2530                    indent, "", ctxt, pci_dev_bus_num(d),
2531                    PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2532                    pci_get_word(d->config + PCI_VENDOR_ID),
2533                    pci_get_word(d->config + PCI_DEVICE_ID),
2534                    pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2535                    pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2536     for (i = 0; i < PCI_NUM_REGIONS; i++) {
2537         r = &d->io_regions[i];
2538         if (!r->size)
2539             continue;
2540         monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2541                        " [0x%"FMT_PCIBUS"]\n",
2542                        indent, "",
2543                        i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2544                        r->addr, r->addr + r->size - 1);
2545     }
2546 }
2547 
2548 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2549 {
2550     PCIDevice *d = (PCIDevice *)dev;
2551     const char *name = NULL;
2552     const pci_class_desc *desc =  pci_class_descriptions;
2553     int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2554 
2555     while (desc->desc &&
2556           (class & ~desc->fw_ign_bits) !=
2557           (desc->class & ~desc->fw_ign_bits)) {
2558         desc++;
2559     }
2560 
2561     if (desc->desc) {
2562         name = desc->fw_name;
2563     }
2564 
2565     if (name) {
2566         pstrcpy(buf, len, name);
2567     } else {
2568         snprintf(buf, len, "pci%04x,%04x",
2569                  pci_get_word(d->config + PCI_VENDOR_ID),
2570                  pci_get_word(d->config + PCI_DEVICE_ID));
2571     }
2572 
2573     return buf;
2574 }
2575 
2576 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2577 {
2578     PCIDevice *d = (PCIDevice *)dev;
2579     char path[50], name[33];
2580     int off;
2581 
2582     off = snprintf(path, sizeof(path), "%s@%x",
2583                    pci_dev_fw_name(dev, name, sizeof name),
2584                    PCI_SLOT(d->devfn));
2585     if (PCI_FUNC(d->devfn))
2586         snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2587     return g_strdup(path);
2588 }
2589 
2590 static char *pcibus_get_dev_path(DeviceState *dev)
2591 {
2592     PCIDevice *d = container_of(dev, PCIDevice, qdev);
2593     PCIDevice *t;
2594     int slot_depth;
2595     /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2596      * 00 is added here to make this format compatible with
2597      * domain:Bus:Slot.Func for systems without nested PCI bridges.
2598      * Slot.Function list specifies the slot and function numbers for all
2599      * devices on the path from root to the specific device. */
2600     const char *root_bus_path;
2601     int root_bus_len;
2602     char slot[] = ":SS.F";
2603     int slot_len = sizeof slot - 1 /* For '\0' */;
2604     int path_len;
2605     char *path, *p;
2606     int s;
2607 
2608     root_bus_path = pci_root_bus_path(d);
2609     root_bus_len = strlen(root_bus_path);
2610 
2611     /* Calculate # of slots on path between device and root. */;
2612     slot_depth = 0;
2613     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2614         ++slot_depth;
2615     }
2616 
2617     path_len = root_bus_len + slot_len * slot_depth;
2618 
2619     /* Allocate memory, fill in the terminating null byte. */
2620     path = g_malloc(path_len + 1 /* For '\0' */);
2621     path[path_len] = '\0';
2622 
2623     memcpy(path, root_bus_path, root_bus_len);
2624 
2625     /* Fill in slot numbers. We walk up from device to root, so need to print
2626      * them in the reverse order, last to first. */
2627     p = path + path_len;
2628     for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2629         p -= slot_len;
2630         s = snprintf(slot, sizeof slot, ":%02x.%x",
2631                      PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2632         assert(s == slot_len);
2633         memcpy(p, slot, slot_len);
2634     }
2635 
2636     return path;
2637 }
2638 
2639 static int pci_qdev_find_recursive(PCIBus *bus,
2640                                    const char *id, PCIDevice **pdev)
2641 {
2642     DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2643     if (!qdev) {
2644         return -ENODEV;
2645     }
2646 
2647     /* roughly check if given qdev is pci device */
2648     if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2649         *pdev = PCI_DEVICE(qdev);
2650         return 0;
2651     }
2652     return -EINVAL;
2653 }
2654 
2655 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2656 {
2657     PCIHostState *host_bridge;
2658     int rc = -ENODEV;
2659 
2660     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2661         int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2662         if (!tmp) {
2663             rc = 0;
2664             break;
2665         }
2666         if (tmp != -ENODEV) {
2667             rc = tmp;
2668         }
2669     }
2670 
2671     return rc;
2672 }
2673 
2674 MemoryRegion *pci_address_space(PCIDevice *dev)
2675 {
2676     return pci_get_bus(dev)->address_space_mem;
2677 }
2678 
2679 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2680 {
2681     return pci_get_bus(dev)->address_space_io;
2682 }
2683 
2684 static void pci_device_class_init(ObjectClass *klass, void *data)
2685 {
2686     DeviceClass *k = DEVICE_CLASS(klass);
2687 
2688     k->realize = pci_qdev_realize;
2689     k->unrealize = pci_qdev_unrealize;
2690     k->bus_type = TYPE_PCI_BUS;
2691     device_class_set_props(k, pci_props);
2692 }
2693 
2694 static void pci_device_class_base_init(ObjectClass *klass, void *data)
2695 {
2696     if (!object_class_is_abstract(klass)) {
2697         ObjectClass *conventional =
2698             object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE);
2699         ObjectClass *pcie =
2700             object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE);
2701         assert(conventional || pcie);
2702     }
2703 }
2704 
2705 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2706 {
2707     PCIBus *bus = pci_get_bus(dev);
2708     PCIBus *iommu_bus = bus;
2709     uint8_t devfn = dev->devfn;
2710 
2711     while (iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2712         PCIBus *parent_bus = pci_get_bus(iommu_bus->parent_dev);
2713 
2714         /*
2715          * The requester ID of the provided device may be aliased, as seen from
2716          * the IOMMU, due to topology limitations.  The IOMMU relies on a
2717          * requester ID to provide a unique AddressSpace for devices, but
2718          * conventional PCI buses pre-date such concepts.  Instead, the PCIe-
2719          * to-PCI bridge creates and accepts transactions on behalf of down-
2720          * stream devices.  When doing so, all downstream devices are masked
2721          * (aliased) behind a single requester ID.  The requester ID used
2722          * depends on the format of the bridge devices.  Proper PCIe-to-PCI
2723          * bridges, with a PCIe capability indicating such, follow the
2724          * guidelines of chapter 2.3 of the PCIe-to-PCI/X bridge specification,
2725          * where the bridge uses the seconary bus as the bridge portion of the
2726          * requester ID and devfn of 00.0.  For other bridges, typically those
2727          * found on the root complex such as the dmi-to-pci-bridge, we follow
2728          * the convention of typical bare-metal hardware, which uses the
2729          * requester ID of the bridge itself.  There are device specific
2730          * exceptions to these rules, but these are the defaults that the
2731          * Linux kernel uses when determining DMA aliases itself and believed
2732          * to be true for the bare metal equivalents of the devices emulated
2733          * in QEMU.
2734          */
2735         if (!pci_bus_is_express(iommu_bus)) {
2736             PCIDevice *parent = iommu_bus->parent_dev;
2737 
2738             if (pci_is_express(parent) &&
2739                 pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
2740                 devfn = PCI_DEVFN(0, 0);
2741                 bus = iommu_bus;
2742             } else {
2743                 devfn = parent->devfn;
2744                 bus = parent_bus;
2745             }
2746         }
2747 
2748         iommu_bus = parent_bus;
2749     }
2750     if (!pci_bus_bypass_iommu(bus) && iommu_bus && iommu_bus->iommu_fn) {
2751         return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, devfn);
2752     }
2753     return &address_space_memory;
2754 }
2755 
2756 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2757 {
2758     bus->iommu_fn = fn;
2759     bus->iommu_opaque = opaque;
2760 }
2761 
2762 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2763 {
2764     Range *range = opaque;
2765     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2766     uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2767     int i;
2768 
2769     if (!(cmd & PCI_COMMAND_MEMORY)) {
2770         return;
2771     }
2772 
2773     if (pc->is_bridge) {
2774         pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2775         pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2776 
2777         base = MAX(base, 0x1ULL << 32);
2778 
2779         if (limit >= base) {
2780             Range pref_range;
2781             range_set_bounds(&pref_range, base, limit);
2782             range_extend(range, &pref_range);
2783         }
2784     }
2785     for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2786         PCIIORegion *r = &dev->io_regions[i];
2787         pcibus_t lob, upb;
2788         Range region_range;
2789 
2790         if (!r->size ||
2791             (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2792             !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2793             continue;
2794         }
2795 
2796         lob = pci_bar_address(dev, i, r->type, r->size);
2797         upb = lob + r->size - 1;
2798         if (lob == PCI_BAR_UNMAPPED) {
2799             continue;
2800         }
2801 
2802         lob = MAX(lob, 0x1ULL << 32);
2803 
2804         if (upb >= lob) {
2805             range_set_bounds(&region_range, lob, upb);
2806             range_extend(range, &region_range);
2807         }
2808     }
2809 }
2810 
2811 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2812 {
2813     range_make_empty(range);
2814     pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2815 }
2816 
2817 static bool pcie_has_upstream_port(PCIDevice *dev)
2818 {
2819     PCIDevice *parent_dev = pci_bridge_get_device(pci_get_bus(dev));
2820 
2821     /* Device associated with an upstream port.
2822      * As there are several types of these, it's easier to check the
2823      * parent device: upstream ports are always connected to
2824      * root or downstream ports.
2825      */
2826     return parent_dev &&
2827         pci_is_express(parent_dev) &&
2828         parent_dev->exp.exp_cap &&
2829         (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2830          pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2831 }
2832 
2833 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2834 {
2835     PCIBus *bus = pci_get_bus(pci_dev);
2836 
2837     if(pcie_has_upstream_port(pci_dev)) {
2838         /* With an upstream PCIe port, we only support 1 device at slot 0 */
2839         return bus->devices[0];
2840     } else {
2841         /* Other bus types might support multiple devices at slots 0-31 */
2842         return bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2843     }
2844 }
2845 
2846 MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2847 {
2848     MSIMessage msg;
2849     if (msix_enabled(dev)) {
2850         msg = msix_get_message(dev, vector);
2851     } else if (msi_enabled(dev)) {
2852         msg = msi_get_message(dev, vector);
2853     } else {
2854         /* Should never happen */
2855         error_report("%s: unknown interrupt type", __func__);
2856         abort();
2857     }
2858     return msg;
2859 }
2860 
2861 void pci_set_power(PCIDevice *d, bool state)
2862 {
2863     if (d->has_power == state) {
2864         return;
2865     }
2866 
2867     d->has_power = state;
2868     pci_update_mappings(d);
2869     memory_region_set_enabled(&d->bus_master_enable_region,
2870                               (pci_get_word(d->config + PCI_COMMAND)
2871                                & PCI_COMMAND_MASTER) && d->has_power);
2872     if (!d->has_power) {
2873         pci_device_reset(d);
2874     }
2875 }
2876 
2877 static const TypeInfo pci_device_type_info = {
2878     .name = TYPE_PCI_DEVICE,
2879     .parent = TYPE_DEVICE,
2880     .instance_size = sizeof(PCIDevice),
2881     .abstract = true,
2882     .class_size = sizeof(PCIDeviceClass),
2883     .class_init = pci_device_class_init,
2884     .class_base_init = pci_device_class_base_init,
2885 };
2886 
2887 static void pci_register_types(void)
2888 {
2889     type_register_static(&pci_bus_info);
2890     type_register_static(&pcie_bus_info);
2891     type_register_static(&conventional_pci_interface_info);
2892     type_register_static(&pcie_interface_info);
2893     type_register_static(&pci_device_type_info);
2894 }
2895 
2896 type_init(pci_register_types)
2897