pci core: assert ENOSPC when add capability
[qemu/ar7.git] / hw / pci / pci.c
blob4b585f47b6aaf17786c51e0bc88a2652d653b3ef
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 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
53 static char *pcibus_get_dev_path(DeviceState *dev);
54 static char *pcibus_get_fw_dev_path(DeviceState *dev);
55 static void pcibus_reset(BusState *qbus);
57 static Property pci_props[] = {
58 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
59 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
60 DEFINE_PROP_UINT32("rombar", PCIDevice, rom_bar, 1),
61 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
62 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
63 DEFINE_PROP_BIT("command_serr_enable", PCIDevice, cap_present,
64 QEMU_PCI_CAP_SERR_BITNR, true),
65 DEFINE_PROP_END_OF_LIST()
68 static const VMStateDescription vmstate_pcibus = {
69 .name = "PCIBUS",
70 .version_id = 1,
71 .minimum_version_id = 1,
72 .fields = (VMStateField[]) {
73 VMSTATE_INT32_EQUAL(nirq, PCIBus),
74 VMSTATE_VARRAY_INT32(irq_count, PCIBus,
75 nirq, 0, vmstate_info_int32,
76 int32_t),
77 VMSTATE_END_OF_LIST()
81 static void pci_bus_realize(BusState *qbus, Error **errp)
83 PCIBus *bus = PCI_BUS(qbus);
85 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
88 static void pci_bus_unrealize(BusState *qbus, Error **errp)
90 PCIBus *bus = PCI_BUS(qbus);
92 vmstate_unregister(NULL, &vmstate_pcibus, bus);
95 static bool pcibus_is_root(PCIBus *bus)
97 return !bus->parent_dev;
100 static int pcibus_num(PCIBus *bus)
102 if (pcibus_is_root(bus)) {
103 return 0; /* pci host bridge */
105 return bus->parent_dev->config[PCI_SECONDARY_BUS];
108 static uint16_t pcibus_numa_node(PCIBus *bus)
110 return NUMA_NODE_UNASSIGNED;
113 static void pci_bus_class_init(ObjectClass *klass, void *data)
115 BusClass *k = BUS_CLASS(klass);
116 PCIBusClass *pbc = PCI_BUS_CLASS(klass);
118 k->print_dev = pcibus_dev_print;
119 k->get_dev_path = pcibus_get_dev_path;
120 k->get_fw_dev_path = pcibus_get_fw_dev_path;
121 k->realize = pci_bus_realize;
122 k->unrealize = pci_bus_unrealize;
123 k->reset = pcibus_reset;
125 pbc->is_root = pcibus_is_root;
126 pbc->bus_num = pcibus_num;
127 pbc->numa_node = pcibus_numa_node;
130 static const TypeInfo pci_bus_info = {
131 .name = TYPE_PCI_BUS,
132 .parent = TYPE_BUS,
133 .instance_size = sizeof(PCIBus),
134 .class_size = sizeof(PCIBusClass),
135 .class_init = pci_bus_class_init,
138 static const TypeInfo pcie_bus_info = {
139 .name = TYPE_PCIE_BUS,
140 .parent = TYPE_PCI_BUS,
143 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num);
144 static void pci_update_mappings(PCIDevice *d);
145 static void pci_irq_handler(void *opaque, int irq_num, int level);
146 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
147 static void pci_del_option_rom(PCIDevice *pdev);
149 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
150 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
152 static QLIST_HEAD(, PCIHostState) pci_host_bridges;
154 int pci_bar(PCIDevice *d, int reg)
156 uint8_t type;
158 if (reg != PCI_ROM_SLOT)
159 return PCI_BASE_ADDRESS_0 + reg * 4;
161 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
162 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
165 static inline int pci_irq_state(PCIDevice *d, int irq_num)
167 return (d->irq_state >> irq_num) & 0x1;
170 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
172 d->irq_state &= ~(0x1 << irq_num);
173 d->irq_state |= level << irq_num;
176 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
178 PCIBus *bus;
179 for (;;) {
180 bus = pci_dev->bus;
181 irq_num = bus->map_irq(pci_dev, irq_num);
182 if (bus->set_irq)
183 break;
184 pci_dev = bus->parent_dev;
186 bus->irq_count[irq_num] += change;
187 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
190 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
192 assert(irq_num >= 0);
193 assert(irq_num < bus->nirq);
194 return !!bus->irq_count[irq_num];
197 /* Update interrupt status bit in config space on interrupt
198 * state change. */
199 static void pci_update_irq_status(PCIDevice *dev)
201 if (dev->irq_state) {
202 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
203 } else {
204 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
208 void pci_device_deassert_intx(PCIDevice *dev)
210 int i;
211 for (i = 0; i < PCI_NUM_PINS; ++i) {
212 pci_irq_handler(dev, i, 0);
216 static void pci_do_device_reset(PCIDevice *dev)
218 int r;
220 pci_device_deassert_intx(dev);
221 assert(dev->irq_state == 0);
223 /* Clear all writable bits */
224 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
225 pci_get_word(dev->wmask + PCI_COMMAND) |
226 pci_get_word(dev->w1cmask + PCI_COMMAND));
227 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
228 pci_get_word(dev->wmask + PCI_STATUS) |
229 pci_get_word(dev->w1cmask + PCI_STATUS));
230 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
231 dev->config[PCI_INTERRUPT_LINE] = 0x0;
232 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
233 PCIIORegion *region = &dev->io_regions[r];
234 if (!region->size) {
235 continue;
238 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
239 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
240 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
241 } else {
242 pci_set_long(dev->config + pci_bar(dev, r), region->type);
245 pci_update_mappings(dev);
247 msi_reset(dev);
248 msix_reset(dev);
252 * This function is called on #RST and FLR.
253 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
255 void pci_device_reset(PCIDevice *dev)
257 qdev_reset_all(&dev->qdev);
258 pci_do_device_reset(dev);
262 * Trigger pci bus reset under a given bus.
263 * Called via qbus_reset_all on RST# assert, after the devices
264 * have been reset qdev_reset_all-ed already.
266 static void pcibus_reset(BusState *qbus)
268 PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
269 int i;
271 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
272 if (bus->devices[i]) {
273 pci_do_device_reset(bus->devices[i]);
277 for (i = 0; i < bus->nirq; i++) {
278 assert(bus->irq_count[i] == 0);
282 static void pci_host_bus_register(DeviceState *host)
284 PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
286 QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
289 PCIBus *pci_find_primary_bus(void)
291 PCIBus *primary_bus = NULL;
292 PCIHostState *host;
294 QLIST_FOREACH(host, &pci_host_bridges, next) {
295 if (primary_bus) {
296 /* We have multiple root buses, refuse to select a primary */
297 return NULL;
299 primary_bus = host->bus;
302 return primary_bus;
305 PCIBus *pci_device_root_bus(const PCIDevice *d)
307 PCIBus *bus = d->bus;
309 while (!pci_bus_is_root(bus)) {
310 d = bus->parent_dev;
311 assert(d != NULL);
313 bus = d->bus;
316 return bus;
319 const char *pci_root_bus_path(PCIDevice *dev)
321 PCIBus *rootbus = pci_device_root_bus(dev);
322 PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
323 PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
325 assert(host_bridge->bus == rootbus);
327 if (hc->root_bus_path) {
328 return (*hc->root_bus_path)(host_bridge, rootbus);
331 return rootbus->qbus.name;
334 static void pci_bus_init(PCIBus *bus, DeviceState *parent,
335 MemoryRegion *address_space_mem,
336 MemoryRegion *address_space_io,
337 uint8_t devfn_min)
339 assert(PCI_FUNC(devfn_min) == 0);
340 bus->devfn_min = devfn_min;
341 bus->address_space_mem = address_space_mem;
342 bus->address_space_io = address_space_io;
344 /* host bridge */
345 QLIST_INIT(&bus->child);
347 pci_host_bus_register(parent);
350 bool pci_bus_is_express(PCIBus *bus)
352 return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
355 bool pci_bus_is_root(PCIBus *bus)
357 return PCI_BUS_GET_CLASS(bus)->is_root(bus);
360 void pci_bus_new_inplace(PCIBus *bus, size_t bus_size, DeviceState *parent,
361 const char *name,
362 MemoryRegion *address_space_mem,
363 MemoryRegion *address_space_io,
364 uint8_t devfn_min, const char *typename)
366 qbus_create_inplace(bus, bus_size, typename, parent, name);
367 pci_bus_init(bus, parent, address_space_mem, address_space_io, devfn_min);
370 PCIBus *pci_bus_new(DeviceState *parent, const char *name,
371 MemoryRegion *address_space_mem,
372 MemoryRegion *address_space_io,
373 uint8_t devfn_min, const char *typename)
375 PCIBus *bus;
377 bus = PCI_BUS(qbus_create(typename, parent, name));
378 pci_bus_init(bus, parent, address_space_mem, address_space_io, devfn_min);
379 return bus;
382 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
383 void *irq_opaque, int nirq)
385 bus->set_irq = set_irq;
386 bus->map_irq = map_irq;
387 bus->irq_opaque = irq_opaque;
388 bus->nirq = nirq;
389 bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
392 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
393 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
394 void *irq_opaque,
395 MemoryRegion *address_space_mem,
396 MemoryRegion *address_space_io,
397 uint8_t devfn_min, int nirq, const char *typename)
399 PCIBus *bus;
401 bus = pci_bus_new(parent, name, address_space_mem,
402 address_space_io, devfn_min, typename);
403 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
404 return bus;
407 int pci_bus_num(PCIBus *s)
409 return PCI_BUS_GET_CLASS(s)->bus_num(s);
412 int pci_bus_numa_node(PCIBus *bus)
414 return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
417 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
419 PCIDevice *s = container_of(pv, PCIDevice, config);
420 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(s);
421 uint8_t *config;
422 int i;
424 assert(size == pci_config_size(s));
425 config = g_malloc(size);
427 qemu_get_buffer(f, config, size);
428 for (i = 0; i < size; ++i) {
429 if ((config[i] ^ s->config[i]) &
430 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
431 error_report("%s: Bad config data: i=0x%x read: %x device: %x "
432 "cmask: %x wmask: %x w1cmask:%x", __func__,
433 i, config[i], s->config[i],
434 s->cmask[i], s->wmask[i], s->w1cmask[i]);
435 g_free(config);
436 return -EINVAL;
439 memcpy(s->config, config, size);
441 pci_update_mappings(s);
442 if (pc->is_bridge) {
443 PCIBridge *b = PCI_BRIDGE(s);
444 pci_bridge_update_mappings(b);
447 memory_region_set_enabled(&s->bus_master_enable_region,
448 pci_get_word(s->config + PCI_COMMAND)
449 & PCI_COMMAND_MASTER);
451 g_free(config);
452 return 0;
455 /* just put buffer */
456 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
458 const uint8_t **v = pv;
459 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
460 qemu_put_buffer(f, *v, size);
463 static VMStateInfo vmstate_info_pci_config = {
464 .name = "pci config",
465 .get = get_pci_config_device,
466 .put = put_pci_config_device,
469 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
471 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
472 uint32_t irq_state[PCI_NUM_PINS];
473 int i;
474 for (i = 0; i < PCI_NUM_PINS; ++i) {
475 irq_state[i] = qemu_get_be32(f);
476 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
477 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
478 irq_state[i]);
479 return -EINVAL;
483 for (i = 0; i < PCI_NUM_PINS; ++i) {
484 pci_set_irq_state(s, i, irq_state[i]);
487 return 0;
490 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
492 int i;
493 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
495 for (i = 0; i < PCI_NUM_PINS; ++i) {
496 qemu_put_be32(f, pci_irq_state(s, i));
500 static VMStateInfo vmstate_info_pci_irq_state = {
501 .name = "pci irq state",
502 .get = get_pci_irq_state,
503 .put = put_pci_irq_state,
506 const VMStateDescription vmstate_pci_device = {
507 .name = "PCIDevice",
508 .version_id = 2,
509 .minimum_version_id = 1,
510 .fields = (VMStateField[]) {
511 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
512 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
513 vmstate_info_pci_config,
514 PCI_CONFIG_SPACE_SIZE),
515 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
516 vmstate_info_pci_irq_state,
517 PCI_NUM_PINS * sizeof(int32_t)),
518 VMSTATE_END_OF_LIST()
522 const VMStateDescription vmstate_pcie_device = {
523 .name = "PCIEDevice",
524 .version_id = 2,
525 .minimum_version_id = 1,
526 .fields = (VMStateField[]) {
527 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
528 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
529 vmstate_info_pci_config,
530 PCIE_CONFIG_SPACE_SIZE),
531 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
532 vmstate_info_pci_irq_state,
533 PCI_NUM_PINS * sizeof(int32_t)),
534 VMSTATE_END_OF_LIST()
538 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
540 return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
543 void pci_device_save(PCIDevice *s, QEMUFile *f)
545 /* Clear interrupt status bit: it is implicit
546 * in irq_state which we are saving.
547 * This makes us compatible with old devices
548 * which never set or clear this bit. */
549 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
550 vmstate_save_state(f, pci_get_vmstate(s), s, NULL);
551 /* Restore the interrupt status bit. */
552 pci_update_irq_status(s);
555 int pci_device_load(PCIDevice *s, QEMUFile *f)
557 int ret;
558 ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
559 /* Restore the interrupt status bit. */
560 pci_update_irq_status(s);
561 return ret;
564 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
566 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
567 pci_default_sub_vendor_id);
568 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
569 pci_default_sub_device_id);
573 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
574 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
576 static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
577 unsigned int *slotp, unsigned int *funcp)
579 const char *p;
580 char *e;
581 unsigned long val;
582 unsigned long dom = 0, bus = 0;
583 unsigned int slot = 0;
584 unsigned int func = 0;
586 p = addr;
587 val = strtoul(p, &e, 16);
588 if (e == p)
589 return -1;
590 if (*e == ':') {
591 bus = val;
592 p = e + 1;
593 val = strtoul(p, &e, 16);
594 if (e == p)
595 return -1;
596 if (*e == ':') {
597 dom = bus;
598 bus = val;
599 p = e + 1;
600 val = strtoul(p, &e, 16);
601 if (e == p)
602 return -1;
606 slot = val;
608 if (funcp != NULL) {
609 if (*e != '.')
610 return -1;
612 p = e + 1;
613 val = strtoul(p, &e, 16);
614 if (e == p)
615 return -1;
617 func = val;
620 /* if funcp == NULL func is 0 */
621 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
622 return -1;
624 if (*e)
625 return -1;
627 *domp = dom;
628 *busp = bus;
629 *slotp = slot;
630 if (funcp != NULL)
631 *funcp = func;
632 return 0;
635 static PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root,
636 const char *devaddr)
638 int dom, bus;
639 unsigned slot;
641 if (!root) {
642 fprintf(stderr, "No primary PCI bus\n");
643 return NULL;
646 assert(!root->parent_dev);
648 if (!devaddr) {
649 *devfnp = -1;
650 return pci_find_bus_nr(root, 0);
653 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
654 return NULL;
657 if (dom != 0) {
658 fprintf(stderr, "No support for non-zero PCI domains\n");
659 return NULL;
662 *devfnp = PCI_DEVFN(slot, 0);
663 return pci_find_bus_nr(root, bus);
666 static void pci_init_cmask(PCIDevice *dev)
668 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
669 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
670 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
671 dev->cmask[PCI_REVISION_ID] = 0xff;
672 dev->cmask[PCI_CLASS_PROG] = 0xff;
673 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
674 dev->cmask[PCI_HEADER_TYPE] = 0xff;
675 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
678 static void pci_init_wmask(PCIDevice *dev)
680 int config_size = pci_config_size(dev);
682 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
683 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
684 pci_set_word(dev->wmask + PCI_COMMAND,
685 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
686 PCI_COMMAND_INTX_DISABLE);
687 if (dev->cap_present & QEMU_PCI_CAP_SERR) {
688 pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
691 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
692 config_size - PCI_CONFIG_HEADER_SIZE);
695 static void pci_init_w1cmask(PCIDevice *dev)
698 * Note: It's okay to set w1cmask even for readonly bits as
699 * long as their value is hardwired to 0.
701 pci_set_word(dev->w1cmask + PCI_STATUS,
702 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
703 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
704 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
707 static void pci_init_mask_bridge(PCIDevice *d)
709 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
710 PCI_SEC_LETENCY_TIMER */
711 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
713 /* base and limit */
714 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
715 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
716 pci_set_word(d->wmask + PCI_MEMORY_BASE,
717 PCI_MEMORY_RANGE_MASK & 0xffff);
718 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
719 PCI_MEMORY_RANGE_MASK & 0xffff);
720 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
721 PCI_PREF_RANGE_MASK & 0xffff);
722 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
723 PCI_PREF_RANGE_MASK & 0xffff);
725 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
726 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
728 /* Supported memory and i/o types */
729 d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
730 d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
731 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
732 PCI_PREF_RANGE_TYPE_64);
733 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
734 PCI_PREF_RANGE_TYPE_64);
737 * TODO: Bridges default to 10-bit VGA decoding but we currently only
738 * implement 16-bit decoding (no alias support).
740 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
741 PCI_BRIDGE_CTL_PARITY |
742 PCI_BRIDGE_CTL_SERR |
743 PCI_BRIDGE_CTL_ISA |
744 PCI_BRIDGE_CTL_VGA |
745 PCI_BRIDGE_CTL_VGA_16BIT |
746 PCI_BRIDGE_CTL_MASTER_ABORT |
747 PCI_BRIDGE_CTL_BUS_RESET |
748 PCI_BRIDGE_CTL_FAST_BACK |
749 PCI_BRIDGE_CTL_DISCARD |
750 PCI_BRIDGE_CTL_SEC_DISCARD |
751 PCI_BRIDGE_CTL_DISCARD_SERR);
752 /* Below does not do anything as we never set this bit, put here for
753 * completeness. */
754 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
755 PCI_BRIDGE_CTL_DISCARD_STATUS);
756 d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
757 d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
758 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
759 PCI_PREF_RANGE_TYPE_MASK);
760 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
761 PCI_PREF_RANGE_TYPE_MASK);
764 static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
766 uint8_t slot = PCI_SLOT(dev->devfn);
767 uint8_t func;
769 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
770 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
774 * multifunction bit is interpreted in two ways as follows.
775 * - all functions must set the bit to 1.
776 * Example: Intel X53
777 * - function 0 must set the bit, but the rest function (> 0)
778 * is allowed to leave the bit to 0.
779 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
781 * So OS (at least Linux) checks the bit of only function 0,
782 * and doesn't see the bit of function > 0.
784 * The below check allows both interpretation.
786 if (PCI_FUNC(dev->devfn)) {
787 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
788 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
789 /* function 0 should set multifunction bit */
790 error_setg(errp, "PCI: single function device can't be populated "
791 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
792 return;
794 return;
797 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
798 return;
800 /* function 0 indicates single function, so function > 0 must be NULL */
801 for (func = 1; func < PCI_FUNC_MAX; ++func) {
802 if (bus->devices[PCI_DEVFN(slot, func)]) {
803 error_setg(errp, "PCI: %x.0 indicates single function, "
804 "but %x.%x is already populated.",
805 slot, slot, func);
806 return;
811 static void pci_config_alloc(PCIDevice *pci_dev)
813 int config_size = pci_config_size(pci_dev);
815 pci_dev->config = g_malloc0(config_size);
816 pci_dev->cmask = g_malloc0(config_size);
817 pci_dev->wmask = g_malloc0(config_size);
818 pci_dev->w1cmask = g_malloc0(config_size);
819 pci_dev->used = g_malloc0(config_size);
822 static void pci_config_free(PCIDevice *pci_dev)
824 g_free(pci_dev->config);
825 g_free(pci_dev->cmask);
826 g_free(pci_dev->wmask);
827 g_free(pci_dev->w1cmask);
828 g_free(pci_dev->used);
831 static void do_pci_unregister_device(PCIDevice *pci_dev)
833 pci_dev->bus->devices[pci_dev->devfn] = NULL;
834 pci_config_free(pci_dev);
836 address_space_destroy(&pci_dev->bus_master_as);
839 /* Extract PCIReqIDCache into BDF format */
840 static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
842 uint8_t bus_n;
843 uint16_t result;
845 switch (cache->type) {
846 case PCI_REQ_ID_BDF:
847 result = pci_get_bdf(cache->dev);
848 break;
849 case PCI_REQ_ID_SECONDARY_BUS:
850 bus_n = pci_bus_num(cache->dev->bus);
851 result = PCI_BUILD_BDF(bus_n, 0);
852 break;
853 default:
854 error_printf("Invalid PCI requester ID cache type: %d\n",
855 cache->type);
856 exit(1);
857 break;
860 return result;
863 /* Parse bridges up to the root complex and return requester ID
864 * cache for specific device. For full PCIe topology, the cache
865 * result would be exactly the same as getting BDF of the device.
866 * However, several tricks are required when system mixed up with
867 * legacy PCI devices and PCIe-to-PCI bridges.
869 * Here we cache the proxy device (and type) not requester ID since
870 * bus number might change from time to time.
872 static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
874 PCIDevice *parent;
875 PCIReqIDCache cache = {
876 .dev = dev,
877 .type = PCI_REQ_ID_BDF,
880 while (!pci_bus_is_root(dev->bus)) {
881 /* We are under PCI/PCIe bridges */
882 parent = dev->bus->parent_dev;
883 if (pci_is_express(parent)) {
884 if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
885 /* When we pass through PCIe-to-PCI/PCIX bridges, we
886 * override the requester ID using secondary bus
887 * number of parent bridge with zeroed devfn
888 * (pcie-to-pci bridge spec chap 2.3). */
889 cache.type = PCI_REQ_ID_SECONDARY_BUS;
890 cache.dev = dev;
892 } else {
893 /* Legacy PCI, override requester ID with the bridge's
894 * BDF upstream. When the root complex connects to
895 * legacy PCI devices (including buses), it can only
896 * obtain requester ID info from directly attached
897 * devices. If devices are attached under bridges, only
898 * the requester ID of the bridge that is directly
899 * attached to the root complex can be recognized. */
900 cache.type = PCI_REQ_ID_BDF;
901 cache.dev = parent;
903 dev = parent;
906 return cache;
909 uint16_t pci_requester_id(PCIDevice *dev)
911 return pci_req_id_cache_extract(&dev->requester_id_cache);
914 /* -1 for devfn means auto assign */
915 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
916 const char *name, int devfn,
917 Error **errp)
919 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
920 PCIConfigReadFunc *config_read = pc->config_read;
921 PCIConfigWriteFunc *config_write = pc->config_write;
922 Error *local_err = NULL;
923 AddressSpace *dma_as;
924 DeviceState *dev = DEVICE(pci_dev);
926 pci_dev->bus = bus;
927 /* Only pci bridges can be attached to extra PCI root buses */
928 if (pci_bus_is_root(bus) && bus->parent_dev && !pc->is_bridge) {
929 error_setg(errp,
930 "PCI: Only PCI/PCIe bridges can be plugged into %s",
931 bus->parent_dev->name);
932 return NULL;
935 if (devfn < 0) {
936 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
937 devfn += PCI_FUNC_MAX) {
938 if (!bus->devices[devfn])
939 goto found;
941 error_setg(errp, "PCI: no slot/function available for %s, all in use",
942 name);
943 return NULL;
944 found: ;
945 } else if (bus->devices[devfn]) {
946 error_setg(errp, "PCI: slot %d function %d not available for %s,"
947 " in use by %s",
948 PCI_SLOT(devfn), PCI_FUNC(devfn), name,
949 bus->devices[devfn]->name);
950 return NULL;
951 } else if (dev->hotplugged &&
952 pci_get_function_0(pci_dev)) {
953 error_setg(errp, "PCI: slot %d function 0 already ocuppied by %s,"
954 " new func %s cannot be exposed to guest.",
955 PCI_SLOT(devfn),
956 bus->devices[PCI_DEVFN(PCI_SLOT(devfn), 0)]->name,
957 name);
959 return NULL;
962 pci_dev->devfn = devfn;
963 pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
964 dma_as = pci_device_iommu_address_space(pci_dev);
966 memory_region_init_alias(&pci_dev->bus_master_enable_region,
967 OBJECT(pci_dev), "bus master",
968 dma_as->root, 0, memory_region_size(dma_as->root));
969 memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
970 address_space_init(&pci_dev->bus_master_as, &pci_dev->bus_master_enable_region,
971 name);
973 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
974 pci_dev->irq_state = 0;
975 pci_config_alloc(pci_dev);
977 pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
978 pci_config_set_device_id(pci_dev->config, pc->device_id);
979 pci_config_set_revision(pci_dev->config, pc->revision);
980 pci_config_set_class(pci_dev->config, pc->class_id);
982 if (!pc->is_bridge) {
983 if (pc->subsystem_vendor_id || pc->subsystem_id) {
984 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
985 pc->subsystem_vendor_id);
986 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
987 pc->subsystem_id);
988 } else {
989 pci_set_default_subsystem_id(pci_dev);
991 } else {
992 /* subsystem_vendor_id/subsystem_id are only for header type 0 */
993 assert(!pc->subsystem_vendor_id);
994 assert(!pc->subsystem_id);
996 pci_init_cmask(pci_dev);
997 pci_init_wmask(pci_dev);
998 pci_init_w1cmask(pci_dev);
999 if (pc->is_bridge) {
1000 pci_init_mask_bridge(pci_dev);
1002 pci_init_multifunction(bus, pci_dev, &local_err);
1003 if (local_err) {
1004 error_propagate(errp, local_err);
1005 do_pci_unregister_device(pci_dev);
1006 return NULL;
1009 if (!config_read)
1010 config_read = pci_default_read_config;
1011 if (!config_write)
1012 config_write = pci_default_write_config;
1013 pci_dev->config_read = config_read;
1014 pci_dev->config_write = config_write;
1015 bus->devices[devfn] = pci_dev;
1016 pci_dev->version_id = 2; /* Current pci device vmstate version */
1017 return pci_dev;
1020 static void pci_unregister_io_regions(PCIDevice *pci_dev)
1022 PCIIORegion *r;
1023 int i;
1025 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1026 r = &pci_dev->io_regions[i];
1027 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
1028 continue;
1029 memory_region_del_subregion(r->address_space, r->memory);
1032 pci_unregister_vga(pci_dev);
1035 static void pci_qdev_unrealize(DeviceState *dev, Error **errp)
1037 PCIDevice *pci_dev = PCI_DEVICE(dev);
1038 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1040 pci_unregister_io_regions(pci_dev);
1041 pci_del_option_rom(pci_dev);
1043 if (pc->exit) {
1044 pc->exit(pci_dev);
1047 do_pci_unregister_device(pci_dev);
1050 void pci_register_bar(PCIDevice *pci_dev, int region_num,
1051 uint8_t type, MemoryRegion *memory)
1053 PCIIORegion *r;
1054 uint32_t addr;
1055 uint64_t wmask;
1056 pcibus_t size = memory_region_size(memory);
1058 assert(region_num >= 0);
1059 assert(region_num < PCI_NUM_REGIONS);
1060 if (size & (size-1)) {
1061 fprintf(stderr, "ERROR: PCI region size must be pow2 "
1062 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
1063 exit(1);
1066 r = &pci_dev->io_regions[region_num];
1067 r->addr = PCI_BAR_UNMAPPED;
1068 r->size = size;
1069 r->type = type;
1070 r->memory = NULL;
1072 wmask = ~(size - 1);
1073 addr = pci_bar(pci_dev, region_num);
1074 if (region_num == PCI_ROM_SLOT) {
1075 /* ROM enable bit is writable */
1076 wmask |= PCI_ROM_ADDRESS_ENABLE;
1078 pci_set_long(pci_dev->config + addr, type);
1079 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1080 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1081 pci_set_quad(pci_dev->wmask + addr, wmask);
1082 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1083 } else {
1084 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1085 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1087 pci_dev->io_regions[region_num].memory = memory;
1088 pci_dev->io_regions[region_num].address_space
1089 = type & PCI_BASE_ADDRESS_SPACE_IO
1090 ? pci_dev->bus->address_space_io
1091 : pci_dev->bus->address_space_mem;
1094 static void pci_update_vga(PCIDevice *pci_dev)
1096 uint16_t cmd;
1098 if (!pci_dev->has_vga) {
1099 return;
1102 cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1104 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1105 cmd & PCI_COMMAND_MEMORY);
1106 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1107 cmd & PCI_COMMAND_IO);
1108 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1109 cmd & PCI_COMMAND_IO);
1112 void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1113 MemoryRegion *io_lo, MemoryRegion *io_hi)
1115 assert(!pci_dev->has_vga);
1117 assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1118 pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1119 memory_region_add_subregion_overlap(pci_dev->bus->address_space_mem,
1120 QEMU_PCI_VGA_MEM_BASE, mem, 1);
1122 assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1123 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1124 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1125 QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1127 assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1128 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1129 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1130 QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1131 pci_dev->has_vga = true;
1133 pci_update_vga(pci_dev);
1136 void pci_unregister_vga(PCIDevice *pci_dev)
1138 if (!pci_dev->has_vga) {
1139 return;
1142 memory_region_del_subregion(pci_dev->bus->address_space_mem,
1143 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1144 memory_region_del_subregion(pci_dev->bus->address_space_io,
1145 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1146 memory_region_del_subregion(pci_dev->bus->address_space_io,
1147 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1148 pci_dev->has_vga = false;
1151 pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1153 return pci_dev->io_regions[region_num].addr;
1156 static pcibus_t pci_bar_address(PCIDevice *d,
1157 int reg, uint8_t type, pcibus_t size)
1159 pcibus_t new_addr, last_addr;
1160 int bar = pci_bar(d, reg);
1161 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1162 Object *machine = qdev_get_machine();
1163 ObjectClass *oc = object_get_class(machine);
1164 MachineClass *mc = MACHINE_CLASS(oc);
1165 bool allow_0_address = mc->pci_allow_0_address;
1167 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1168 if (!(cmd & PCI_COMMAND_IO)) {
1169 return PCI_BAR_UNMAPPED;
1171 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
1172 last_addr = new_addr + size - 1;
1173 /* Check if 32 bit BAR wraps around explicitly.
1174 * TODO: make priorities correct and remove this work around.
1176 if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1177 (!allow_0_address && new_addr == 0)) {
1178 return PCI_BAR_UNMAPPED;
1180 return new_addr;
1183 if (!(cmd & PCI_COMMAND_MEMORY)) {
1184 return PCI_BAR_UNMAPPED;
1186 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1187 new_addr = pci_get_quad(d->config + bar);
1188 } else {
1189 new_addr = pci_get_long(d->config + bar);
1191 /* the ROM slot has a specific enable bit */
1192 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1193 return PCI_BAR_UNMAPPED;
1195 new_addr &= ~(size - 1);
1196 last_addr = new_addr + size - 1;
1197 /* NOTE: we do not support wrapping */
1198 /* XXX: as we cannot support really dynamic
1199 mappings, we handle specific values as invalid
1200 mappings. */
1201 if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1202 (!allow_0_address && new_addr == 0)) {
1203 return PCI_BAR_UNMAPPED;
1206 /* Now pcibus_t is 64bit.
1207 * Check if 32 bit BAR wraps around explicitly.
1208 * Without this, PC ide doesn't work well.
1209 * TODO: remove this work around.
1211 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1212 return PCI_BAR_UNMAPPED;
1216 * OS is allowed to set BAR beyond its addressable
1217 * bits. For example, 32 bit OS can set 64bit bar
1218 * to >4G. Check it. TODO: we might need to support
1219 * it in the future for e.g. PAE.
1221 if (last_addr >= HWADDR_MAX) {
1222 return PCI_BAR_UNMAPPED;
1225 return new_addr;
1228 static void pci_update_mappings(PCIDevice *d)
1230 PCIIORegion *r;
1231 int i;
1232 pcibus_t new_addr;
1234 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1235 r = &d->io_regions[i];
1237 /* this region isn't registered */
1238 if (!r->size)
1239 continue;
1241 new_addr = pci_bar_address(d, i, r->type, r->size);
1243 /* This bar isn't changed */
1244 if (new_addr == r->addr)
1245 continue;
1247 /* now do the real mapping */
1248 if (r->addr != PCI_BAR_UNMAPPED) {
1249 trace_pci_update_mappings_del(d, pci_bus_num(d->bus),
1250 PCI_SLOT(d->devfn),
1251 PCI_FUNC(d->devfn),
1252 i, r->addr, r->size);
1253 memory_region_del_subregion(r->address_space, r->memory);
1255 r->addr = new_addr;
1256 if (r->addr != PCI_BAR_UNMAPPED) {
1257 trace_pci_update_mappings_add(d, pci_bus_num(d->bus),
1258 PCI_SLOT(d->devfn),
1259 PCI_FUNC(d->devfn),
1260 i, r->addr, r->size);
1261 memory_region_add_subregion_overlap(r->address_space,
1262 r->addr, r->memory, 1);
1266 pci_update_vga(d);
1269 static inline int pci_irq_disabled(PCIDevice *d)
1271 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1274 /* Called after interrupt disabled field update in config space,
1275 * assert/deassert interrupts if necessary.
1276 * Gets original interrupt disable bit value (before update). */
1277 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1279 int i, disabled = pci_irq_disabled(d);
1280 if (disabled == was_irq_disabled)
1281 return;
1282 for (i = 0; i < PCI_NUM_PINS; ++i) {
1283 int state = pci_irq_state(d, i);
1284 pci_change_irq_level(d, i, disabled ? -state : state);
1288 uint32_t pci_default_read_config(PCIDevice *d,
1289 uint32_t address, int len)
1291 uint32_t val = 0;
1293 memcpy(&val, d->config + address, len);
1294 return le32_to_cpu(val);
1297 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1299 int i, was_irq_disabled = pci_irq_disabled(d);
1300 uint32_t val = val_in;
1302 for (i = 0; i < l; val >>= 8, ++i) {
1303 uint8_t wmask = d->wmask[addr + i];
1304 uint8_t w1cmask = d->w1cmask[addr + i];
1305 assert(!(wmask & w1cmask));
1306 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1307 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1309 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1310 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1311 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1312 range_covers_byte(addr, l, PCI_COMMAND))
1313 pci_update_mappings(d);
1315 if (range_covers_byte(addr, l, PCI_COMMAND)) {
1316 pci_update_irq_disabled(d, was_irq_disabled);
1317 memory_region_set_enabled(&d->bus_master_enable_region,
1318 pci_get_word(d->config + PCI_COMMAND)
1319 & PCI_COMMAND_MASTER);
1322 msi_write_config(d, addr, val_in, l);
1323 msix_write_config(d, addr, val_in, l);
1326 /***********************************************************/
1327 /* generic PCI irq support */
1329 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1330 static void pci_irq_handler(void *opaque, int irq_num, int level)
1332 PCIDevice *pci_dev = opaque;
1333 int change;
1335 change = level - pci_irq_state(pci_dev, irq_num);
1336 if (!change)
1337 return;
1339 pci_set_irq_state(pci_dev, irq_num, level);
1340 pci_update_irq_status(pci_dev);
1341 if (pci_irq_disabled(pci_dev))
1342 return;
1343 pci_change_irq_level(pci_dev, irq_num, change);
1346 static inline int pci_intx(PCIDevice *pci_dev)
1348 return pci_get_byte(pci_dev->config + PCI_INTERRUPT_PIN) - 1;
1351 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1353 int intx = pci_intx(pci_dev);
1355 return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1358 void pci_set_irq(PCIDevice *pci_dev, int level)
1360 int intx = pci_intx(pci_dev);
1361 pci_irq_handler(pci_dev, intx, level);
1364 /* Special hooks used by device assignment */
1365 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1367 assert(pci_bus_is_root(bus));
1368 bus->route_intx_to_irq = route_intx_to_irq;
1371 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1373 PCIBus *bus;
1375 do {
1376 bus = dev->bus;
1377 pin = bus->map_irq(dev, pin);
1378 dev = bus->parent_dev;
1379 } while (dev);
1381 if (!bus->route_intx_to_irq) {
1382 error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1383 object_get_typename(OBJECT(bus->qbus.parent)));
1384 return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1387 return bus->route_intx_to_irq(bus->irq_opaque, pin);
1390 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1392 return old->mode != new->mode || old->irq != new->irq;
1395 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1397 PCIDevice *dev;
1398 PCIBus *sec;
1399 int i;
1401 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1402 dev = bus->devices[i];
1403 if (dev && dev->intx_routing_notifier) {
1404 dev->intx_routing_notifier(dev);
1408 QLIST_FOREACH(sec, &bus->child, sibling) {
1409 pci_bus_fire_intx_routing_notifier(sec);
1413 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1414 PCIINTxRoutingNotifier notifier)
1416 dev->intx_routing_notifier = notifier;
1420 * PCI-to-PCI bridge specification
1421 * 9.1: Interrupt routing. Table 9-1
1423 * the PCI Express Base Specification, Revision 2.1
1424 * 2.2.8.1: INTx interrutp signaling - Rules
1425 * the Implementation Note
1426 * Table 2-20
1429 * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1430 * 0-origin unlike PCI interrupt pin register.
1432 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1434 return (pin + PCI_SLOT(pci_dev->devfn)) % PCI_NUM_PINS;
1437 /***********************************************************/
1438 /* monitor info on PCI */
1440 typedef struct {
1441 uint16_t class;
1442 const char *desc;
1443 const char *fw_name;
1444 uint16_t fw_ign_bits;
1445 } pci_class_desc;
1447 static const pci_class_desc pci_class_descriptions[] =
1449 { 0x0001, "VGA controller", "display"},
1450 { 0x0100, "SCSI controller", "scsi"},
1451 { 0x0101, "IDE controller", "ide"},
1452 { 0x0102, "Floppy controller", "fdc"},
1453 { 0x0103, "IPI controller", "ipi"},
1454 { 0x0104, "RAID controller", "raid"},
1455 { 0x0106, "SATA controller"},
1456 { 0x0107, "SAS controller"},
1457 { 0x0180, "Storage controller"},
1458 { 0x0200, "Ethernet controller", "ethernet"},
1459 { 0x0201, "Token Ring controller", "token-ring"},
1460 { 0x0202, "FDDI controller", "fddi"},
1461 { 0x0203, "ATM controller", "atm"},
1462 { 0x0280, "Network controller"},
1463 { 0x0300, "VGA controller", "display", 0x00ff},
1464 { 0x0301, "XGA controller"},
1465 { 0x0302, "3D controller"},
1466 { 0x0380, "Display controller"},
1467 { 0x0400, "Video controller", "video"},
1468 { 0x0401, "Audio controller", "sound"},
1469 { 0x0402, "Phone"},
1470 { 0x0403, "Audio controller", "sound"},
1471 { 0x0480, "Multimedia controller"},
1472 { 0x0500, "RAM controller", "memory"},
1473 { 0x0501, "Flash controller", "flash"},
1474 { 0x0580, "Memory controller"},
1475 { 0x0600, "Host bridge", "host"},
1476 { 0x0601, "ISA bridge", "isa"},
1477 { 0x0602, "EISA bridge", "eisa"},
1478 { 0x0603, "MC bridge", "mca"},
1479 { 0x0604, "PCI bridge", "pci-bridge"},
1480 { 0x0605, "PCMCIA bridge", "pcmcia"},
1481 { 0x0606, "NUBUS bridge", "nubus"},
1482 { 0x0607, "CARDBUS bridge", "cardbus"},
1483 { 0x0608, "RACEWAY bridge"},
1484 { 0x0680, "Bridge"},
1485 { 0x0700, "Serial port", "serial"},
1486 { 0x0701, "Parallel port", "parallel"},
1487 { 0x0800, "Interrupt controller", "interrupt-controller"},
1488 { 0x0801, "DMA controller", "dma-controller"},
1489 { 0x0802, "Timer", "timer"},
1490 { 0x0803, "RTC", "rtc"},
1491 { 0x0900, "Keyboard", "keyboard"},
1492 { 0x0901, "Pen", "pen"},
1493 { 0x0902, "Mouse", "mouse"},
1494 { 0x0A00, "Dock station", "dock", 0x00ff},
1495 { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1496 { 0x0c00, "Fireware contorller", "fireware"},
1497 { 0x0c01, "Access bus controller", "access-bus"},
1498 { 0x0c02, "SSA controller", "ssa"},
1499 { 0x0c03, "USB controller", "usb"},
1500 { 0x0c04, "Fibre channel controller", "fibre-channel"},
1501 { 0x0c05, "SMBus"},
1502 { 0, NULL}
1505 static void pci_for_each_device_under_bus(PCIBus *bus,
1506 void (*fn)(PCIBus *b, PCIDevice *d,
1507 void *opaque),
1508 void *opaque)
1510 PCIDevice *d;
1511 int devfn;
1513 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1514 d = bus->devices[devfn];
1515 if (d) {
1516 fn(bus, d, opaque);
1521 void pci_for_each_device(PCIBus *bus, int bus_num,
1522 void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
1523 void *opaque)
1525 bus = pci_find_bus_nr(bus, bus_num);
1527 if (bus) {
1528 pci_for_each_device_under_bus(bus, fn, opaque);
1532 static const pci_class_desc *get_class_desc(int class)
1534 const pci_class_desc *desc;
1536 desc = pci_class_descriptions;
1537 while (desc->desc && class != desc->class) {
1538 desc++;
1541 return desc;
1544 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num);
1546 static PciMemoryRegionList *qmp_query_pci_regions(const PCIDevice *dev)
1548 PciMemoryRegionList *head = NULL, *cur_item = NULL;
1549 int i;
1551 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1552 const PCIIORegion *r = &dev->io_regions[i];
1553 PciMemoryRegionList *region;
1555 if (!r->size) {
1556 continue;
1559 region = g_malloc0(sizeof(*region));
1560 region->value = g_malloc0(sizeof(*region->value));
1562 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1563 region->value->type = g_strdup("io");
1564 } else {
1565 region->value->type = g_strdup("memory");
1566 region->value->has_prefetch = true;
1567 region->value->prefetch = !!(r->type & PCI_BASE_ADDRESS_MEM_PREFETCH);
1568 region->value->has_mem_type_64 = true;
1569 region->value->mem_type_64 = !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
1572 region->value->bar = i;
1573 region->value->address = r->addr;
1574 region->value->size = r->size;
1576 /* XXX: waiting for the qapi to support GSList */
1577 if (!cur_item) {
1578 head = cur_item = region;
1579 } else {
1580 cur_item->next = region;
1581 cur_item = region;
1585 return head;
1588 static PciBridgeInfo *qmp_query_pci_bridge(PCIDevice *dev, PCIBus *bus,
1589 int bus_num)
1591 PciBridgeInfo *info;
1592 PciMemoryRange *range;
1594 info = g_new0(PciBridgeInfo, 1);
1596 info->bus = g_new0(PciBusInfo, 1);
1597 info->bus->number = dev->config[PCI_PRIMARY_BUS];
1598 info->bus->secondary = dev->config[PCI_SECONDARY_BUS];
1599 info->bus->subordinate = dev->config[PCI_SUBORDINATE_BUS];
1601 range = info->bus->io_range = g_new0(PciMemoryRange, 1);
1602 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
1603 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
1605 range = info->bus->memory_range = g_new0(PciMemoryRange, 1);
1606 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1607 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1609 range = info->bus->prefetchable_range = g_new0(PciMemoryRange, 1);
1610 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1611 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1613 if (dev->config[PCI_SECONDARY_BUS] != 0) {
1614 PCIBus *child_bus = pci_find_bus_nr(bus, dev->config[PCI_SECONDARY_BUS]);
1615 if (child_bus) {
1616 info->has_devices = true;
1617 info->devices = qmp_query_pci_devices(child_bus, dev->config[PCI_SECONDARY_BUS]);
1621 return info;
1624 static PciDeviceInfo *qmp_query_pci_device(PCIDevice *dev, PCIBus *bus,
1625 int bus_num)
1627 const pci_class_desc *desc;
1628 PciDeviceInfo *info;
1629 uint8_t type;
1630 int class;
1632 info = g_new0(PciDeviceInfo, 1);
1633 info->bus = bus_num;
1634 info->slot = PCI_SLOT(dev->devfn);
1635 info->function = PCI_FUNC(dev->devfn);
1637 info->class_info = g_new0(PciDeviceClass, 1);
1638 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1639 info->class_info->q_class = class;
1640 desc = get_class_desc(class);
1641 if (desc->desc) {
1642 info->class_info->has_desc = true;
1643 info->class_info->desc = g_strdup(desc->desc);
1646 info->id = g_new0(PciDeviceId, 1);
1647 info->id->vendor = pci_get_word(dev->config + PCI_VENDOR_ID);
1648 info->id->device = pci_get_word(dev->config + PCI_DEVICE_ID);
1649 info->regions = qmp_query_pci_regions(dev);
1650 info->qdev_id = g_strdup(dev->qdev.id ? dev->qdev.id : "");
1652 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1653 info->has_irq = true;
1654 info->irq = dev->config[PCI_INTERRUPT_LINE];
1657 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1658 if (type == PCI_HEADER_TYPE_BRIDGE) {
1659 info->has_pci_bridge = true;
1660 info->pci_bridge = qmp_query_pci_bridge(dev, bus, bus_num);
1663 return info;
1666 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num)
1668 PciDeviceInfoList *info, *head = NULL, *cur_item = NULL;
1669 PCIDevice *dev;
1670 int devfn;
1672 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1673 dev = bus->devices[devfn];
1674 if (dev) {
1675 info = g_malloc0(sizeof(*info));
1676 info->value = qmp_query_pci_device(dev, bus, bus_num);
1678 /* XXX: waiting for the qapi to support GSList */
1679 if (!cur_item) {
1680 head = cur_item = info;
1681 } else {
1682 cur_item->next = info;
1683 cur_item = info;
1688 return head;
1691 static PciInfo *qmp_query_pci_bus(PCIBus *bus, int bus_num)
1693 PciInfo *info = NULL;
1695 bus = pci_find_bus_nr(bus, bus_num);
1696 if (bus) {
1697 info = g_malloc0(sizeof(*info));
1698 info->bus = bus_num;
1699 info->devices = qmp_query_pci_devices(bus, bus_num);
1702 return info;
1705 PciInfoList *qmp_query_pci(Error **errp)
1707 PciInfoList *info, *head = NULL, *cur_item = NULL;
1708 PCIHostState *host_bridge;
1710 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
1711 info = g_malloc0(sizeof(*info));
1712 info->value = qmp_query_pci_bus(host_bridge->bus,
1713 pci_bus_num(host_bridge->bus));
1715 /* XXX: waiting for the qapi to support GSList */
1716 if (!cur_item) {
1717 head = cur_item = info;
1718 } else {
1719 cur_item->next = info;
1720 cur_item = info;
1724 return head;
1727 static const char * const pci_nic_models[] = {
1728 "ne2k_pci",
1729 "i82551",
1730 "i82557b",
1731 "i82559er",
1732 "rtl8139",
1733 "e1000",
1734 "pcnet",
1735 "virtio",
1736 NULL
1739 static const char * const pci_nic_names[] = {
1740 "ne2k_pci",
1741 "i82551",
1742 "i82557b",
1743 "i82559er",
1744 "rtl8139",
1745 "e1000",
1746 "pcnet",
1747 "virtio-net-pci",
1748 NULL
1751 /* Initialize a PCI NIC. */
1752 PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1753 const char *default_model,
1754 const char *default_devaddr)
1756 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1757 Error *err = NULL;
1758 PCIBus *bus;
1759 PCIDevice *pci_dev;
1760 DeviceState *dev;
1761 int devfn;
1762 int i;
1764 if (qemu_show_nic_models(nd->model, pci_nic_models)) {
1765 exit(0);
1768 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1769 if (i < 0) {
1770 exit(1);
1773 bus = pci_get_bus_devfn(&devfn, rootbus, devaddr);
1774 if (!bus) {
1775 error_report("Invalid PCI device address %s for device %s",
1776 devaddr, pci_nic_names[i]);
1777 exit(1);
1780 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1781 dev = &pci_dev->qdev;
1782 qdev_set_nic_properties(dev, nd);
1784 object_property_set_bool(OBJECT(dev), true, "realized", &err);
1785 if (err) {
1786 error_report_err(err);
1787 object_unparent(OBJECT(dev));
1788 exit(1);
1791 return pci_dev;
1794 PCIDevice *pci_vga_init(PCIBus *bus)
1796 switch (vga_interface_type) {
1797 case VGA_CIRRUS:
1798 return pci_create_simple(bus, -1, "cirrus-vga");
1799 case VGA_QXL:
1800 return pci_create_simple(bus, -1, "qxl-vga");
1801 case VGA_STD:
1802 return pci_create_simple(bus, -1, "VGA");
1803 case VGA_VMWARE:
1804 return pci_create_simple(bus, -1, "vmware-svga");
1805 case VGA_VIRTIO:
1806 return pci_create_simple(bus, -1, "virtio-vga");
1807 case VGA_NONE:
1808 default: /* Other non-PCI types. Checking for unsupported types is already
1809 done in vl.c. */
1810 return NULL;
1814 /* Whether a given bus number is in range of the secondary
1815 * bus of the given bridge device. */
1816 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1818 return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1819 PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1820 dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1821 bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1824 /* Whether a given bus number is in a range of a root bus */
1825 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1827 int i;
1829 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1830 PCIDevice *dev = bus->devices[i];
1832 if (dev && PCI_DEVICE_GET_CLASS(dev)->is_bridge) {
1833 if (pci_secondary_bus_in_range(dev, bus_num)) {
1834 return true;
1839 return false;
1842 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1844 PCIBus *sec;
1846 if (!bus) {
1847 return NULL;
1850 if (pci_bus_num(bus) == bus_num) {
1851 return bus;
1854 /* Consider all bus numbers in range for the host pci bridge. */
1855 if (!pci_bus_is_root(bus) &&
1856 !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1857 return NULL;
1860 /* try child bus */
1861 for (; bus; bus = sec) {
1862 QLIST_FOREACH(sec, &bus->child, sibling) {
1863 if (pci_bus_num(sec) == bus_num) {
1864 return sec;
1866 /* PXB buses assumed to be children of bus 0 */
1867 if (pci_bus_is_root(sec)) {
1868 if (pci_root_bus_in_range(sec, bus_num)) {
1869 break;
1871 } else {
1872 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1873 break;
1879 return NULL;
1882 void pci_for_each_bus_depth_first(PCIBus *bus,
1883 void *(*begin)(PCIBus *bus, void *parent_state),
1884 void (*end)(PCIBus *bus, void *state),
1885 void *parent_state)
1887 PCIBus *sec;
1888 void *state;
1890 if (!bus) {
1891 return;
1894 if (begin) {
1895 state = begin(bus, parent_state);
1896 } else {
1897 state = parent_state;
1900 QLIST_FOREACH(sec, &bus->child, sibling) {
1901 pci_for_each_bus_depth_first(sec, begin, end, state);
1904 if (end) {
1905 end(bus, state);
1910 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1912 bus = pci_find_bus_nr(bus, bus_num);
1914 if (!bus)
1915 return NULL;
1917 return bus->devices[devfn];
1920 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
1922 PCIDevice *pci_dev = (PCIDevice *)qdev;
1923 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1924 Error *local_err = NULL;
1925 PCIBus *bus;
1926 bool is_default_rom;
1928 /* initialize cap_present for pci_is_express() and pci_config_size() */
1929 if (pc->is_express) {
1930 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1933 bus = PCI_BUS(qdev_get_parent_bus(qdev));
1934 pci_dev = do_pci_register_device(pci_dev, bus,
1935 object_get_typename(OBJECT(qdev)),
1936 pci_dev->devfn, errp);
1937 if (pci_dev == NULL)
1938 return;
1940 if (pc->realize) {
1941 pc->realize(pci_dev, &local_err);
1942 if (local_err) {
1943 error_propagate(errp, local_err);
1944 do_pci_unregister_device(pci_dev);
1945 return;
1949 /* rom loading */
1950 is_default_rom = false;
1951 if (pci_dev->romfile == NULL && pc->romfile != NULL) {
1952 pci_dev->romfile = g_strdup(pc->romfile);
1953 is_default_rom = true;
1956 pci_add_option_rom(pci_dev, is_default_rom, &local_err);
1957 if (local_err) {
1958 error_propagate(errp, local_err);
1959 pci_qdev_unrealize(DEVICE(pci_dev), NULL);
1960 return;
1964 static void pci_default_realize(PCIDevice *dev, Error **errp)
1966 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
1968 if (pc->init) {
1969 if (pc->init(dev) < 0) {
1970 error_setg(errp, "Device initialization failed");
1971 return;
1976 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1977 const char *name)
1979 DeviceState *dev;
1981 dev = qdev_create(&bus->qbus, name);
1982 qdev_prop_set_int32(dev, "addr", devfn);
1983 qdev_prop_set_bit(dev, "multifunction", multifunction);
1984 return PCI_DEVICE(dev);
1987 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1988 bool multifunction,
1989 const char *name)
1991 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1992 qdev_init_nofail(&dev->qdev);
1993 return dev;
1996 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1998 return pci_create_multifunction(bus, devfn, false, name);
2001 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2003 return pci_create_simple_multifunction(bus, devfn, false, name);
2006 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2008 int offset = PCI_CONFIG_HEADER_SIZE;
2009 int i;
2010 for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2011 if (pdev->used[i])
2012 offset = i + 1;
2013 else if (i - offset + 1 == size)
2014 return offset;
2016 return 0;
2019 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2020 uint8_t *prev_p)
2022 uint8_t next, prev;
2024 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2025 return 0;
2027 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2028 prev = next + PCI_CAP_LIST_NEXT)
2029 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2030 break;
2032 if (prev_p)
2033 *prev_p = prev;
2034 return next;
2037 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2039 uint8_t next, prev, found = 0;
2041 if (!(pdev->used[offset])) {
2042 return 0;
2045 assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2047 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2048 prev = next + PCI_CAP_LIST_NEXT) {
2049 if (next <= offset && next > found) {
2050 found = next;
2053 return found;
2056 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2057 This is needed for an option rom which is used for more than one device. */
2058 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
2060 uint16_t vendor_id;
2061 uint16_t device_id;
2062 uint16_t rom_vendor_id;
2063 uint16_t rom_device_id;
2064 uint16_t rom_magic;
2065 uint16_t pcir_offset;
2066 uint8_t checksum;
2068 /* Words in rom data are little endian (like in PCI configuration),
2069 so they can be read / written with pci_get_word / pci_set_word. */
2071 /* Only a valid rom will be patched. */
2072 rom_magic = pci_get_word(ptr);
2073 if (rom_magic != 0xaa55) {
2074 PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2075 return;
2077 pcir_offset = pci_get_word(ptr + 0x18);
2078 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2079 PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2080 return;
2083 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2084 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2085 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2086 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2088 PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2089 vendor_id, device_id, rom_vendor_id, rom_device_id);
2091 checksum = ptr[6];
2093 if (vendor_id != rom_vendor_id) {
2094 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2095 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2096 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2097 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2098 ptr[6] = checksum;
2099 pci_set_word(ptr + pcir_offset + 4, vendor_id);
2102 if (device_id != rom_device_id) {
2103 /* Patch device id and checksum (at offset 6 for etherboot roms). */
2104 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2105 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2106 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2107 ptr[6] = checksum;
2108 pci_set_word(ptr + pcir_offset + 6, device_id);
2112 /* Add an option rom for the device */
2113 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2114 Error **errp)
2116 int size;
2117 char *path;
2118 void *ptr;
2119 char name[32];
2120 const VMStateDescription *vmsd;
2122 if (!pdev->romfile)
2123 return;
2124 if (strlen(pdev->romfile) == 0)
2125 return;
2127 if (!pdev->rom_bar) {
2129 * Load rom via fw_cfg instead of creating a rom bar,
2130 * for 0.11 compatibility.
2132 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2135 * Hot-plugged devices can't use the option ROM
2136 * if the rom bar is disabled.
2138 if (DEVICE(pdev)->hotplugged) {
2139 error_setg(errp, "Hot-plugged device without ROM bar"
2140 " can't have an option ROM");
2141 return;
2144 if (class == 0x0300) {
2145 rom_add_vga(pdev->romfile);
2146 } else {
2147 rom_add_option(pdev->romfile, -1);
2149 return;
2152 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2153 if (path == NULL) {
2154 path = g_strdup(pdev->romfile);
2157 size = get_image_size(path);
2158 if (size < 0) {
2159 error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2160 g_free(path);
2161 return;
2162 } else if (size == 0) {
2163 error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2164 g_free(path);
2165 return;
2167 size = pow2ceil(size);
2169 vmsd = qdev_get_vmsd(DEVICE(pdev));
2171 if (vmsd) {
2172 snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2173 } else {
2174 snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2176 pdev->has_rom = true;
2177 memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_fatal);
2178 vmstate_register_ram(&pdev->rom, &pdev->qdev);
2179 ptr = memory_region_get_ram_ptr(&pdev->rom);
2180 load_image(path, ptr);
2181 g_free(path);
2183 if (is_default_rom) {
2184 /* Only the default rom images will be patched (if needed). */
2185 pci_patch_ids(pdev, ptr, size);
2188 pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2191 static void pci_del_option_rom(PCIDevice *pdev)
2193 if (!pdev->has_rom)
2194 return;
2196 vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2197 pdev->has_rom = false;
2201 * if offset = 0,
2202 * Find and reserve space and add capability to the linked list
2203 * in pci config space
2205 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2206 uint8_t offset, uint8_t size)
2208 int ret;
2209 Error *local_err = NULL;
2211 ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err);
2212 if (local_err) {
2213 assert(ret < 0);
2214 error_report_err(local_err);
2215 } else {
2216 /* success implies a positive offset in config space */
2217 assert(ret > 0);
2219 return ret;
2222 int pci_add_capability2(PCIDevice *pdev, uint8_t cap_id,
2223 uint8_t offset, uint8_t size,
2224 Error **errp)
2226 uint8_t *config;
2227 int i, overlapping_cap;
2229 if (!offset) {
2230 offset = pci_find_space(pdev, size);
2231 /* out of PCI config space is programming error */
2232 assert(offset);
2233 } else {
2234 /* Verify that capabilities don't overlap. Note: device assignment
2235 * depends on this check to verify that the device is not broken.
2236 * Should never trigger for emulated devices, but it's helpful
2237 * for debugging these. */
2238 for (i = offset; i < offset + size; i++) {
2239 overlapping_cap = pci_find_capability_at_offset(pdev, i);
2240 if (overlapping_cap) {
2241 error_setg(errp, "%s:%02x:%02x.%x "
2242 "Attempt to add PCI capability %x at offset "
2243 "%x overlaps existing capability %x at offset %x",
2244 pci_root_bus_path(pdev), pci_bus_num(pdev->bus),
2245 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2246 cap_id, offset, overlapping_cap, i);
2247 return -EINVAL;
2252 config = pdev->config + offset;
2253 config[PCI_CAP_LIST_ID] = cap_id;
2254 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2255 pdev->config[PCI_CAPABILITY_LIST] = offset;
2256 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2257 memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2258 /* Make capability read-only by default */
2259 memset(pdev->wmask + offset, 0, size);
2260 /* Check capability by default */
2261 memset(pdev->cmask + offset, 0xFF, size);
2262 return offset;
2265 /* Unlink capability from the pci config space. */
2266 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2268 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2269 if (!offset)
2270 return;
2271 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2272 /* Make capability writable again */
2273 memset(pdev->wmask + offset, 0xff, size);
2274 memset(pdev->w1cmask + offset, 0, size);
2275 /* Clear cmask as device-specific registers can't be checked */
2276 memset(pdev->cmask + offset, 0, size);
2277 memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2279 if (!pdev->config[PCI_CAPABILITY_LIST])
2280 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2283 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2285 return pci_find_capability_list(pdev, cap_id, NULL);
2288 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2290 PCIDevice *d = (PCIDevice *)dev;
2291 const pci_class_desc *desc;
2292 char ctxt[64];
2293 PCIIORegion *r;
2294 int i, class;
2296 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2297 desc = pci_class_descriptions;
2298 while (desc->desc && class != desc->class)
2299 desc++;
2300 if (desc->desc) {
2301 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2302 } else {
2303 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2306 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2307 "pci id %04x:%04x (sub %04x:%04x)\n",
2308 indent, "", ctxt, pci_bus_num(d->bus),
2309 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2310 pci_get_word(d->config + PCI_VENDOR_ID),
2311 pci_get_word(d->config + PCI_DEVICE_ID),
2312 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2313 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2314 for (i = 0; i < PCI_NUM_REGIONS; i++) {
2315 r = &d->io_regions[i];
2316 if (!r->size)
2317 continue;
2318 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2319 " [0x%"FMT_PCIBUS"]\n",
2320 indent, "",
2321 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2322 r->addr, r->addr + r->size - 1);
2326 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2328 PCIDevice *d = (PCIDevice *)dev;
2329 const char *name = NULL;
2330 const pci_class_desc *desc = pci_class_descriptions;
2331 int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2333 while (desc->desc &&
2334 (class & ~desc->fw_ign_bits) !=
2335 (desc->class & ~desc->fw_ign_bits)) {
2336 desc++;
2339 if (desc->desc) {
2340 name = desc->fw_name;
2343 if (name) {
2344 pstrcpy(buf, len, name);
2345 } else {
2346 snprintf(buf, len, "pci%04x,%04x",
2347 pci_get_word(d->config + PCI_VENDOR_ID),
2348 pci_get_word(d->config + PCI_DEVICE_ID));
2351 return buf;
2354 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2356 PCIDevice *d = (PCIDevice *)dev;
2357 char path[50], name[33];
2358 int off;
2360 off = snprintf(path, sizeof(path), "%s@%x",
2361 pci_dev_fw_name(dev, name, sizeof name),
2362 PCI_SLOT(d->devfn));
2363 if (PCI_FUNC(d->devfn))
2364 snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2365 return g_strdup(path);
2368 static char *pcibus_get_dev_path(DeviceState *dev)
2370 PCIDevice *d = container_of(dev, PCIDevice, qdev);
2371 PCIDevice *t;
2372 int slot_depth;
2373 /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2374 * 00 is added here to make this format compatible with
2375 * domain:Bus:Slot.Func for systems without nested PCI bridges.
2376 * Slot.Function list specifies the slot and function numbers for all
2377 * devices on the path from root to the specific device. */
2378 const char *root_bus_path;
2379 int root_bus_len;
2380 char slot[] = ":SS.F";
2381 int slot_len = sizeof slot - 1 /* For '\0' */;
2382 int path_len;
2383 char *path, *p;
2384 int s;
2386 root_bus_path = pci_root_bus_path(d);
2387 root_bus_len = strlen(root_bus_path);
2389 /* Calculate # of slots on path between device and root. */;
2390 slot_depth = 0;
2391 for (t = d; t; t = t->bus->parent_dev) {
2392 ++slot_depth;
2395 path_len = root_bus_len + slot_len * slot_depth;
2397 /* Allocate memory, fill in the terminating null byte. */
2398 path = g_malloc(path_len + 1 /* For '\0' */);
2399 path[path_len] = '\0';
2401 memcpy(path, root_bus_path, root_bus_len);
2403 /* Fill in slot numbers. We walk up from device to root, so need to print
2404 * them in the reverse order, last to first. */
2405 p = path + path_len;
2406 for (t = d; t; t = t->bus->parent_dev) {
2407 p -= slot_len;
2408 s = snprintf(slot, sizeof slot, ":%02x.%x",
2409 PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2410 assert(s == slot_len);
2411 memcpy(p, slot, slot_len);
2414 return path;
2417 static int pci_qdev_find_recursive(PCIBus *bus,
2418 const char *id, PCIDevice **pdev)
2420 DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2421 if (!qdev) {
2422 return -ENODEV;
2425 /* roughly check if given qdev is pci device */
2426 if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2427 *pdev = PCI_DEVICE(qdev);
2428 return 0;
2430 return -EINVAL;
2433 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2435 PCIHostState *host_bridge;
2436 int rc = -ENODEV;
2438 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2439 int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2440 if (!tmp) {
2441 rc = 0;
2442 break;
2444 if (tmp != -ENODEV) {
2445 rc = tmp;
2449 return rc;
2452 MemoryRegion *pci_address_space(PCIDevice *dev)
2454 return dev->bus->address_space_mem;
2457 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2459 return dev->bus->address_space_io;
2462 static void pci_device_class_init(ObjectClass *klass, void *data)
2464 DeviceClass *k = DEVICE_CLASS(klass);
2465 PCIDeviceClass *pc = PCI_DEVICE_CLASS(klass);
2467 k->realize = pci_qdev_realize;
2468 k->unrealize = pci_qdev_unrealize;
2469 k->bus_type = TYPE_PCI_BUS;
2470 k->props = pci_props;
2471 pc->realize = pci_default_realize;
2474 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2476 PCIBus *bus = PCI_BUS(dev->bus);
2477 PCIBus *iommu_bus = bus;
2479 while(iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2480 iommu_bus = PCI_BUS(iommu_bus->parent_dev->bus);
2482 if (iommu_bus && iommu_bus->iommu_fn) {
2483 return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, dev->devfn);
2485 return &address_space_memory;
2488 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2490 bus->iommu_fn = fn;
2491 bus->iommu_opaque = opaque;
2494 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2496 Range *range = opaque;
2497 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2498 uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2499 int i;
2501 if (!(cmd & PCI_COMMAND_MEMORY)) {
2502 return;
2505 if (pc->is_bridge) {
2506 pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2507 pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2509 base = MAX(base, 0x1ULL << 32);
2511 if (limit >= base) {
2512 Range pref_range;
2513 pref_range.begin = base;
2514 pref_range.end = limit + 1;
2515 range_extend(range, &pref_range);
2518 for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2519 PCIIORegion *r = &dev->io_regions[i];
2520 Range region_range;
2522 if (!r->size ||
2523 (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2524 !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2525 continue;
2527 region_range.begin = pci_bar_address(dev, i, r->type, r->size);
2528 region_range.end = region_range.begin + r->size;
2530 if (region_range.begin == PCI_BAR_UNMAPPED) {
2531 continue;
2534 region_range.begin = MAX(region_range.begin, 0x1ULL << 32);
2536 if (region_range.end - 1 >= region_range.begin) {
2537 range_extend(range, &region_range);
2542 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2544 range->begin = range->end = 0;
2545 pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2548 static bool pcie_has_upstream_port(PCIDevice *dev)
2550 PCIDevice *parent_dev = pci_bridge_get_device(dev->bus);
2552 /* Device associated with an upstream port.
2553 * As there are several types of these, it's easier to check the
2554 * parent device: upstream ports are always connected to
2555 * root or downstream ports.
2557 return parent_dev &&
2558 pci_is_express(parent_dev) &&
2559 parent_dev->exp.exp_cap &&
2560 (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2561 pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2564 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2566 if(pcie_has_upstream_port(pci_dev)) {
2567 /* With an upstream PCIe port, we only support 1 device at slot 0 */
2568 return pci_dev->bus->devices[0];
2569 } else {
2570 /* Other bus types might support multiple devices at slots 0-31 */
2571 return pci_dev->bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2575 static const TypeInfo pci_device_type_info = {
2576 .name = TYPE_PCI_DEVICE,
2577 .parent = TYPE_DEVICE,
2578 .instance_size = sizeof(PCIDevice),
2579 .abstract = true,
2580 .class_size = sizeof(PCIDeviceClass),
2581 .class_init = pci_device_class_init,
2584 static void pci_register_types(void)
2586 type_register_static(&pci_bus_info);
2587 type_register_static(&pcie_bus_info);
2588 type_register_static(&pci_device_type_info);
2591 type_init(pci_register_types)