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