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