ar7: Remove conditional compilation
[qemu/ar7.git] / hw / pci / pci.c
blobe5476cc3ac187faf4e74fbf622c8a0e6496411d0
1 /*
2 * QEMU PCI bus manager
4 * Copyright (c) 2004 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu/osdep.h"
25 #include "hw/hw.h"
26 #include "hw/pci/pci.h"
27 #include "hw/pci/pci_bridge.h"
28 #include "hw/pci/pci_bus.h"
29 #include "hw/pci/pci_host.h"
30 #include "monitor/monitor.h"
31 #include "net/net.h"
32 #include "sysemu/sysemu.h"
33 #include "hw/loader.h"
34 #include "qemu/error-report.h"
35 #include "qemu/range.h"
36 #include "qmp-commands.h"
37 #include "trace.h"
38 #include "hw/pci/msi.h"
39 #include "hw/pci/msix.h"
40 #include "exec/address-spaces.h"
41 #include "hw/hotplug.h"
42 #include "hw/boards.h"
43 #include "qemu/cutils.h"
45 //#define DEBUG_PCI
46 #ifdef DEBUG_PCI
47 # define PCI_DPRINTF(format, ...) printf(format, ## __VA_ARGS__)
48 #else
49 # define PCI_DPRINTF(format, ...) do { } while (0)
50 #endif
52 bool pci_available = true;
54 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
55 static char *pcibus_get_dev_path(DeviceState *dev);
56 static char *pcibus_get_fw_dev_path(DeviceState *dev);
57 static void pcibus_reset(BusState *qbus);
59 static Property pci_props[] = {
60 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
61 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
62 DEFINE_PROP_UINT32("rombar", PCIDevice, rom_bar, 1),
63 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
64 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
65 DEFINE_PROP_BIT("command_serr_enable", PCIDevice, cap_present,
66 QEMU_PCI_CAP_SERR_BITNR, true),
67 DEFINE_PROP_BIT("x-pcie-lnksta-dllla", PCIDevice, cap_present,
68 QEMU_PCIE_LNKSTA_DLLLA_BITNR, true),
69 DEFINE_PROP_BIT("x-pcie-extcap-init", PCIDevice, cap_present,
70 QEMU_PCIE_EXTCAP_INIT_BITNR, true),
71 DEFINE_PROP_END_OF_LIST()
74 static const VMStateDescription vmstate_pcibus = {
75 .name = "PCIBUS",
76 .version_id = 1,
77 .minimum_version_id = 1,
78 .fields = (VMStateField[]) {
79 VMSTATE_INT32_EQUAL(nirq, PCIBus, NULL),
80 VMSTATE_VARRAY_INT32(irq_count, PCIBus,
81 nirq, 0, vmstate_info_int32,
82 int32_t),
83 VMSTATE_END_OF_LIST()
87 static void pci_init_bus_master(PCIDevice *pci_dev)
89 AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);
91 memory_region_init_alias(&pci_dev->bus_master_enable_region,
92 OBJECT(pci_dev), "bus master",
93 dma_as->root, 0, memory_region_size(dma_as->root));
94 memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
95 memory_region_add_subregion(&pci_dev->bus_master_container_region, 0,
96 &pci_dev->bus_master_enable_region);
99 static void pcibus_machine_done(Notifier *notifier, void *data)
101 PCIBus *bus = container_of(notifier, PCIBus, machine_done);
102 int i;
104 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
105 if (bus->devices[i]) {
106 pci_init_bus_master(bus->devices[i]);
111 static void pci_bus_realize(BusState *qbus, Error **errp)
113 PCIBus *bus = PCI_BUS(qbus);
115 bus->machine_done.notify = pcibus_machine_done;
116 qemu_add_machine_init_done_notifier(&bus->machine_done);
118 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
121 static void pci_bus_unrealize(BusState *qbus, Error **errp)
123 PCIBus *bus = PCI_BUS(qbus);
125 qemu_remove_machine_init_done_notifier(&bus->machine_done);
127 vmstate_unregister(NULL, &vmstate_pcibus, bus);
130 static bool pcibus_is_root(PCIBus *bus)
132 return !bus->parent_dev;
135 static int pcibus_num(PCIBus *bus)
137 if (pcibus_is_root(bus)) {
138 return 0; /* pci host bridge */
140 return bus->parent_dev->config[PCI_SECONDARY_BUS];
143 static uint16_t pcibus_numa_node(PCIBus *bus)
145 return NUMA_NODE_UNASSIGNED;
148 static void pci_bus_class_init(ObjectClass *klass, void *data)
150 BusClass *k = BUS_CLASS(klass);
151 PCIBusClass *pbc = PCI_BUS_CLASS(klass);
153 k->print_dev = pcibus_dev_print;
154 k->get_dev_path = pcibus_get_dev_path;
155 k->get_fw_dev_path = pcibus_get_fw_dev_path;
156 k->realize = pci_bus_realize;
157 k->unrealize = pci_bus_unrealize;
158 k->reset = pcibus_reset;
160 pbc->is_root = pcibus_is_root;
161 pbc->bus_num = pcibus_num;
162 pbc->numa_node = pcibus_numa_node;
165 static const TypeInfo pci_bus_info = {
166 .name = TYPE_PCI_BUS,
167 .parent = TYPE_BUS,
168 .instance_size = sizeof(PCIBus),
169 .class_size = sizeof(PCIBusClass),
170 .class_init = pci_bus_class_init,
173 static const TypeInfo pcie_bus_info = {
174 .name = TYPE_PCIE_BUS,
175 .parent = TYPE_PCI_BUS,
178 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num);
179 static void pci_update_mappings(PCIDevice *d);
180 static void pci_irq_handler(void *opaque, int irq_num, int level);
181 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
182 static void pci_del_option_rom(PCIDevice *pdev);
184 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
185 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
187 static QLIST_HEAD(, PCIHostState) pci_host_bridges;
189 int pci_bar(PCIDevice *d, int reg)
191 uint8_t type;
193 if (reg != PCI_ROM_SLOT)
194 return PCI_BASE_ADDRESS_0 + reg * 4;
196 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
197 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
200 static inline int pci_irq_state(PCIDevice *d, int irq_num)
202 return (d->irq_state >> irq_num) & 0x1;
205 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
207 d->irq_state &= ~(0x1 << irq_num);
208 d->irq_state |= level << irq_num;
211 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
213 PCIBus *bus;
214 for (;;) {
215 bus = pci_dev->bus;
216 irq_num = bus->map_irq(pci_dev, irq_num);
217 if (bus->set_irq)
218 break;
219 pci_dev = bus->parent_dev;
221 bus->irq_count[irq_num] += change;
222 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
225 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
227 assert(irq_num >= 0);
228 assert(irq_num < bus->nirq);
229 return !!bus->irq_count[irq_num];
232 /* Update interrupt status bit in config space on interrupt
233 * state change. */
234 static void pci_update_irq_status(PCIDevice *dev)
236 if (dev->irq_state) {
237 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
238 } else {
239 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
243 void pci_device_deassert_intx(PCIDevice *dev)
245 int i;
246 for (i = 0; i < PCI_NUM_PINS; ++i) {
247 pci_irq_handler(dev, i, 0);
251 static void pci_do_device_reset(PCIDevice *dev)
253 int r;
255 pci_device_deassert_intx(dev);
256 assert(dev->irq_state == 0);
258 /* Clear all writable bits */
259 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
260 pci_get_word(dev->wmask + PCI_COMMAND) |
261 pci_get_word(dev->w1cmask + PCI_COMMAND));
262 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
263 pci_get_word(dev->wmask + PCI_STATUS) |
264 pci_get_word(dev->w1cmask + PCI_STATUS));
265 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
266 dev->config[PCI_INTERRUPT_LINE] = 0x0;
267 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
268 PCIIORegion *region = &dev->io_regions[r];
269 if (!region->size) {
270 continue;
273 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
274 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
275 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
276 } else {
277 pci_set_long(dev->config + pci_bar(dev, r), region->type);
280 pci_update_mappings(dev);
282 msi_reset(dev);
283 msix_reset(dev);
287 * This function is called on #RST and FLR.
288 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
290 void pci_device_reset(PCIDevice *dev)
292 qdev_reset_all(&dev->qdev);
293 pci_do_device_reset(dev);
297 * Trigger pci bus reset under a given bus.
298 * Called via qbus_reset_all on RST# assert, after the devices
299 * have been reset qdev_reset_all-ed already.
301 static void pcibus_reset(BusState *qbus)
303 PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
304 int i;
306 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
307 if (bus->devices[i]) {
308 pci_do_device_reset(bus->devices[i]);
312 for (i = 0; i < bus->nirq; i++) {
313 assert(bus->irq_count[i] == 0);
317 static void pci_host_bus_register(DeviceState *host)
319 PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
321 QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
324 PCIBus *pci_find_primary_bus(void)
326 PCIBus *primary_bus = NULL;
327 PCIHostState *host;
329 QLIST_FOREACH(host, &pci_host_bridges, next) {
330 if (primary_bus) {
331 /* We have multiple root buses, refuse to select a primary */
332 return NULL;
334 primary_bus = host->bus;
337 return primary_bus;
340 PCIBus *pci_device_root_bus(const PCIDevice *d)
342 PCIBus *bus = d->bus;
344 while (!pci_bus_is_root(bus)) {
345 d = bus->parent_dev;
346 assert(d != NULL);
348 bus = d->bus;
351 return bus;
354 const char *pci_root_bus_path(PCIDevice *dev)
356 PCIBus *rootbus = pci_device_root_bus(dev);
357 PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
358 PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
360 assert(host_bridge->bus == rootbus);
362 if (hc->root_bus_path) {
363 return (*hc->root_bus_path)(host_bridge, rootbus);
366 return rootbus->qbus.name;
369 static void pci_bus_init(PCIBus *bus, DeviceState *parent,
370 MemoryRegion *address_space_mem,
371 MemoryRegion *address_space_io,
372 uint8_t devfn_min)
374 assert(PCI_FUNC(devfn_min) == 0);
375 bus->devfn_min = devfn_min;
376 bus->slot_reserved_mask = 0x0;
377 bus->address_space_mem = address_space_mem;
378 bus->address_space_io = address_space_io;
380 /* host bridge */
381 QLIST_INIT(&bus->child);
383 pci_host_bus_register(parent);
386 bool pci_bus_is_express(PCIBus *bus)
388 return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
391 bool pci_bus_is_root(PCIBus *bus)
393 return PCI_BUS_GET_CLASS(bus)->is_root(bus);
396 void pci_bus_new_inplace(PCIBus *bus, size_t bus_size, DeviceState *parent,
397 const char *name,
398 MemoryRegion *address_space_mem,
399 MemoryRegion *address_space_io,
400 uint8_t devfn_min, const char *typename)
402 qbus_create_inplace(bus, bus_size, typename, parent, name);
403 pci_bus_init(bus, parent, address_space_mem, address_space_io, devfn_min);
406 PCIBus *pci_bus_new(DeviceState *parent, const char *name,
407 MemoryRegion *address_space_mem,
408 MemoryRegion *address_space_io,
409 uint8_t devfn_min, const char *typename)
411 PCIBus *bus;
413 bus = PCI_BUS(qbus_create(typename, parent, name));
414 pci_bus_init(bus, parent, address_space_mem, address_space_io, devfn_min);
415 return bus;
418 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
419 void *irq_opaque, int nirq)
421 bus->set_irq = set_irq;
422 bus->map_irq = map_irq;
423 bus->irq_opaque = irq_opaque;
424 bus->nirq = nirq;
425 bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
428 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
429 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
430 void *irq_opaque,
431 MemoryRegion *address_space_mem,
432 MemoryRegion *address_space_io,
433 uint8_t devfn_min, int nirq, const char *typename)
435 PCIBus *bus;
437 bus = pci_bus_new(parent, name, address_space_mem,
438 address_space_io, devfn_min, typename);
439 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
440 return bus;
443 int pci_bus_num(PCIBus *s)
445 return PCI_BUS_GET_CLASS(s)->bus_num(s);
448 int pci_bus_numa_node(PCIBus *bus)
450 return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
453 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size,
454 VMStateField *field)
456 PCIDevice *s = container_of(pv, PCIDevice, config);
457 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(s);
458 uint8_t *config;
459 int i;
461 assert(size == pci_config_size(s));
462 config = g_malloc(size);
464 qemu_get_buffer(f, config, size);
465 for (i = 0; i < size; ++i) {
466 if ((config[i] ^ s->config[i]) &
467 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
468 error_report("%s: Bad config data: i=0x%x read: %x device: %x "
469 "cmask: %x wmask: %x w1cmask:%x", __func__,
470 i, config[i], s->config[i],
471 s->cmask[i], s->wmask[i], s->w1cmask[i]);
472 g_free(config);
473 return -EINVAL;
476 memcpy(s->config, config, size);
478 pci_update_mappings(s);
479 if (pc->is_bridge) {
480 PCIBridge *b = PCI_BRIDGE(s);
481 pci_bridge_update_mappings(b);
484 memory_region_set_enabled(&s->bus_master_enable_region,
485 pci_get_word(s->config + PCI_COMMAND)
486 & PCI_COMMAND_MASTER);
488 g_free(config);
489 return 0;
492 /* just put buffer */
493 static int put_pci_config_device(QEMUFile *f, void *pv, size_t size,
494 VMStateField *field, QJSON *vmdesc)
496 const uint8_t **v = pv;
497 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
498 qemu_put_buffer(f, *v, size);
500 return 0;
503 static VMStateInfo vmstate_info_pci_config = {
504 .name = "pci config",
505 .get = get_pci_config_device,
506 .put = put_pci_config_device,
509 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size,
510 VMStateField *field)
512 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
513 uint32_t irq_state[PCI_NUM_PINS];
514 int i;
515 for (i = 0; i < PCI_NUM_PINS; ++i) {
516 irq_state[i] = qemu_get_be32(f);
517 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
518 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
519 irq_state[i]);
520 return -EINVAL;
524 for (i = 0; i < PCI_NUM_PINS; ++i) {
525 pci_set_irq_state(s, i, irq_state[i]);
528 return 0;
531 static int put_pci_irq_state(QEMUFile *f, void *pv, size_t size,
532 VMStateField *field, QJSON *vmdesc)
534 int i;
535 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
537 for (i = 0; i < PCI_NUM_PINS; ++i) {
538 qemu_put_be32(f, pci_irq_state(s, i));
541 return 0;
544 static VMStateInfo vmstate_info_pci_irq_state = {
545 .name = "pci irq state",
546 .get = get_pci_irq_state,
547 .put = put_pci_irq_state,
550 static bool migrate_is_pcie(void *opaque, int version_id)
552 return pci_is_express((PCIDevice *)opaque);
555 static bool migrate_is_not_pcie(void *opaque, int version_id)
557 return !pci_is_express((PCIDevice *)opaque);
560 const VMStateDescription vmstate_pci_device = {
561 .name = "PCIDevice",
562 .version_id = 2,
563 .minimum_version_id = 1,
564 .fields = (VMStateField[]) {
565 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
566 VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
567 migrate_is_not_pcie,
568 0, vmstate_info_pci_config,
569 PCI_CONFIG_SPACE_SIZE),
570 VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
571 migrate_is_pcie,
572 0, vmstate_info_pci_config,
573 PCIE_CONFIG_SPACE_SIZE),
574 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
575 vmstate_info_pci_irq_state,
576 PCI_NUM_PINS * sizeof(int32_t)),
577 VMSTATE_END_OF_LIST()
582 void pci_device_save(PCIDevice *s, QEMUFile *f)
584 /* Clear interrupt status bit: it is implicit
585 * in irq_state which we are saving.
586 * This makes us compatible with old devices
587 * which never set or clear this bit. */
588 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
589 vmstate_save_state(f, &vmstate_pci_device, s, NULL);
590 /* Restore the interrupt status bit. */
591 pci_update_irq_status(s);
594 int pci_device_load(PCIDevice *s, QEMUFile *f)
596 int ret;
597 ret = vmstate_load_state(f, &vmstate_pci_device, s, s->version_id);
598 /* Restore the interrupt status bit. */
599 pci_update_irq_status(s);
600 return ret;
603 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
605 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
606 pci_default_sub_vendor_id);
607 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
608 pci_default_sub_device_id);
612 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
613 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
615 static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
616 unsigned int *slotp, unsigned int *funcp)
618 const char *p;
619 char *e;
620 unsigned long val;
621 unsigned long dom = 0, bus = 0;
622 unsigned int slot = 0;
623 unsigned int func = 0;
625 p = addr;
626 val = strtoul(p, &e, 16);
627 if (e == p)
628 return -1;
629 if (*e == ':') {
630 bus = val;
631 p = e + 1;
632 val = strtoul(p, &e, 16);
633 if (e == p)
634 return -1;
635 if (*e == ':') {
636 dom = bus;
637 bus = val;
638 p = e + 1;
639 val = strtoul(p, &e, 16);
640 if (e == p)
641 return -1;
645 slot = val;
647 if (funcp != NULL) {
648 if (*e != '.')
649 return -1;
651 p = e + 1;
652 val = strtoul(p, &e, 16);
653 if (e == p)
654 return -1;
656 func = val;
659 /* if funcp == NULL func is 0 */
660 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
661 return -1;
663 if (*e)
664 return -1;
666 *domp = dom;
667 *busp = bus;
668 *slotp = slot;
669 if (funcp != NULL)
670 *funcp = func;
671 return 0;
674 static PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root,
675 const char *devaddr)
677 int dom, bus;
678 unsigned slot;
680 if (!root) {
681 fprintf(stderr, "No primary PCI bus\n");
682 return NULL;
685 assert(!root->parent_dev);
687 if (!devaddr) {
688 *devfnp = -1;
689 return pci_find_bus_nr(root, 0);
692 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
693 return NULL;
696 if (dom != 0) {
697 fprintf(stderr, "No support for non-zero PCI domains\n");
698 return NULL;
701 *devfnp = PCI_DEVFN(slot, 0);
702 return pci_find_bus_nr(root, bus);
705 static void pci_init_cmask(PCIDevice *dev)
707 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
708 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
709 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
710 dev->cmask[PCI_REVISION_ID] = 0xff;
711 dev->cmask[PCI_CLASS_PROG] = 0xff;
712 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
713 dev->cmask[PCI_HEADER_TYPE] = 0xff;
714 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
717 static void pci_init_wmask(PCIDevice *dev)
719 int config_size = pci_config_size(dev);
721 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
722 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
723 pci_set_word(dev->wmask + PCI_COMMAND,
724 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
725 PCI_COMMAND_INTX_DISABLE);
726 if (dev->cap_present & QEMU_PCI_CAP_SERR) {
727 pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
730 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
731 config_size - PCI_CONFIG_HEADER_SIZE);
734 static void pci_init_w1cmask(PCIDevice *dev)
737 * Note: It's okay to set w1cmask even for readonly bits as
738 * long as their value is hardwired to 0.
740 pci_set_word(dev->w1cmask + PCI_STATUS,
741 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
742 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
743 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
746 static void pci_init_mask_bridge(PCIDevice *d)
748 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
749 PCI_SEC_LETENCY_TIMER */
750 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
752 /* base and limit */
753 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
754 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
755 pci_set_word(d->wmask + PCI_MEMORY_BASE,
756 PCI_MEMORY_RANGE_MASK & 0xffff);
757 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
758 PCI_MEMORY_RANGE_MASK & 0xffff);
759 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
760 PCI_PREF_RANGE_MASK & 0xffff);
761 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
762 PCI_PREF_RANGE_MASK & 0xffff);
764 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
765 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
767 /* Supported memory and i/o types */
768 d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
769 d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
770 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
771 PCI_PREF_RANGE_TYPE_64);
772 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
773 PCI_PREF_RANGE_TYPE_64);
776 * TODO: Bridges default to 10-bit VGA decoding but we currently only
777 * implement 16-bit decoding (no alias support).
779 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
780 PCI_BRIDGE_CTL_PARITY |
781 PCI_BRIDGE_CTL_SERR |
782 PCI_BRIDGE_CTL_ISA |
783 PCI_BRIDGE_CTL_VGA |
784 PCI_BRIDGE_CTL_VGA_16BIT |
785 PCI_BRIDGE_CTL_MASTER_ABORT |
786 PCI_BRIDGE_CTL_BUS_RESET |
787 PCI_BRIDGE_CTL_FAST_BACK |
788 PCI_BRIDGE_CTL_DISCARD |
789 PCI_BRIDGE_CTL_SEC_DISCARD |
790 PCI_BRIDGE_CTL_DISCARD_SERR);
791 /* Below does not do anything as we never set this bit, put here for
792 * completeness. */
793 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
794 PCI_BRIDGE_CTL_DISCARD_STATUS);
795 d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
796 d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
797 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
798 PCI_PREF_RANGE_TYPE_MASK);
799 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
800 PCI_PREF_RANGE_TYPE_MASK);
803 static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
805 uint8_t slot = PCI_SLOT(dev->devfn);
806 uint8_t func;
808 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
809 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
813 * multifunction bit is interpreted in two ways as follows.
814 * - all functions must set the bit to 1.
815 * Example: Intel X53
816 * - function 0 must set the bit, but the rest function (> 0)
817 * is allowed to leave the bit to 0.
818 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
820 * So OS (at least Linux) checks the bit of only function 0,
821 * and doesn't see the bit of function > 0.
823 * The below check allows both interpretation.
825 if (PCI_FUNC(dev->devfn)) {
826 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
827 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
828 /* function 0 should set multifunction bit */
829 error_setg(errp, "PCI: single function device can't be populated "
830 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
831 return;
833 return;
836 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
837 return;
839 /* function 0 indicates single function, so function > 0 must be NULL */
840 for (func = 1; func < PCI_FUNC_MAX; ++func) {
841 if (bus->devices[PCI_DEVFN(slot, func)]) {
842 error_setg(errp, "PCI: %x.0 indicates single function, "
843 "but %x.%x is already populated.",
844 slot, slot, func);
845 return;
850 static void pci_config_alloc(PCIDevice *pci_dev)
852 int config_size = pci_config_size(pci_dev);
854 pci_dev->config = g_malloc0(config_size);
855 pci_dev->cmask = g_malloc0(config_size);
856 pci_dev->wmask = g_malloc0(config_size);
857 pci_dev->w1cmask = g_malloc0(config_size);
858 pci_dev->used = g_malloc0(config_size);
861 static void pci_config_free(PCIDevice *pci_dev)
863 g_free(pci_dev->config);
864 g_free(pci_dev->cmask);
865 g_free(pci_dev->wmask);
866 g_free(pci_dev->w1cmask);
867 g_free(pci_dev->used);
870 static void do_pci_unregister_device(PCIDevice *pci_dev)
872 pci_dev->bus->devices[pci_dev->devfn] = NULL;
873 pci_config_free(pci_dev);
875 if (memory_region_is_mapped(&pci_dev->bus_master_enable_region)) {
876 memory_region_del_subregion(&pci_dev->bus_master_container_region,
877 &pci_dev->bus_master_enable_region);
879 address_space_destroy(&pci_dev->bus_master_as);
882 /* Extract PCIReqIDCache into BDF format */
883 static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
885 uint8_t bus_n;
886 uint16_t result;
888 switch (cache->type) {
889 case PCI_REQ_ID_BDF:
890 result = pci_get_bdf(cache->dev);
891 break;
892 case PCI_REQ_ID_SECONDARY_BUS:
893 bus_n = pci_bus_num(cache->dev->bus);
894 result = PCI_BUILD_BDF(bus_n, 0);
895 break;
896 default:
897 error_printf("Invalid PCI requester ID cache type: %d\n",
898 cache->type);
899 exit(1);
900 break;
903 return result;
906 /* Parse bridges up to the root complex and return requester ID
907 * cache for specific device. For full PCIe topology, the cache
908 * result would be exactly the same as getting BDF of the device.
909 * However, several tricks are required when system mixed up with
910 * legacy PCI devices and PCIe-to-PCI bridges.
912 * Here we cache the proxy device (and type) not requester ID since
913 * bus number might change from time to time.
915 static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
917 PCIDevice *parent;
918 PCIReqIDCache cache = {
919 .dev = dev,
920 .type = PCI_REQ_ID_BDF,
923 while (!pci_bus_is_root(dev->bus)) {
924 /* We are under PCI/PCIe bridges */
925 parent = dev->bus->parent_dev;
926 if (pci_is_express(parent)) {
927 if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
928 /* When we pass through PCIe-to-PCI/PCIX bridges, we
929 * override the requester ID using secondary bus
930 * number of parent bridge with zeroed devfn
931 * (pcie-to-pci bridge spec chap 2.3). */
932 cache.type = PCI_REQ_ID_SECONDARY_BUS;
933 cache.dev = dev;
935 } else {
936 /* Legacy PCI, override requester ID with the bridge's
937 * BDF upstream. When the root complex connects to
938 * legacy PCI devices (including buses), it can only
939 * obtain requester ID info from directly attached
940 * devices. If devices are attached under bridges, only
941 * the requester ID of the bridge that is directly
942 * attached to the root complex can be recognized. */
943 cache.type = PCI_REQ_ID_BDF;
944 cache.dev = parent;
946 dev = parent;
949 return cache;
952 uint16_t pci_requester_id(PCIDevice *dev)
954 return pci_req_id_cache_extract(&dev->requester_id_cache);
957 static bool pci_bus_devfn_available(PCIBus *bus, int devfn)
959 return !(bus->devices[devfn]);
962 static bool pci_bus_devfn_reserved(PCIBus *bus, int devfn)
964 return bus->slot_reserved_mask & (1UL << PCI_SLOT(devfn));
967 /* -1 for devfn means auto assign */
968 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
969 const char *name, int devfn,
970 Error **errp)
972 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
973 PCIConfigReadFunc *config_read = pc->config_read;
974 PCIConfigWriteFunc *config_write = pc->config_write;
975 Error *local_err = NULL;
976 DeviceState *dev = DEVICE(pci_dev);
978 pci_dev->bus = bus;
979 /* Only pci bridges can be attached to extra PCI root buses */
980 if (pci_bus_is_root(bus) && bus->parent_dev && !pc->is_bridge) {
981 error_setg(errp,
982 "PCI: Only PCI/PCIe bridges can be plugged into %s",
983 bus->parent_dev->name);
984 return NULL;
987 if (devfn < 0) {
988 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
989 devfn += PCI_FUNC_MAX) {
990 if (pci_bus_devfn_available(bus, devfn) &&
991 !pci_bus_devfn_reserved(bus, devfn)) {
992 goto found;
995 error_setg(errp, "PCI: no slot/function available for %s, all in use "
996 "or reserved", name);
997 return NULL;
998 found: ;
999 } else if (pci_bus_devfn_reserved(bus, devfn)) {
1000 error_setg(errp, "PCI: slot %d function %d not available for %s,"
1001 " reserved",
1002 PCI_SLOT(devfn), PCI_FUNC(devfn), name);
1003 return NULL;
1004 } else if (!pci_bus_devfn_available(bus, devfn)) {
1005 error_setg(errp, "PCI: slot %d function %d not available for %s,"
1006 " in use by %s",
1007 PCI_SLOT(devfn), PCI_FUNC(devfn), name,
1008 bus->devices[devfn]->name);
1009 return NULL;
1010 } else if (dev->hotplugged &&
1011 pci_get_function_0(pci_dev)) {
1012 error_setg(errp, "PCI: slot %d function 0 already ocuppied by %s,"
1013 " new func %s cannot be exposed to guest.",
1014 PCI_SLOT(pci_get_function_0(pci_dev)->devfn),
1015 pci_get_function_0(pci_dev)->name,
1016 name);
1018 return NULL;
1021 pci_dev->devfn = devfn;
1022 pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
1024 memory_region_init(&pci_dev->bus_master_container_region, OBJECT(pci_dev),
1025 "bus master container", UINT64_MAX);
1026 address_space_init(&pci_dev->bus_master_as,
1027 &pci_dev->bus_master_container_region, pci_dev->name);
1029 if (qdev_hotplug) {
1030 pci_init_bus_master(pci_dev);
1032 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
1033 pci_dev->irq_state = 0;
1034 pci_config_alloc(pci_dev);
1036 pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
1037 pci_config_set_device_id(pci_dev->config, pc->device_id);
1038 pci_config_set_revision(pci_dev->config, pc->revision);
1039 pci_config_set_class(pci_dev->config, pc->class_id);
1041 if (!pc->is_bridge) {
1042 if (pc->subsystem_vendor_id || pc->subsystem_id) {
1043 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
1044 pc->subsystem_vendor_id);
1045 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
1046 pc->subsystem_id);
1047 } else {
1048 pci_set_default_subsystem_id(pci_dev);
1050 } else {
1051 /* subsystem_vendor_id/subsystem_id are only for header type 0 */
1052 assert(!pc->subsystem_vendor_id);
1053 assert(!pc->subsystem_id);
1055 pci_init_cmask(pci_dev);
1056 pci_init_wmask(pci_dev);
1057 pci_init_w1cmask(pci_dev);
1058 if (pc->is_bridge) {
1059 pci_init_mask_bridge(pci_dev);
1061 pci_init_multifunction(bus, pci_dev, &local_err);
1062 if (local_err) {
1063 error_propagate(errp, local_err);
1064 do_pci_unregister_device(pci_dev);
1065 return NULL;
1068 if (!config_read)
1069 config_read = pci_default_read_config;
1070 if (!config_write)
1071 config_write = pci_default_write_config;
1072 pci_dev->config_read = config_read;
1073 pci_dev->config_write = config_write;
1074 bus->devices[devfn] = pci_dev;
1075 pci_dev->version_id = 2; /* Current pci device vmstate version */
1076 return pci_dev;
1079 static void pci_unregister_io_regions(PCIDevice *pci_dev)
1081 PCIIORegion *r;
1082 int i;
1084 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1085 r = &pci_dev->io_regions[i];
1086 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
1087 continue;
1088 memory_region_del_subregion(r->address_space, r->memory);
1091 pci_unregister_vga(pci_dev);
1094 static void pci_qdev_unrealize(DeviceState *dev, Error **errp)
1096 PCIDevice *pci_dev = PCI_DEVICE(dev);
1097 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1099 pci_unregister_io_regions(pci_dev);
1100 pci_del_option_rom(pci_dev);
1102 if (pc->exit) {
1103 pc->exit(pci_dev);
1106 pci_device_deassert_intx(pci_dev);
1107 do_pci_unregister_device(pci_dev);
1110 void pci_register_bar(PCIDevice *pci_dev, int region_num,
1111 uint8_t type, MemoryRegion *memory)
1113 PCIIORegion *r;
1114 uint32_t addr; /* offset in pci config space */
1115 uint64_t wmask;
1116 pcibus_t size = memory_region_size(memory);
1118 g_assert(region_num >= 0);
1119 g_assert(region_num < PCI_NUM_REGIONS);
1120 if (size & (size-1)) {
1121 fprintf(stderr, "ERROR: PCI region size must be pow2 "
1122 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
1123 exit(1);
1126 r = &pci_dev->io_regions[region_num];
1127 r->addr = PCI_BAR_UNMAPPED;
1128 r->size = size;
1129 r->type = type;
1130 r->memory = memory;
1131 r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO
1132 ? pci_dev->bus->address_space_io
1133 : pci_dev->bus->address_space_mem;
1135 wmask = ~(size - 1);
1136 if (region_num == PCI_ROM_SLOT) {
1137 /* ROM enable bit is writable */
1138 wmask |= PCI_ROM_ADDRESS_ENABLE;
1141 addr = pci_bar(pci_dev, region_num);
1142 pci_set_long(pci_dev->config + addr, type);
1144 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1145 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1146 pci_set_quad(pci_dev->wmask + addr, wmask);
1147 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1148 } else {
1149 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1150 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1154 static void pci_update_vga(PCIDevice *pci_dev)
1156 uint16_t cmd;
1158 if (!pci_dev->has_vga) {
1159 return;
1162 cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1164 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1165 cmd & PCI_COMMAND_MEMORY);
1166 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1167 cmd & PCI_COMMAND_IO);
1168 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1169 cmd & PCI_COMMAND_IO);
1172 void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1173 MemoryRegion *io_lo, MemoryRegion *io_hi)
1175 assert(!pci_dev->has_vga);
1177 assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1178 pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1179 memory_region_add_subregion_overlap(pci_dev->bus->address_space_mem,
1180 QEMU_PCI_VGA_MEM_BASE, mem, 1);
1182 assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1183 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1184 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1185 QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1187 assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1188 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1189 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1190 QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1191 pci_dev->has_vga = true;
1193 pci_update_vga(pci_dev);
1196 void pci_unregister_vga(PCIDevice *pci_dev)
1198 if (!pci_dev->has_vga) {
1199 return;
1202 memory_region_del_subregion(pci_dev->bus->address_space_mem,
1203 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1204 memory_region_del_subregion(pci_dev->bus->address_space_io,
1205 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1206 memory_region_del_subregion(pci_dev->bus->address_space_io,
1207 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1208 pci_dev->has_vga = false;
1211 pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1213 return pci_dev->io_regions[region_num].addr;
1216 static pcibus_t pci_bar_address(PCIDevice *d,
1217 int reg, uint8_t type, pcibus_t size)
1219 pcibus_t new_addr, last_addr;
1220 int bar = pci_bar(d, reg);
1221 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1222 Object *machine = qdev_get_machine();
1223 ObjectClass *oc = object_get_class(machine);
1224 MachineClass *mc = MACHINE_CLASS(oc);
1225 bool allow_0_address = mc->pci_allow_0_address;
1227 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1228 if (!(cmd & PCI_COMMAND_IO)) {
1229 return PCI_BAR_UNMAPPED;
1231 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
1232 last_addr = new_addr + size - 1;
1233 /* Check if 32 bit BAR wraps around explicitly.
1234 * TODO: make priorities correct and remove this work around.
1236 if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1237 (!allow_0_address && new_addr == 0)) {
1238 return PCI_BAR_UNMAPPED;
1240 return new_addr;
1243 if (!(cmd & PCI_COMMAND_MEMORY)) {
1244 return PCI_BAR_UNMAPPED;
1246 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1247 new_addr = pci_get_quad(d->config + bar);
1248 } else {
1249 new_addr = pci_get_long(d->config + bar);
1251 /* the ROM slot has a specific enable bit */
1252 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1253 return PCI_BAR_UNMAPPED;
1255 new_addr &= ~(size - 1);
1256 last_addr = new_addr + size - 1;
1257 /* NOTE: we do not support wrapping */
1258 /* XXX: as we cannot support really dynamic
1259 mappings, we handle specific values as invalid
1260 mappings. */
1261 if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1262 (!allow_0_address && new_addr == 0)) {
1263 return PCI_BAR_UNMAPPED;
1266 /* Now pcibus_t is 64bit.
1267 * Check if 32 bit BAR wraps around explicitly.
1268 * Without this, PC ide doesn't work well.
1269 * TODO: remove this work around.
1271 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1272 return PCI_BAR_UNMAPPED;
1276 * OS is allowed to set BAR beyond its addressable
1277 * bits. For example, 32 bit OS can set 64bit bar
1278 * to >4G. Check it. TODO: we might need to support
1279 * it in the future for e.g. PAE.
1281 if (last_addr >= HWADDR_MAX) {
1282 return PCI_BAR_UNMAPPED;
1285 return new_addr;
1288 static void pci_update_mappings(PCIDevice *d)
1290 PCIIORegion *r;
1291 int i;
1292 pcibus_t new_addr;
1294 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1295 r = &d->io_regions[i];
1297 /* this region isn't registered */
1298 if (!r->size)
1299 continue;
1301 new_addr = pci_bar_address(d, i, r->type, r->size);
1303 /* This bar isn't changed */
1304 if (new_addr == r->addr)
1305 continue;
1307 /* now do the real mapping */
1308 if (r->addr != PCI_BAR_UNMAPPED) {
1309 trace_pci_update_mappings_del(d, pci_bus_num(d->bus),
1310 PCI_SLOT(d->devfn),
1311 PCI_FUNC(d->devfn),
1312 i, r->addr, r->size);
1313 memory_region_del_subregion(r->address_space, r->memory);
1315 r->addr = new_addr;
1316 if (r->addr != PCI_BAR_UNMAPPED) {
1317 trace_pci_update_mappings_add(d, pci_bus_num(d->bus),
1318 PCI_SLOT(d->devfn),
1319 PCI_FUNC(d->devfn),
1320 i, r->addr, r->size);
1321 memory_region_add_subregion_overlap(r->address_space,
1322 r->addr, r->memory, 1);
1326 pci_update_vga(d);
1329 static inline int pci_irq_disabled(PCIDevice *d)
1331 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1334 /* Called after interrupt disabled field update in config space,
1335 * assert/deassert interrupts if necessary.
1336 * Gets original interrupt disable bit value (before update). */
1337 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1339 int i, disabled = pci_irq_disabled(d);
1340 if (disabled == was_irq_disabled)
1341 return;
1342 for (i = 0; i < PCI_NUM_PINS; ++i) {
1343 int state = pci_irq_state(d, i);
1344 pci_change_irq_level(d, i, disabled ? -state : state);
1348 uint32_t pci_default_read_config(PCIDevice *d,
1349 uint32_t address, int len)
1351 uint32_t val = 0;
1353 memcpy(&val, d->config + address, len);
1354 return le32_to_cpu(val);
1357 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1359 int i, was_irq_disabled = pci_irq_disabled(d);
1360 uint32_t val = val_in;
1362 for (i = 0; i < l; val >>= 8, ++i) {
1363 uint8_t wmask = d->wmask[addr + i];
1364 uint8_t w1cmask = d->w1cmask[addr + i];
1365 assert(!(wmask & w1cmask));
1366 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1367 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1369 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1370 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1371 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1372 range_covers_byte(addr, l, PCI_COMMAND))
1373 pci_update_mappings(d);
1375 if (range_covers_byte(addr, l, PCI_COMMAND)) {
1376 pci_update_irq_disabled(d, was_irq_disabled);
1377 memory_region_set_enabled(&d->bus_master_enable_region,
1378 pci_get_word(d->config + PCI_COMMAND)
1379 & PCI_COMMAND_MASTER);
1382 msi_write_config(d, addr, val_in, l);
1383 msix_write_config(d, addr, val_in, l);
1386 /***********************************************************/
1387 /* generic PCI irq support */
1389 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1390 static void pci_irq_handler(void *opaque, int irq_num, int level)
1392 PCIDevice *pci_dev = opaque;
1393 int change;
1395 change = level - pci_irq_state(pci_dev, irq_num);
1396 if (!change)
1397 return;
1399 pci_set_irq_state(pci_dev, irq_num, level);
1400 pci_update_irq_status(pci_dev);
1401 if (pci_irq_disabled(pci_dev))
1402 return;
1403 pci_change_irq_level(pci_dev, irq_num, change);
1406 static inline int pci_intx(PCIDevice *pci_dev)
1408 return pci_get_byte(pci_dev->config + PCI_INTERRUPT_PIN) - 1;
1411 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1413 int intx = pci_intx(pci_dev);
1415 return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1418 void pci_set_irq(PCIDevice *pci_dev, int level)
1420 int intx = pci_intx(pci_dev);
1421 pci_irq_handler(pci_dev, intx, level);
1424 /* Special hooks used by device assignment */
1425 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1427 assert(pci_bus_is_root(bus));
1428 bus->route_intx_to_irq = route_intx_to_irq;
1431 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1433 PCIBus *bus;
1435 do {
1436 bus = dev->bus;
1437 pin = bus->map_irq(dev, pin);
1438 dev = bus->parent_dev;
1439 } while (dev);
1441 if (!bus->route_intx_to_irq) {
1442 error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1443 object_get_typename(OBJECT(bus->qbus.parent)));
1444 return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1447 return bus->route_intx_to_irq(bus->irq_opaque, pin);
1450 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1452 return old->mode != new->mode || old->irq != new->irq;
1455 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1457 PCIDevice *dev;
1458 PCIBus *sec;
1459 int i;
1461 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1462 dev = bus->devices[i];
1463 if (dev && dev->intx_routing_notifier) {
1464 dev->intx_routing_notifier(dev);
1468 QLIST_FOREACH(sec, &bus->child, sibling) {
1469 pci_bus_fire_intx_routing_notifier(sec);
1473 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1474 PCIINTxRoutingNotifier notifier)
1476 dev->intx_routing_notifier = notifier;
1480 * PCI-to-PCI bridge specification
1481 * 9.1: Interrupt routing. Table 9-1
1483 * the PCI Express Base Specification, Revision 2.1
1484 * 2.2.8.1: INTx interrutp signaling - Rules
1485 * the Implementation Note
1486 * Table 2-20
1489 * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1490 * 0-origin unlike PCI interrupt pin register.
1492 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1494 return (pin + PCI_SLOT(pci_dev->devfn)) % PCI_NUM_PINS;
1497 /***********************************************************/
1498 /* monitor info on PCI */
1500 typedef struct {
1501 uint16_t class;
1502 const char *desc;
1503 const char *fw_name;
1504 uint16_t fw_ign_bits;
1505 } pci_class_desc;
1507 static const pci_class_desc pci_class_descriptions[] =
1509 { 0x0001, "VGA controller", "display"},
1510 { 0x0100, "SCSI controller", "scsi"},
1511 { 0x0101, "IDE controller", "ide"},
1512 { 0x0102, "Floppy controller", "fdc"},
1513 { 0x0103, "IPI controller", "ipi"},
1514 { 0x0104, "RAID controller", "raid"},
1515 { 0x0106, "SATA controller"},
1516 { 0x0107, "SAS controller"},
1517 { 0x0180, "Storage controller"},
1518 { 0x0200, "Ethernet controller", "ethernet"},
1519 { 0x0201, "Token Ring controller", "token-ring"},
1520 { 0x0202, "FDDI controller", "fddi"},
1521 { 0x0203, "ATM controller", "atm"},
1522 { 0x0280, "Network controller"},
1523 { 0x0300, "VGA controller", "display", 0x00ff},
1524 { 0x0301, "XGA controller"},
1525 { 0x0302, "3D controller"},
1526 { 0x0380, "Display controller"},
1527 { 0x0400, "Video controller", "video"},
1528 { 0x0401, "Audio controller", "sound"},
1529 { 0x0402, "Phone"},
1530 { 0x0403, "Audio controller", "sound"},
1531 { 0x0480, "Multimedia controller"},
1532 { 0x0500, "RAM controller", "memory"},
1533 { 0x0501, "Flash controller", "flash"},
1534 { 0x0580, "Memory controller"},
1535 { 0x0600, "Host bridge", "host"},
1536 { 0x0601, "ISA bridge", "isa"},
1537 { 0x0602, "EISA bridge", "eisa"},
1538 { 0x0603, "MC bridge", "mca"},
1539 { 0x0604, "PCI bridge", "pci-bridge"},
1540 { 0x0605, "PCMCIA bridge", "pcmcia"},
1541 { 0x0606, "NUBUS bridge", "nubus"},
1542 { 0x0607, "CARDBUS bridge", "cardbus"},
1543 { 0x0608, "RACEWAY bridge"},
1544 { 0x0680, "Bridge"},
1545 { 0x0700, "Serial port", "serial"},
1546 { 0x0701, "Parallel port", "parallel"},
1547 { 0x0800, "Interrupt controller", "interrupt-controller"},
1548 { 0x0801, "DMA controller", "dma-controller"},
1549 { 0x0802, "Timer", "timer"},
1550 { 0x0803, "RTC", "rtc"},
1551 { 0x0900, "Keyboard", "keyboard"},
1552 { 0x0901, "Pen", "pen"},
1553 { 0x0902, "Mouse", "mouse"},
1554 { 0x0A00, "Dock station", "dock", 0x00ff},
1555 { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1556 { 0x0c00, "Fireware contorller", "fireware"},
1557 { 0x0c01, "Access bus controller", "access-bus"},
1558 { 0x0c02, "SSA controller", "ssa"},
1559 { 0x0c03, "USB controller", "usb"},
1560 { 0x0c04, "Fibre channel controller", "fibre-channel"},
1561 { 0x0c05, "SMBus"},
1562 { 0, NULL}
1565 static void pci_for_each_device_under_bus_reverse(PCIBus *bus,
1566 void (*fn)(PCIBus *b,
1567 PCIDevice *d,
1568 void *opaque),
1569 void *opaque)
1571 PCIDevice *d;
1572 int devfn;
1574 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1575 d = bus->devices[ARRAY_SIZE(bus->devices) - 1 - devfn];
1576 if (d) {
1577 fn(bus, d, opaque);
1582 void pci_for_each_device_reverse(PCIBus *bus, int bus_num,
1583 void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
1584 void *opaque)
1586 bus = pci_find_bus_nr(bus, bus_num);
1588 if (bus) {
1589 pci_for_each_device_under_bus_reverse(bus, fn, opaque);
1593 static void pci_for_each_device_under_bus(PCIBus *bus,
1594 void (*fn)(PCIBus *b, PCIDevice *d,
1595 void *opaque),
1596 void *opaque)
1598 PCIDevice *d;
1599 int devfn;
1601 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1602 d = bus->devices[devfn];
1603 if (d) {
1604 fn(bus, d, opaque);
1609 void pci_for_each_device(PCIBus *bus, int bus_num,
1610 void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
1611 void *opaque)
1613 bus = pci_find_bus_nr(bus, bus_num);
1615 if (bus) {
1616 pci_for_each_device_under_bus(bus, fn, opaque);
1620 static const pci_class_desc *get_class_desc(int class)
1622 const pci_class_desc *desc;
1624 desc = pci_class_descriptions;
1625 while (desc->desc && class != desc->class) {
1626 desc++;
1629 return desc;
1632 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num);
1634 static PciMemoryRegionList *qmp_query_pci_regions(const PCIDevice *dev)
1636 PciMemoryRegionList *head = NULL, *cur_item = NULL;
1637 int i;
1639 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1640 const PCIIORegion *r = &dev->io_regions[i];
1641 PciMemoryRegionList *region;
1643 if (!r->size) {
1644 continue;
1647 region = g_malloc0(sizeof(*region));
1648 region->value = g_malloc0(sizeof(*region->value));
1650 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1651 region->value->type = g_strdup("io");
1652 } else {
1653 region->value->type = g_strdup("memory");
1654 region->value->has_prefetch = true;
1655 region->value->prefetch = !!(r->type & PCI_BASE_ADDRESS_MEM_PREFETCH);
1656 region->value->has_mem_type_64 = true;
1657 region->value->mem_type_64 = !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
1660 region->value->bar = i;
1661 region->value->address = r->addr;
1662 region->value->size = r->size;
1664 /* XXX: waiting for the qapi to support GSList */
1665 if (!cur_item) {
1666 head = cur_item = region;
1667 } else {
1668 cur_item->next = region;
1669 cur_item = region;
1673 return head;
1676 static PciBridgeInfo *qmp_query_pci_bridge(PCIDevice *dev, PCIBus *bus,
1677 int bus_num)
1679 PciBridgeInfo *info;
1680 PciMemoryRange *range;
1682 info = g_new0(PciBridgeInfo, 1);
1684 info->bus = g_new0(PciBusInfo, 1);
1685 info->bus->number = dev->config[PCI_PRIMARY_BUS];
1686 info->bus->secondary = dev->config[PCI_SECONDARY_BUS];
1687 info->bus->subordinate = dev->config[PCI_SUBORDINATE_BUS];
1689 range = info->bus->io_range = g_new0(PciMemoryRange, 1);
1690 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
1691 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
1693 range = info->bus->memory_range = g_new0(PciMemoryRange, 1);
1694 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1695 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1697 range = info->bus->prefetchable_range = g_new0(PciMemoryRange, 1);
1698 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1699 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1701 if (dev->config[PCI_SECONDARY_BUS] != 0) {
1702 PCIBus *child_bus = pci_find_bus_nr(bus, dev->config[PCI_SECONDARY_BUS]);
1703 if (child_bus) {
1704 info->has_devices = true;
1705 info->devices = qmp_query_pci_devices(child_bus, dev->config[PCI_SECONDARY_BUS]);
1709 return info;
1712 static PciDeviceInfo *qmp_query_pci_device(PCIDevice *dev, PCIBus *bus,
1713 int bus_num)
1715 const pci_class_desc *desc;
1716 PciDeviceInfo *info;
1717 uint8_t type;
1718 int class;
1720 info = g_new0(PciDeviceInfo, 1);
1721 info->bus = bus_num;
1722 info->slot = PCI_SLOT(dev->devfn);
1723 info->function = PCI_FUNC(dev->devfn);
1725 info->class_info = g_new0(PciDeviceClass, 1);
1726 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1727 info->class_info->q_class = class;
1728 desc = get_class_desc(class);
1729 if (desc->desc) {
1730 info->class_info->has_desc = true;
1731 info->class_info->desc = g_strdup(desc->desc);
1734 info->id = g_new0(PciDeviceId, 1);
1735 info->id->vendor = pci_get_word(dev->config + PCI_VENDOR_ID);
1736 info->id->device = pci_get_word(dev->config + PCI_DEVICE_ID);
1737 info->regions = qmp_query_pci_regions(dev);
1738 info->qdev_id = g_strdup(dev->qdev.id ? dev->qdev.id : "");
1740 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1741 info->has_irq = true;
1742 info->irq = dev->config[PCI_INTERRUPT_LINE];
1745 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1746 if (type == PCI_HEADER_TYPE_BRIDGE) {
1747 info->has_pci_bridge = true;
1748 info->pci_bridge = qmp_query_pci_bridge(dev, bus, bus_num);
1751 return info;
1754 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num)
1756 PciDeviceInfoList *info, *head = NULL, *cur_item = NULL;
1757 PCIDevice *dev;
1758 int devfn;
1760 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1761 dev = bus->devices[devfn];
1762 if (dev) {
1763 info = g_malloc0(sizeof(*info));
1764 info->value = qmp_query_pci_device(dev, bus, bus_num);
1766 /* XXX: waiting for the qapi to support GSList */
1767 if (!cur_item) {
1768 head = cur_item = info;
1769 } else {
1770 cur_item->next = info;
1771 cur_item = info;
1776 return head;
1779 static PciInfo *qmp_query_pci_bus(PCIBus *bus, int bus_num)
1781 PciInfo *info = NULL;
1783 bus = pci_find_bus_nr(bus, bus_num);
1784 if (bus) {
1785 info = g_malloc0(sizeof(*info));
1786 info->bus = bus_num;
1787 info->devices = qmp_query_pci_devices(bus, bus_num);
1790 return info;
1793 PciInfoList *qmp_query_pci(Error **errp)
1795 PciInfoList *info, *head = NULL, *cur_item = NULL;
1796 PCIHostState *host_bridge;
1798 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
1799 info = g_malloc0(sizeof(*info));
1800 info->value = qmp_query_pci_bus(host_bridge->bus,
1801 pci_bus_num(host_bridge->bus));
1803 /* XXX: waiting for the qapi to support GSList */
1804 if (!cur_item) {
1805 head = cur_item = info;
1806 } else {
1807 cur_item->next = info;
1808 cur_item = info;
1812 return head;
1815 static const char * const pci_nic_models[] = {
1816 #if !defined(CONFIG_WIN32)
1817 "atheros_wlan",
1818 #endif
1819 "dp83816",
1820 "e100",
1821 "ne2k_pci",
1822 "i82551",
1823 "i82557a",
1824 "i82557b",
1825 "i82557c",
1826 "i82558b",
1827 "i82559c",
1828 "i82559er",
1829 "i82801",
1830 "rtl8139",
1831 "e1000",
1832 "pcnet",
1833 "tnetw1130",
1834 "virtio",
1835 "sungem",
1836 NULL
1839 static const char * const pci_nic_names[] = {
1840 #if !defined(CONFIG_WIN32)
1841 "atheros_wlan",
1842 #endif
1843 "dp83816",
1844 "e100",
1845 "ne2k_pci",
1846 "i82551",
1847 "i82557a",
1848 "i82557b",
1849 "i82557c",
1850 "i82558b",
1851 "i82559c",
1852 "i82559er",
1853 "i82801",
1854 "rtl8139",
1855 "e1000",
1856 "pcnet",
1857 "tnetw1130",
1858 "virtio-net-pci",
1859 "sungem",
1860 NULL
1863 /* Initialize a PCI NIC. */
1864 PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1865 const char *default_model,
1866 const char *default_devaddr)
1868 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1869 PCIBus *bus;
1870 PCIDevice *pci_dev;
1871 DeviceState *dev;
1872 int devfn;
1873 int i;
1875 if (qemu_show_nic_models(nd->model, pci_nic_models)) {
1876 exit(0);
1879 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1880 if (i < 0) {
1881 exit(1);
1884 bus = pci_get_bus_devfn(&devfn, rootbus, devaddr);
1885 if (!bus) {
1886 error_report("Invalid PCI device address %s for device %s",
1887 devaddr, pci_nic_names[i]);
1888 exit(1);
1891 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1892 dev = &pci_dev->qdev;
1893 qdev_set_nic_properties(dev, nd);
1894 qdev_init_nofail(dev);
1896 return pci_dev;
1899 PCIDevice *pci_vga_init(PCIBus *bus)
1901 switch (vga_interface_type) {
1902 case VGA_CIRRUS:
1903 return pci_create_simple(bus, -1, "cirrus-vga");
1904 case VGA_QXL:
1905 return pci_create_simple(bus, -1, "qxl-vga");
1906 case VGA_STD:
1907 return pci_create_simple(bus, -1, "VGA");
1908 case VGA_VMWARE:
1909 return pci_create_simple(bus, -1, "vmware-svga");
1910 case VGA_VIRTIO:
1911 return pci_create_simple(bus, -1, "virtio-vga");
1912 case VGA_NONE:
1913 default: /* Other non-PCI types. Checking for unsupported types is already
1914 done in vl.c. */
1915 return NULL;
1919 /* Whether a given bus number is in range of the secondary
1920 * bus of the given bridge device. */
1921 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1923 return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1924 PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1925 dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1926 bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1929 /* Whether a given bus number is in a range of a root bus */
1930 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1932 int i;
1934 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1935 PCIDevice *dev = bus->devices[i];
1937 if (dev && PCI_DEVICE_GET_CLASS(dev)->is_bridge) {
1938 if (pci_secondary_bus_in_range(dev, bus_num)) {
1939 return true;
1944 return false;
1947 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1949 PCIBus *sec;
1951 if (!bus) {
1952 return NULL;
1955 if (pci_bus_num(bus) == bus_num) {
1956 return bus;
1959 /* Consider all bus numbers in range for the host pci bridge. */
1960 if (!pci_bus_is_root(bus) &&
1961 !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1962 return NULL;
1965 /* try child bus */
1966 for (; bus; bus = sec) {
1967 QLIST_FOREACH(sec, &bus->child, sibling) {
1968 if (pci_bus_num(sec) == bus_num) {
1969 return sec;
1971 /* PXB buses assumed to be children of bus 0 */
1972 if (pci_bus_is_root(sec)) {
1973 if (pci_root_bus_in_range(sec, bus_num)) {
1974 break;
1976 } else {
1977 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1978 break;
1984 return NULL;
1987 void pci_for_each_bus_depth_first(PCIBus *bus,
1988 void *(*begin)(PCIBus *bus, void *parent_state),
1989 void (*end)(PCIBus *bus, void *state),
1990 void *parent_state)
1992 PCIBus *sec;
1993 void *state;
1995 if (!bus) {
1996 return;
1999 if (begin) {
2000 state = begin(bus, parent_state);
2001 } else {
2002 state = parent_state;
2005 QLIST_FOREACH(sec, &bus->child, sibling) {
2006 pci_for_each_bus_depth_first(sec, begin, end, state);
2009 if (end) {
2010 end(bus, state);
2015 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
2017 bus = pci_find_bus_nr(bus, bus_num);
2019 if (!bus)
2020 return NULL;
2022 return bus->devices[devfn];
2025 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
2027 PCIDevice *pci_dev = (PCIDevice *)qdev;
2028 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
2029 Error *local_err = NULL;
2030 PCIBus *bus;
2031 bool is_default_rom;
2033 /* initialize cap_present for pci_is_express() and pci_config_size() */
2034 if (pc->is_express) {
2035 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2038 bus = PCI_BUS(qdev_get_parent_bus(qdev));
2039 pci_dev = do_pci_register_device(pci_dev, bus,
2040 object_get_typename(OBJECT(qdev)),
2041 pci_dev->devfn, errp);
2042 if (pci_dev == NULL)
2043 return;
2045 if (pc->realize) {
2046 pc->realize(pci_dev, &local_err);
2047 if (local_err) {
2048 error_propagate(errp, local_err);
2049 do_pci_unregister_device(pci_dev);
2050 return;
2054 /* rom loading */
2055 is_default_rom = false;
2056 if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2057 pci_dev->romfile = g_strdup(pc->romfile);
2058 is_default_rom = true;
2061 pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2062 if (local_err) {
2063 error_propagate(errp, local_err);
2064 pci_qdev_unrealize(DEVICE(pci_dev), NULL);
2065 return;
2069 static void pci_default_realize(PCIDevice *dev, Error **errp)
2071 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2073 if (pc->init) {
2074 if (pc->init(dev) < 0) {
2075 error_setg(errp, "Device initialization failed");
2076 return;
2081 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
2082 const char *name)
2084 DeviceState *dev;
2086 dev = qdev_create(&bus->qbus, name);
2087 qdev_prop_set_int32(dev, "addr", devfn);
2088 qdev_prop_set_bit(dev, "multifunction", multifunction);
2089 return PCI_DEVICE(dev);
2092 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2093 bool multifunction,
2094 const char *name)
2096 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
2097 qdev_init_nofail(&dev->qdev);
2098 return dev;
2101 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
2103 return pci_create_multifunction(bus, devfn, false, name);
2106 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2108 return pci_create_simple_multifunction(bus, devfn, false, name);
2111 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2113 int offset = PCI_CONFIG_HEADER_SIZE;
2114 int i;
2115 for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2116 if (pdev->used[i])
2117 offset = i + 1;
2118 else if (i - offset + 1 == size)
2119 return offset;
2121 return 0;
2124 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2125 uint8_t *prev_p)
2127 uint8_t next, prev;
2129 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2130 return 0;
2132 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2133 prev = next + PCI_CAP_LIST_NEXT)
2134 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2135 break;
2137 if (prev_p)
2138 *prev_p = prev;
2139 return next;
2142 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2144 uint8_t next, prev, found = 0;
2146 if (!(pdev->used[offset])) {
2147 return 0;
2150 assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2152 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2153 prev = next + PCI_CAP_LIST_NEXT) {
2154 if (next <= offset && next > found) {
2155 found = next;
2158 return found;
2161 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2162 This is needed for an option rom which is used for more than one device. */
2163 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
2165 uint16_t vendor_id;
2166 uint16_t device_id;
2167 uint16_t rom_vendor_id;
2168 uint16_t rom_device_id;
2169 uint16_t rom_magic;
2170 uint16_t pcir_offset;
2171 uint8_t checksum;
2173 /* Words in rom data are little endian (like in PCI configuration),
2174 so they can be read / written with pci_get_word / pci_set_word. */
2176 /* Only a valid rom will be patched. */
2177 rom_magic = pci_get_word(ptr);
2178 if (rom_magic != 0xaa55) {
2179 PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2180 return;
2182 pcir_offset = pci_get_word(ptr + 0x18);
2183 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2184 PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2185 return;
2188 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2189 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2190 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2191 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2193 PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2194 vendor_id, device_id, rom_vendor_id, rom_device_id);
2196 checksum = ptr[6];
2198 if (vendor_id != rom_vendor_id) {
2199 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2200 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2201 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2202 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2203 ptr[6] = checksum;
2204 pci_set_word(ptr + pcir_offset + 4, vendor_id);
2207 if (device_id != rom_device_id) {
2208 /* Patch device id and checksum (at offset 6 for etherboot roms). */
2209 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2210 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2211 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2212 ptr[6] = checksum;
2213 pci_set_word(ptr + pcir_offset + 6, device_id);
2217 /* Add an option rom for the device */
2218 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2219 Error **errp)
2221 int size;
2222 char *path;
2223 void *ptr;
2224 char name[32];
2225 const VMStateDescription *vmsd;
2227 if (!pdev->romfile)
2228 return;
2229 if (strlen(pdev->romfile) == 0)
2230 return;
2232 if (!pdev->rom_bar) {
2234 * Load rom via fw_cfg instead of creating a rom bar,
2235 * for 0.11 compatibility.
2237 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2240 * Hot-plugged devices can't use the option ROM
2241 * if the rom bar is disabled.
2243 if (DEVICE(pdev)->hotplugged) {
2244 error_setg(errp, "Hot-plugged device without ROM bar"
2245 " can't have an option ROM");
2246 return;
2249 if (class == 0x0300) {
2250 rom_add_vga(pdev->romfile);
2251 } else {
2252 rom_add_option(pdev->romfile, -1);
2254 return;
2257 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2258 if (path == NULL) {
2259 path = g_strdup(pdev->romfile);
2262 size = get_image_size(path);
2263 if (size < 0) {
2264 error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2265 g_free(path);
2266 return;
2267 } else if (size == 0) {
2268 error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2269 g_free(path);
2270 return;
2272 size = pow2ceil(size);
2274 vmsd = qdev_get_vmsd(DEVICE(pdev));
2276 if (vmsd) {
2277 snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2278 } else {
2279 snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2281 pdev->has_rom = true;
2282 memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, size, &error_fatal);
2283 ptr = memory_region_get_ram_ptr(&pdev->rom);
2284 load_image(path, ptr);
2285 g_free(path);
2287 if (is_default_rom) {
2288 /* Only the default rom images will be patched (if needed). */
2289 pci_patch_ids(pdev, ptr, size);
2292 pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2295 static void pci_del_option_rom(PCIDevice *pdev)
2297 if (!pdev->has_rom)
2298 return;
2300 vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2301 pdev->has_rom = false;
2305 * On success, pci_add_capability() returns a positive value
2306 * that the offset of the pci capability.
2307 * On failure, it sets an error and returns a negative error
2308 * code.
2310 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2311 uint8_t offset, uint8_t size,
2312 Error **errp)
2314 uint8_t *config;
2315 int i, overlapping_cap;
2317 if (!offset) {
2318 offset = pci_find_space(pdev, size);
2319 /* out of PCI config space is programming error */
2320 assert(offset);
2321 } else {
2322 /* Verify that capabilities don't overlap. Note: device assignment
2323 * depends on this check to verify that the device is not broken.
2324 * Should never trigger for emulated devices, but it's helpful
2325 * for debugging these. */
2326 for (i = offset; i < offset + size; i++) {
2327 overlapping_cap = pci_find_capability_at_offset(pdev, i);
2328 if (overlapping_cap) {
2329 error_setg(errp, "%s:%02x:%02x.%x "
2330 "Attempt to add PCI capability %x at offset "
2331 "%x overlaps existing capability %x at offset %x",
2332 pci_root_bus_path(pdev), pci_bus_num(pdev->bus),
2333 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2334 cap_id, offset, overlapping_cap, i);
2335 return -EINVAL;
2340 config = pdev->config + offset;
2341 config[PCI_CAP_LIST_ID] = cap_id;
2342 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2343 pdev->config[PCI_CAPABILITY_LIST] = offset;
2344 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2345 memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2346 /* Make capability read-only by default */
2347 memset(pdev->wmask + offset, 0, size);
2348 /* Check capability by default */
2349 memset(pdev->cmask + offset, 0xFF, size);
2350 return offset;
2353 /* Unlink capability from the pci config space. */
2354 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2356 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2357 if (!offset)
2358 return;
2359 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2360 /* Make capability writable again */
2361 memset(pdev->wmask + offset, 0xff, size);
2362 memset(pdev->w1cmask + offset, 0, size);
2363 /* Clear cmask as device-specific registers can't be checked */
2364 memset(pdev->cmask + offset, 0, size);
2365 memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2367 if (!pdev->config[PCI_CAPABILITY_LIST])
2368 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2371 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2373 return pci_find_capability_list(pdev, cap_id, NULL);
2376 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2378 PCIDevice *d = (PCIDevice *)dev;
2379 const pci_class_desc *desc;
2380 char ctxt[64];
2381 PCIIORegion *r;
2382 int i, class;
2384 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2385 desc = pci_class_descriptions;
2386 while (desc->desc && class != desc->class)
2387 desc++;
2388 if (desc->desc) {
2389 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2390 } else {
2391 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2394 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2395 "pci id %04x:%04x (sub %04x:%04x)\n",
2396 indent, "", ctxt, pci_bus_num(d->bus),
2397 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2398 pci_get_word(d->config + PCI_VENDOR_ID),
2399 pci_get_word(d->config + PCI_DEVICE_ID),
2400 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2401 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2402 for (i = 0; i < PCI_NUM_REGIONS; i++) {
2403 r = &d->io_regions[i];
2404 if (!r->size)
2405 continue;
2406 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2407 " [0x%"FMT_PCIBUS"]\n",
2408 indent, "",
2409 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2410 r->addr, r->addr + r->size - 1);
2414 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2416 PCIDevice *d = (PCIDevice *)dev;
2417 const char *name = NULL;
2418 const pci_class_desc *desc = pci_class_descriptions;
2419 int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2421 while (desc->desc &&
2422 (class & ~desc->fw_ign_bits) !=
2423 (desc->class & ~desc->fw_ign_bits)) {
2424 desc++;
2427 if (desc->desc) {
2428 name = desc->fw_name;
2431 if (name) {
2432 pstrcpy(buf, len, name);
2433 } else {
2434 snprintf(buf, len, "pci%04x,%04x",
2435 pci_get_word(d->config + PCI_VENDOR_ID),
2436 pci_get_word(d->config + PCI_DEVICE_ID));
2439 return buf;
2442 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2444 PCIDevice *d = (PCIDevice *)dev;
2445 char path[50], name[33];
2446 int off;
2448 off = snprintf(path, sizeof(path), "%s@%x",
2449 pci_dev_fw_name(dev, name, sizeof name),
2450 PCI_SLOT(d->devfn));
2451 if (PCI_FUNC(d->devfn))
2452 snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2453 return g_strdup(path);
2456 static char *pcibus_get_dev_path(DeviceState *dev)
2458 PCIDevice *d = container_of(dev, PCIDevice, qdev);
2459 PCIDevice *t;
2460 int slot_depth;
2461 /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2462 * 00 is added here to make this format compatible with
2463 * domain:Bus:Slot.Func for systems without nested PCI bridges.
2464 * Slot.Function list specifies the slot and function numbers for all
2465 * devices on the path from root to the specific device. */
2466 const char *root_bus_path;
2467 int root_bus_len;
2468 char slot[] = ":SS.F";
2469 int slot_len = sizeof slot - 1 /* For '\0' */;
2470 int path_len;
2471 char *path, *p;
2472 int s;
2474 root_bus_path = pci_root_bus_path(d);
2475 root_bus_len = strlen(root_bus_path);
2477 /* Calculate # of slots on path between device and root. */;
2478 slot_depth = 0;
2479 for (t = d; t; t = t->bus->parent_dev) {
2480 ++slot_depth;
2483 path_len = root_bus_len + slot_len * slot_depth;
2485 /* Allocate memory, fill in the terminating null byte. */
2486 path = g_malloc(path_len + 1 /* For '\0' */);
2487 path[path_len] = '\0';
2489 memcpy(path, root_bus_path, root_bus_len);
2491 /* Fill in slot numbers. We walk up from device to root, so need to print
2492 * them in the reverse order, last to first. */
2493 p = path + path_len;
2494 for (t = d; t; t = t->bus->parent_dev) {
2495 p -= slot_len;
2496 s = snprintf(slot, sizeof slot, ":%02x.%x",
2497 PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2498 assert(s == slot_len);
2499 memcpy(p, slot, slot_len);
2502 return path;
2505 static int pci_qdev_find_recursive(PCIBus *bus,
2506 const char *id, PCIDevice **pdev)
2508 DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2509 if (!qdev) {
2510 return -ENODEV;
2513 /* roughly check if given qdev is pci device */
2514 if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2515 *pdev = PCI_DEVICE(qdev);
2516 return 0;
2518 return -EINVAL;
2521 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2523 PCIHostState *host_bridge;
2524 int rc = -ENODEV;
2526 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2527 int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2528 if (!tmp) {
2529 rc = 0;
2530 break;
2532 if (tmp != -ENODEV) {
2533 rc = tmp;
2537 return rc;
2540 MemoryRegion *pci_address_space(PCIDevice *dev)
2542 return dev->bus->address_space_mem;
2545 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2547 return dev->bus->address_space_io;
2550 static void pci_device_class_init(ObjectClass *klass, void *data)
2552 DeviceClass *k = DEVICE_CLASS(klass);
2553 PCIDeviceClass *pc = PCI_DEVICE_CLASS(klass);
2555 k->realize = pci_qdev_realize;
2556 k->unrealize = pci_qdev_unrealize;
2557 k->bus_type = TYPE_PCI_BUS;
2558 k->props = pci_props;
2559 pc->realize = pci_default_realize;
2562 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2564 PCIBus *bus = PCI_BUS(dev->bus);
2565 PCIBus *iommu_bus = bus;
2567 while(iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2568 iommu_bus = PCI_BUS(iommu_bus->parent_dev->bus);
2570 if (iommu_bus && iommu_bus->iommu_fn) {
2571 return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, dev->devfn);
2573 return &address_space_memory;
2576 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2578 bus->iommu_fn = fn;
2579 bus->iommu_opaque = opaque;
2582 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2584 Range *range = opaque;
2585 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2586 uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2587 int i;
2589 if (!(cmd & PCI_COMMAND_MEMORY)) {
2590 return;
2593 if (pc->is_bridge) {
2594 pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2595 pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2597 base = MAX(base, 0x1ULL << 32);
2599 if (limit >= base) {
2600 Range pref_range;
2601 range_set_bounds(&pref_range, base, limit);
2602 range_extend(range, &pref_range);
2605 for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2606 PCIIORegion *r = &dev->io_regions[i];
2607 pcibus_t lob, upb;
2608 Range region_range;
2610 if (!r->size ||
2611 (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2612 !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2613 continue;
2616 lob = pci_bar_address(dev, i, r->type, r->size);
2617 upb = lob + r->size - 1;
2618 if (lob == PCI_BAR_UNMAPPED) {
2619 continue;
2622 lob = MAX(lob, 0x1ULL << 32);
2624 if (upb >= lob) {
2625 range_set_bounds(&region_range, lob, upb);
2626 range_extend(range, &region_range);
2631 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2633 range_make_empty(range);
2634 pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2637 static bool pcie_has_upstream_port(PCIDevice *dev)
2639 PCIDevice *parent_dev = pci_bridge_get_device(dev->bus);
2641 /* Device associated with an upstream port.
2642 * As there are several types of these, it's easier to check the
2643 * parent device: upstream ports are always connected to
2644 * root or downstream ports.
2646 return parent_dev &&
2647 pci_is_express(parent_dev) &&
2648 parent_dev->exp.exp_cap &&
2649 (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2650 pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2653 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2655 if(pcie_has_upstream_port(pci_dev)) {
2656 /* With an upstream PCIe port, we only support 1 device at slot 0 */
2657 return pci_dev->bus->devices[0];
2658 } else {
2659 /* Other bus types might support multiple devices at slots 0-31 */
2660 return pci_dev->bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2664 MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2666 MSIMessage msg;
2667 if (msix_enabled(dev)) {
2668 msg = msix_get_message(dev, vector);
2669 } else if (msi_enabled(dev)) {
2670 msg = msi_get_message(dev, vector);
2671 } else {
2672 /* Should never happen */
2673 error_report("%s: unknown interrupt type", __func__);
2674 abort();
2676 return msg;
2679 static const TypeInfo pci_device_type_info = {
2680 .name = TYPE_PCI_DEVICE,
2681 .parent = TYPE_DEVICE,
2682 .instance_size = sizeof(PCIDevice),
2683 .abstract = true,
2684 .class_size = sizeof(PCIDeviceClass),
2685 .class_init = pci_device_class_init,
2688 static void pci_register_types(void)
2690 type_register_static(&pci_bus_info);
2691 type_register_static(&pcie_bus_info);
2692 type_register_static(&pci_device_type_info);
2695 type_init(pci_register_types)