hw/pci: made pci_bus_num a PCIBusClass method
[qemu.git] / hw / pci / pci.c
blob2f24f74cf8440870442f9df3eee439876e7caa29
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 "hw/hw.h"
25 #include "hw/pci/pci.h"
26 #include "hw/pci/pci_bridge.h"
27 #include "hw/pci/pci_bus.h"
28 #include "hw/pci/pci_host.h"
29 #include "monitor/monitor.h"
30 #include "net/net.h"
31 #include "sysemu/sysemu.h"
32 #include "hw/loader.h"
33 #include "qemu/range.h"
34 #include "qmp-commands.h"
35 #include "trace.h"
36 #include "hw/pci/msi.h"
37 #include "hw/pci/msix.h"
38 #include "exec/address-spaces.h"
39 #include "hw/hotplug.h"
41 //#define DEBUG_PCI
42 #ifdef DEBUG_PCI
43 # define PCI_DPRINTF(format, ...) printf(format, ## __VA_ARGS__)
44 #else
45 # define PCI_DPRINTF(format, ...) do { } while (0)
46 #endif
48 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
49 static char *pcibus_get_dev_path(DeviceState *dev);
50 static char *pcibus_get_fw_dev_path(DeviceState *dev);
51 static void pcibus_reset(BusState *qbus);
53 static Property pci_props[] = {
54 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
55 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
56 DEFINE_PROP_UINT32("rombar", PCIDevice, rom_bar, 1),
57 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
58 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
59 DEFINE_PROP_BIT("command_serr_enable", PCIDevice, cap_present,
60 QEMU_PCI_CAP_SERR_BITNR, true),
61 DEFINE_PROP_END_OF_LIST()
64 static const VMStateDescription vmstate_pcibus = {
65 .name = "PCIBUS",
66 .version_id = 1,
67 .minimum_version_id = 1,
68 .fields = (VMStateField[]) {
69 VMSTATE_INT32_EQUAL(nirq, PCIBus),
70 VMSTATE_VARRAY_INT32(irq_count, PCIBus,
71 nirq, 0, vmstate_info_int32,
72 int32_t),
73 VMSTATE_END_OF_LIST()
77 static void pci_bus_realize(BusState *qbus, Error **errp)
79 PCIBus *bus = PCI_BUS(qbus);
81 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
84 static void pci_bus_unrealize(BusState *qbus, Error **errp)
86 PCIBus *bus = PCI_BUS(qbus);
88 vmstate_unregister(NULL, &vmstate_pcibus, bus);
91 static bool pcibus_is_root(PCIBus *bus)
93 return !bus->parent_dev;
96 static int pcibus_num(PCIBus *bus)
98 if (pcibus_is_root(bus)) {
99 return 0; /* pci host bridge */
101 return bus->parent_dev->config[PCI_SECONDARY_BUS];
104 static void pci_bus_class_init(ObjectClass *klass, void *data)
106 BusClass *k = BUS_CLASS(klass);
107 PCIBusClass *pbc = PCI_BUS_CLASS(klass);
109 k->print_dev = pcibus_dev_print;
110 k->get_dev_path = pcibus_get_dev_path;
111 k->get_fw_dev_path = pcibus_get_fw_dev_path;
112 k->realize = pci_bus_realize;
113 k->unrealize = pci_bus_unrealize;
114 k->reset = pcibus_reset;
116 pbc->is_root = pcibus_is_root;
117 pbc->bus_num = pcibus_num;
120 static const TypeInfo pci_bus_info = {
121 .name = TYPE_PCI_BUS,
122 .parent = TYPE_BUS,
123 .instance_size = sizeof(PCIBus),
124 .class_size = sizeof(PCIBusClass),
125 .class_init = pci_bus_class_init,
128 static const TypeInfo pcie_bus_info = {
129 .name = TYPE_PCIE_BUS,
130 .parent = TYPE_PCI_BUS,
133 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num);
134 static void pci_update_mappings(PCIDevice *d);
135 static void pci_irq_handler(void *opaque, int irq_num, int level);
136 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
137 static void pci_del_option_rom(PCIDevice *pdev);
139 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
140 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
142 static QLIST_HEAD(, PCIHostState) pci_host_bridges;
144 static int pci_bar(PCIDevice *d, int reg)
146 uint8_t type;
148 if (reg != PCI_ROM_SLOT)
149 return PCI_BASE_ADDRESS_0 + reg * 4;
151 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
152 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
155 static inline int pci_irq_state(PCIDevice *d, int irq_num)
157 return (d->irq_state >> irq_num) & 0x1;
160 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
162 d->irq_state &= ~(0x1 << irq_num);
163 d->irq_state |= level << irq_num;
166 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
168 PCIBus *bus;
169 for (;;) {
170 bus = pci_dev->bus;
171 irq_num = bus->map_irq(pci_dev, irq_num);
172 if (bus->set_irq)
173 break;
174 pci_dev = bus->parent_dev;
176 bus->irq_count[irq_num] += change;
177 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
180 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
182 assert(irq_num >= 0);
183 assert(irq_num < bus->nirq);
184 return !!bus->irq_count[irq_num];
187 /* Update interrupt status bit in config space on interrupt
188 * state change. */
189 static void pci_update_irq_status(PCIDevice *dev)
191 if (dev->irq_state) {
192 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
193 } else {
194 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
198 void pci_device_deassert_intx(PCIDevice *dev)
200 int i;
201 for (i = 0; i < PCI_NUM_PINS; ++i) {
202 pci_irq_handler(dev, i, 0);
206 static void pci_do_device_reset(PCIDevice *dev)
208 int r;
210 pci_device_deassert_intx(dev);
211 assert(dev->irq_state == 0);
213 /* Clear all writable bits */
214 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
215 pci_get_word(dev->wmask + PCI_COMMAND) |
216 pci_get_word(dev->w1cmask + PCI_COMMAND));
217 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
218 pci_get_word(dev->wmask + PCI_STATUS) |
219 pci_get_word(dev->w1cmask + PCI_STATUS));
220 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
221 dev->config[PCI_INTERRUPT_LINE] = 0x0;
222 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
223 PCIIORegion *region = &dev->io_regions[r];
224 if (!region->size) {
225 continue;
228 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
229 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
230 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
231 } else {
232 pci_set_long(dev->config + pci_bar(dev, r), region->type);
235 pci_update_mappings(dev);
237 msi_reset(dev);
238 msix_reset(dev);
242 * This function is called on #RST and FLR.
243 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
245 void pci_device_reset(PCIDevice *dev)
247 qdev_reset_all(&dev->qdev);
248 pci_do_device_reset(dev);
252 * Trigger pci bus reset under a given bus.
253 * Called via qbus_reset_all on RST# assert, after the devices
254 * have been reset qdev_reset_all-ed already.
256 static void pcibus_reset(BusState *qbus)
258 PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
259 int i;
261 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
262 if (bus->devices[i]) {
263 pci_do_device_reset(bus->devices[i]);
267 for (i = 0; i < bus->nirq; i++) {
268 assert(bus->irq_count[i] == 0);
272 static void pci_host_bus_register(PCIBus *bus, DeviceState *parent)
274 PCIHostState *host_bridge = PCI_HOST_BRIDGE(parent);
276 QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
279 PCIBus *pci_find_primary_bus(void)
281 PCIBus *primary_bus = NULL;
282 PCIHostState *host;
284 QLIST_FOREACH(host, &pci_host_bridges, next) {
285 if (primary_bus) {
286 /* We have multiple root buses, refuse to select a primary */
287 return NULL;
289 primary_bus = host->bus;
292 return primary_bus;
295 PCIBus *pci_device_root_bus(const PCIDevice *d)
297 PCIBus *bus = d->bus;
299 while (!pci_bus_is_root(bus)) {
300 d = bus->parent_dev;
301 assert(d != NULL);
303 bus = d->bus;
306 return bus;
309 const char *pci_root_bus_path(PCIDevice *dev)
311 PCIBus *rootbus = pci_device_root_bus(dev);
312 PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
313 PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
315 assert(host_bridge->bus == rootbus);
317 if (hc->root_bus_path) {
318 return (*hc->root_bus_path)(host_bridge, rootbus);
321 return rootbus->qbus.name;
324 static void pci_bus_init(PCIBus *bus, DeviceState *parent,
325 const char *name,
326 MemoryRegion *address_space_mem,
327 MemoryRegion *address_space_io,
328 uint8_t devfn_min)
330 assert(PCI_FUNC(devfn_min) == 0);
331 bus->devfn_min = devfn_min;
332 bus->address_space_mem = address_space_mem;
333 bus->address_space_io = address_space_io;
335 /* host bridge */
336 QLIST_INIT(&bus->child);
338 pci_host_bus_register(bus, parent);
341 bool pci_bus_is_express(PCIBus *bus)
343 return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
346 bool pci_bus_is_root(PCIBus *bus)
348 return PCI_BUS_GET_CLASS(bus)->is_root(bus);
351 void pci_bus_new_inplace(PCIBus *bus, size_t bus_size, DeviceState *parent,
352 const char *name,
353 MemoryRegion *address_space_mem,
354 MemoryRegion *address_space_io,
355 uint8_t devfn_min, const char *typename)
357 qbus_create_inplace(bus, bus_size, typename, parent, name);
358 pci_bus_init(bus, parent, name, address_space_mem,
359 address_space_io, devfn_min);
362 PCIBus *pci_bus_new(DeviceState *parent, const char *name,
363 MemoryRegion *address_space_mem,
364 MemoryRegion *address_space_io,
365 uint8_t devfn_min, const char *typename)
367 PCIBus *bus;
369 bus = PCI_BUS(qbus_create(typename, parent, name));
370 pci_bus_init(bus, parent, name, address_space_mem,
371 address_space_io, devfn_min);
372 return bus;
375 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
376 void *irq_opaque, int nirq)
378 bus->set_irq = set_irq;
379 bus->map_irq = map_irq;
380 bus->irq_opaque = irq_opaque;
381 bus->nirq = nirq;
382 bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
385 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
386 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
387 void *irq_opaque,
388 MemoryRegion *address_space_mem,
389 MemoryRegion *address_space_io,
390 uint8_t devfn_min, int nirq, const char *typename)
392 PCIBus *bus;
394 bus = pci_bus_new(parent, name, address_space_mem,
395 address_space_io, devfn_min, typename);
396 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
397 return bus;
400 int pci_bus_num(PCIBus *s)
402 return PCI_BUS_GET_CLASS(s)->bus_num(s);
405 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
407 PCIDevice *s = container_of(pv, PCIDevice, config);
408 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(s);
409 uint8_t *config;
410 int i;
412 assert(size == pci_config_size(s));
413 config = g_malloc(size);
415 qemu_get_buffer(f, config, size);
416 for (i = 0; i < size; ++i) {
417 if ((config[i] ^ s->config[i]) &
418 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
419 g_free(config);
420 return -EINVAL;
423 memcpy(s->config, config, size);
425 pci_update_mappings(s);
426 if (pc->is_bridge) {
427 PCIBridge *b = PCI_BRIDGE(s);
428 pci_bridge_update_mappings(b);
431 memory_region_set_enabled(&s->bus_master_enable_region,
432 pci_get_word(s->config + PCI_COMMAND)
433 & PCI_COMMAND_MASTER);
435 g_free(config);
436 return 0;
439 /* just put buffer */
440 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
442 const uint8_t **v = pv;
443 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
444 qemu_put_buffer(f, *v, size);
447 static VMStateInfo vmstate_info_pci_config = {
448 .name = "pci config",
449 .get = get_pci_config_device,
450 .put = put_pci_config_device,
453 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
455 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
456 uint32_t irq_state[PCI_NUM_PINS];
457 int i;
458 for (i = 0; i < PCI_NUM_PINS; ++i) {
459 irq_state[i] = qemu_get_be32(f);
460 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
461 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
462 irq_state[i]);
463 return -EINVAL;
467 for (i = 0; i < PCI_NUM_PINS; ++i) {
468 pci_set_irq_state(s, i, irq_state[i]);
471 return 0;
474 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
476 int i;
477 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
479 for (i = 0; i < PCI_NUM_PINS; ++i) {
480 qemu_put_be32(f, pci_irq_state(s, i));
484 static VMStateInfo vmstate_info_pci_irq_state = {
485 .name = "pci irq state",
486 .get = get_pci_irq_state,
487 .put = put_pci_irq_state,
490 const VMStateDescription vmstate_pci_device = {
491 .name = "PCIDevice",
492 .version_id = 2,
493 .minimum_version_id = 1,
494 .fields = (VMStateField[]) {
495 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
496 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
497 vmstate_info_pci_config,
498 PCI_CONFIG_SPACE_SIZE),
499 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
500 vmstate_info_pci_irq_state,
501 PCI_NUM_PINS * sizeof(int32_t)),
502 VMSTATE_END_OF_LIST()
506 const VMStateDescription vmstate_pcie_device = {
507 .name = "PCIEDevice",
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 PCIE_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 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
524 return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
527 void pci_device_save(PCIDevice *s, QEMUFile *f)
529 /* Clear interrupt status bit: it is implicit
530 * in irq_state which we are saving.
531 * This makes us compatible with old devices
532 * which never set or clear this bit. */
533 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
534 vmstate_save_state(f, pci_get_vmstate(s), s, NULL);
535 /* Restore the interrupt status bit. */
536 pci_update_irq_status(s);
539 int pci_device_load(PCIDevice *s, QEMUFile *f)
541 int ret;
542 ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
543 /* Restore the interrupt status bit. */
544 pci_update_irq_status(s);
545 return ret;
548 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
550 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
551 pci_default_sub_vendor_id);
552 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
553 pci_default_sub_device_id);
557 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
558 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
560 static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
561 unsigned int *slotp, unsigned int *funcp)
563 const char *p;
564 char *e;
565 unsigned long val;
566 unsigned long dom = 0, bus = 0;
567 unsigned int slot = 0;
568 unsigned int func = 0;
570 p = addr;
571 val = strtoul(p, &e, 16);
572 if (e == p)
573 return -1;
574 if (*e == ':') {
575 bus = val;
576 p = e + 1;
577 val = strtoul(p, &e, 16);
578 if (e == p)
579 return -1;
580 if (*e == ':') {
581 dom = bus;
582 bus = val;
583 p = e + 1;
584 val = strtoul(p, &e, 16);
585 if (e == p)
586 return -1;
590 slot = val;
592 if (funcp != NULL) {
593 if (*e != '.')
594 return -1;
596 p = e + 1;
597 val = strtoul(p, &e, 16);
598 if (e == p)
599 return -1;
601 func = val;
604 /* if funcp == NULL func is 0 */
605 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
606 return -1;
608 if (*e)
609 return -1;
611 *domp = dom;
612 *busp = bus;
613 *slotp = slot;
614 if (funcp != NULL)
615 *funcp = func;
616 return 0;
619 static PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root,
620 const char *devaddr)
622 int dom, bus;
623 unsigned slot;
625 if (!root) {
626 fprintf(stderr, "No primary PCI bus\n");
627 return NULL;
630 assert(!root->parent_dev);
632 if (!devaddr) {
633 *devfnp = -1;
634 return pci_find_bus_nr(root, 0);
637 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
638 return NULL;
641 if (dom != 0) {
642 fprintf(stderr, "No support for non-zero PCI domains\n");
643 return NULL;
646 *devfnp = PCI_DEVFN(slot, 0);
647 return pci_find_bus_nr(root, bus);
650 static void pci_init_cmask(PCIDevice *dev)
652 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
653 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
654 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
655 dev->cmask[PCI_REVISION_ID] = 0xff;
656 dev->cmask[PCI_CLASS_PROG] = 0xff;
657 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
658 dev->cmask[PCI_HEADER_TYPE] = 0xff;
659 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
662 static void pci_init_wmask(PCIDevice *dev)
664 int config_size = pci_config_size(dev);
666 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
667 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
668 pci_set_word(dev->wmask + PCI_COMMAND,
669 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
670 PCI_COMMAND_INTX_DISABLE);
671 if (dev->cap_present & QEMU_PCI_CAP_SERR) {
672 pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
675 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
676 config_size - PCI_CONFIG_HEADER_SIZE);
679 static void pci_init_w1cmask(PCIDevice *dev)
682 * Note: It's okay to set w1cmask even for readonly bits as
683 * long as their value is hardwired to 0.
685 pci_set_word(dev->w1cmask + PCI_STATUS,
686 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
687 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
688 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
691 static void pci_init_mask_bridge(PCIDevice *d)
693 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
694 PCI_SEC_LETENCY_TIMER */
695 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
697 /* base and limit */
698 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
699 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
700 pci_set_word(d->wmask + PCI_MEMORY_BASE,
701 PCI_MEMORY_RANGE_MASK & 0xffff);
702 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
703 PCI_MEMORY_RANGE_MASK & 0xffff);
704 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
705 PCI_PREF_RANGE_MASK & 0xffff);
706 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
707 PCI_PREF_RANGE_MASK & 0xffff);
709 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
710 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
712 /* Supported memory and i/o types */
713 d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
714 d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
715 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
716 PCI_PREF_RANGE_TYPE_64);
717 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
718 PCI_PREF_RANGE_TYPE_64);
721 * TODO: Bridges default to 10-bit VGA decoding but we currently only
722 * implement 16-bit decoding (no alias support).
724 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
725 PCI_BRIDGE_CTL_PARITY |
726 PCI_BRIDGE_CTL_SERR |
727 PCI_BRIDGE_CTL_ISA |
728 PCI_BRIDGE_CTL_VGA |
729 PCI_BRIDGE_CTL_VGA_16BIT |
730 PCI_BRIDGE_CTL_MASTER_ABORT |
731 PCI_BRIDGE_CTL_BUS_RESET |
732 PCI_BRIDGE_CTL_FAST_BACK |
733 PCI_BRIDGE_CTL_DISCARD |
734 PCI_BRIDGE_CTL_SEC_DISCARD |
735 PCI_BRIDGE_CTL_DISCARD_SERR);
736 /* Below does not do anything as we never set this bit, put here for
737 * completeness. */
738 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
739 PCI_BRIDGE_CTL_DISCARD_STATUS);
740 d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
741 d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
742 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
743 PCI_PREF_RANGE_TYPE_MASK);
744 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
745 PCI_PREF_RANGE_TYPE_MASK);
748 static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
750 uint8_t slot = PCI_SLOT(dev->devfn);
751 uint8_t func;
753 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
754 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
758 * multifunction bit is interpreted in two ways as follows.
759 * - all functions must set the bit to 1.
760 * Example: Intel X53
761 * - function 0 must set the bit, but the rest function (> 0)
762 * is allowed to leave the bit to 0.
763 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
765 * So OS (at least Linux) checks the bit of only function 0,
766 * and doesn't see the bit of function > 0.
768 * The below check allows both interpretation.
770 if (PCI_FUNC(dev->devfn)) {
771 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
772 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
773 /* function 0 should set multifunction bit */
774 error_setg(errp, "PCI: single function device can't be populated "
775 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
776 return;
778 return;
781 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
782 return;
784 /* function 0 indicates single function, so function > 0 must be NULL */
785 for (func = 1; func < PCI_FUNC_MAX; ++func) {
786 if (bus->devices[PCI_DEVFN(slot, func)]) {
787 error_setg(errp, "PCI: %x.0 indicates single function, "
788 "but %x.%x is already populated.",
789 slot, slot, func);
790 return;
795 static void pci_config_alloc(PCIDevice *pci_dev)
797 int config_size = pci_config_size(pci_dev);
799 pci_dev->config = g_malloc0(config_size);
800 pci_dev->cmask = g_malloc0(config_size);
801 pci_dev->wmask = g_malloc0(config_size);
802 pci_dev->w1cmask = g_malloc0(config_size);
803 pci_dev->used = g_malloc0(config_size);
806 static void pci_config_free(PCIDevice *pci_dev)
808 g_free(pci_dev->config);
809 g_free(pci_dev->cmask);
810 g_free(pci_dev->wmask);
811 g_free(pci_dev->w1cmask);
812 g_free(pci_dev->used);
815 static void do_pci_unregister_device(PCIDevice *pci_dev)
817 pci_dev->bus->devices[pci_dev->devfn] = NULL;
818 pci_config_free(pci_dev);
820 address_space_destroy(&pci_dev->bus_master_as);
823 /* -1 for devfn means auto assign */
824 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
825 const char *name, int devfn,
826 Error **errp)
828 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
829 PCIConfigReadFunc *config_read = pc->config_read;
830 PCIConfigWriteFunc *config_write = pc->config_write;
831 Error *local_err = NULL;
832 AddressSpace *dma_as;
834 if (devfn < 0) {
835 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
836 devfn += PCI_FUNC_MAX) {
837 if (!bus->devices[devfn])
838 goto found;
840 error_setg(errp, "PCI: no slot/function available for %s, all in use",
841 name);
842 return NULL;
843 found: ;
844 } else if (bus->devices[devfn]) {
845 error_setg(errp, "PCI: slot %d function %d not available for %s,"
846 " in use by %s",
847 PCI_SLOT(devfn), PCI_FUNC(devfn), name,
848 bus->devices[devfn]->name);
849 return NULL;
852 pci_dev->bus = bus;
853 pci_dev->devfn = devfn;
854 dma_as = pci_device_iommu_address_space(pci_dev);
856 memory_region_init_alias(&pci_dev->bus_master_enable_region,
857 OBJECT(pci_dev), "bus master",
858 dma_as->root, 0, memory_region_size(dma_as->root));
859 memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
860 address_space_init(&pci_dev->bus_master_as, &pci_dev->bus_master_enable_region,
861 name);
863 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
864 pci_dev->irq_state = 0;
865 pci_config_alloc(pci_dev);
867 pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
868 pci_config_set_device_id(pci_dev->config, pc->device_id);
869 pci_config_set_revision(pci_dev->config, pc->revision);
870 pci_config_set_class(pci_dev->config, pc->class_id);
872 if (!pc->is_bridge) {
873 if (pc->subsystem_vendor_id || pc->subsystem_id) {
874 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
875 pc->subsystem_vendor_id);
876 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
877 pc->subsystem_id);
878 } else {
879 pci_set_default_subsystem_id(pci_dev);
881 } else {
882 /* subsystem_vendor_id/subsystem_id are only for header type 0 */
883 assert(!pc->subsystem_vendor_id);
884 assert(!pc->subsystem_id);
886 pci_init_cmask(pci_dev);
887 pci_init_wmask(pci_dev);
888 pci_init_w1cmask(pci_dev);
889 if (pc->is_bridge) {
890 pci_init_mask_bridge(pci_dev);
892 pci_init_multifunction(bus, pci_dev, &local_err);
893 if (local_err) {
894 error_propagate(errp, local_err);
895 do_pci_unregister_device(pci_dev);
896 return NULL;
899 if (!config_read)
900 config_read = pci_default_read_config;
901 if (!config_write)
902 config_write = pci_default_write_config;
903 pci_dev->config_read = config_read;
904 pci_dev->config_write = config_write;
905 bus->devices[devfn] = pci_dev;
906 pci_dev->version_id = 2; /* Current pci device vmstate version */
907 return pci_dev;
910 static void pci_unregister_io_regions(PCIDevice *pci_dev)
912 PCIIORegion *r;
913 int i;
915 for(i = 0; i < PCI_NUM_REGIONS; i++) {
916 r = &pci_dev->io_regions[i];
917 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
918 continue;
919 memory_region_del_subregion(r->address_space, r->memory);
922 pci_unregister_vga(pci_dev);
925 static void pci_qdev_unrealize(DeviceState *dev, Error **errp)
927 PCIDevice *pci_dev = PCI_DEVICE(dev);
928 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
930 pci_unregister_io_regions(pci_dev);
931 pci_del_option_rom(pci_dev);
933 if (pc->exit) {
934 pc->exit(pci_dev);
937 do_pci_unregister_device(pci_dev);
940 void pci_register_bar(PCIDevice *pci_dev, int region_num,
941 uint8_t type, MemoryRegion *memory)
943 PCIIORegion *r;
944 uint32_t addr;
945 uint64_t wmask;
946 pcibus_t size = memory_region_size(memory);
948 assert(region_num >= 0);
949 assert(region_num < PCI_NUM_REGIONS);
950 if (size & (size-1)) {
951 fprintf(stderr, "ERROR: PCI region size must be pow2 "
952 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
953 exit(1);
956 r = &pci_dev->io_regions[region_num];
957 r->addr = PCI_BAR_UNMAPPED;
958 r->size = size;
959 r->type = type;
960 r->memory = NULL;
962 wmask = ~(size - 1);
963 addr = pci_bar(pci_dev, region_num);
964 if (region_num == PCI_ROM_SLOT) {
965 /* ROM enable bit is writable */
966 wmask |= PCI_ROM_ADDRESS_ENABLE;
968 pci_set_long(pci_dev->config + addr, type);
969 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
970 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
971 pci_set_quad(pci_dev->wmask + addr, wmask);
972 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
973 } else {
974 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
975 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
977 pci_dev->io_regions[region_num].memory = memory;
978 pci_dev->io_regions[region_num].address_space
979 = type & PCI_BASE_ADDRESS_SPACE_IO
980 ? pci_dev->bus->address_space_io
981 : pci_dev->bus->address_space_mem;
984 static void pci_update_vga(PCIDevice *pci_dev)
986 uint16_t cmd;
988 if (!pci_dev->has_vga) {
989 return;
992 cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
994 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
995 cmd & PCI_COMMAND_MEMORY);
996 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
997 cmd & PCI_COMMAND_IO);
998 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
999 cmd & PCI_COMMAND_IO);
1002 void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1003 MemoryRegion *io_lo, MemoryRegion *io_hi)
1005 assert(!pci_dev->has_vga);
1007 assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1008 pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1009 memory_region_add_subregion_overlap(pci_dev->bus->address_space_mem,
1010 QEMU_PCI_VGA_MEM_BASE, mem, 1);
1012 assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1013 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1014 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1015 QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1017 assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1018 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1019 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1020 QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1021 pci_dev->has_vga = true;
1023 pci_update_vga(pci_dev);
1026 void pci_unregister_vga(PCIDevice *pci_dev)
1028 if (!pci_dev->has_vga) {
1029 return;
1032 memory_region_del_subregion(pci_dev->bus->address_space_mem,
1033 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1034 memory_region_del_subregion(pci_dev->bus->address_space_io,
1035 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1036 memory_region_del_subregion(pci_dev->bus->address_space_io,
1037 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1038 pci_dev->has_vga = false;
1041 pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1043 return pci_dev->io_regions[region_num].addr;
1046 static pcibus_t pci_bar_address(PCIDevice *d,
1047 int reg, uint8_t type, pcibus_t size)
1049 pcibus_t new_addr, last_addr;
1050 int bar = pci_bar(d, reg);
1051 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1053 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1054 if (!(cmd & PCI_COMMAND_IO)) {
1055 return PCI_BAR_UNMAPPED;
1057 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
1058 last_addr = new_addr + size - 1;
1059 /* Check if 32 bit BAR wraps around explicitly.
1060 * TODO: make priorities correct and remove this work around.
1062 if (last_addr <= new_addr || new_addr == 0 || last_addr >= UINT32_MAX) {
1063 return PCI_BAR_UNMAPPED;
1065 return new_addr;
1068 if (!(cmd & PCI_COMMAND_MEMORY)) {
1069 return PCI_BAR_UNMAPPED;
1071 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1072 new_addr = pci_get_quad(d->config + bar);
1073 } else {
1074 new_addr = pci_get_long(d->config + bar);
1076 /* the ROM slot has a specific enable bit */
1077 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1078 return PCI_BAR_UNMAPPED;
1080 new_addr &= ~(size - 1);
1081 last_addr = new_addr + size - 1;
1082 /* NOTE: we do not support wrapping */
1083 /* XXX: as we cannot support really dynamic
1084 mappings, we handle specific values as invalid
1085 mappings. */
1086 if (last_addr <= new_addr || new_addr == 0 ||
1087 last_addr == PCI_BAR_UNMAPPED) {
1088 return PCI_BAR_UNMAPPED;
1091 /* Now pcibus_t is 64bit.
1092 * Check if 32 bit BAR wraps around explicitly.
1093 * Without this, PC ide doesn't work well.
1094 * TODO: remove this work around.
1096 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1097 return PCI_BAR_UNMAPPED;
1101 * OS is allowed to set BAR beyond its addressable
1102 * bits. For example, 32 bit OS can set 64bit bar
1103 * to >4G. Check it. TODO: we might need to support
1104 * it in the future for e.g. PAE.
1106 if (last_addr >= HWADDR_MAX) {
1107 return PCI_BAR_UNMAPPED;
1110 return new_addr;
1113 static void pci_update_mappings(PCIDevice *d)
1115 PCIIORegion *r;
1116 int i;
1117 pcibus_t new_addr;
1119 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1120 r = &d->io_regions[i];
1122 /* this region isn't registered */
1123 if (!r->size)
1124 continue;
1126 new_addr = pci_bar_address(d, i, r->type, r->size);
1128 /* This bar isn't changed */
1129 if (new_addr == r->addr)
1130 continue;
1132 /* now do the real mapping */
1133 if (r->addr != PCI_BAR_UNMAPPED) {
1134 trace_pci_update_mappings_del(d, pci_bus_num(d->bus),
1135 PCI_FUNC(d->devfn),
1136 PCI_SLOT(d->devfn),
1137 i, r->addr, r->size);
1138 memory_region_del_subregion(r->address_space, r->memory);
1140 r->addr = new_addr;
1141 if (r->addr != PCI_BAR_UNMAPPED) {
1142 trace_pci_update_mappings_add(d, pci_bus_num(d->bus),
1143 PCI_FUNC(d->devfn),
1144 PCI_SLOT(d->devfn),
1145 i, r->addr, r->size);
1146 memory_region_add_subregion_overlap(r->address_space,
1147 r->addr, r->memory, 1);
1151 pci_update_vga(d);
1154 static inline int pci_irq_disabled(PCIDevice *d)
1156 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1159 /* Called after interrupt disabled field update in config space,
1160 * assert/deassert interrupts if necessary.
1161 * Gets original interrupt disable bit value (before update). */
1162 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1164 int i, disabled = pci_irq_disabled(d);
1165 if (disabled == was_irq_disabled)
1166 return;
1167 for (i = 0; i < PCI_NUM_PINS; ++i) {
1168 int state = pci_irq_state(d, i);
1169 pci_change_irq_level(d, i, disabled ? -state : state);
1173 uint32_t pci_default_read_config(PCIDevice *d,
1174 uint32_t address, int len)
1176 uint32_t val = 0;
1178 memcpy(&val, d->config + address, len);
1179 return le32_to_cpu(val);
1182 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1184 int i, was_irq_disabled = pci_irq_disabled(d);
1185 uint32_t val = val_in;
1187 for (i = 0; i < l; val >>= 8, ++i) {
1188 uint8_t wmask = d->wmask[addr + i];
1189 uint8_t w1cmask = d->w1cmask[addr + i];
1190 assert(!(wmask & w1cmask));
1191 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1192 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1194 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1195 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1196 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1197 range_covers_byte(addr, l, PCI_COMMAND))
1198 pci_update_mappings(d);
1200 if (range_covers_byte(addr, l, PCI_COMMAND)) {
1201 pci_update_irq_disabled(d, was_irq_disabled);
1202 memory_region_set_enabled(&d->bus_master_enable_region,
1203 pci_get_word(d->config + PCI_COMMAND)
1204 & PCI_COMMAND_MASTER);
1207 msi_write_config(d, addr, val_in, l);
1208 msix_write_config(d, addr, val_in, l);
1211 /***********************************************************/
1212 /* generic PCI irq support */
1214 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1215 static void pci_irq_handler(void *opaque, int irq_num, int level)
1217 PCIDevice *pci_dev = opaque;
1218 int change;
1220 change = level - pci_irq_state(pci_dev, irq_num);
1221 if (!change)
1222 return;
1224 pci_set_irq_state(pci_dev, irq_num, level);
1225 pci_update_irq_status(pci_dev);
1226 if (pci_irq_disabled(pci_dev))
1227 return;
1228 pci_change_irq_level(pci_dev, irq_num, change);
1231 static inline int pci_intx(PCIDevice *pci_dev)
1233 return pci_get_byte(pci_dev->config + PCI_INTERRUPT_PIN) - 1;
1236 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1238 int intx = pci_intx(pci_dev);
1240 return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1243 void pci_set_irq(PCIDevice *pci_dev, int level)
1245 int intx = pci_intx(pci_dev);
1246 pci_irq_handler(pci_dev, intx, level);
1249 /* Special hooks used by device assignment */
1250 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1252 assert(pci_bus_is_root(bus));
1253 bus->route_intx_to_irq = route_intx_to_irq;
1256 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1258 PCIBus *bus;
1260 do {
1261 bus = dev->bus;
1262 pin = bus->map_irq(dev, pin);
1263 dev = bus->parent_dev;
1264 } while (dev);
1266 if (!bus->route_intx_to_irq) {
1267 error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1268 object_get_typename(OBJECT(bus->qbus.parent)));
1269 return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1272 return bus->route_intx_to_irq(bus->irq_opaque, pin);
1275 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1277 return old->mode != new->mode || old->irq != new->irq;
1280 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1282 PCIDevice *dev;
1283 PCIBus *sec;
1284 int i;
1286 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1287 dev = bus->devices[i];
1288 if (dev && dev->intx_routing_notifier) {
1289 dev->intx_routing_notifier(dev);
1293 QLIST_FOREACH(sec, &bus->child, sibling) {
1294 pci_bus_fire_intx_routing_notifier(sec);
1298 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1299 PCIINTxRoutingNotifier notifier)
1301 dev->intx_routing_notifier = notifier;
1305 * PCI-to-PCI bridge specification
1306 * 9.1: Interrupt routing. Table 9-1
1308 * the PCI Express Base Specification, Revision 2.1
1309 * 2.2.8.1: INTx interrutp signaling - Rules
1310 * the Implementation Note
1311 * Table 2-20
1314 * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1315 * 0-origin unlike PCI interrupt pin register.
1317 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1319 return (pin + PCI_SLOT(pci_dev->devfn)) % PCI_NUM_PINS;
1322 /***********************************************************/
1323 /* monitor info on PCI */
1325 typedef struct {
1326 uint16_t class;
1327 const char *desc;
1328 const char *fw_name;
1329 uint16_t fw_ign_bits;
1330 } pci_class_desc;
1332 static const pci_class_desc pci_class_descriptions[] =
1334 { 0x0001, "VGA controller", "display"},
1335 { 0x0100, "SCSI controller", "scsi"},
1336 { 0x0101, "IDE controller", "ide"},
1337 { 0x0102, "Floppy controller", "fdc"},
1338 { 0x0103, "IPI controller", "ipi"},
1339 { 0x0104, "RAID controller", "raid"},
1340 { 0x0106, "SATA controller"},
1341 { 0x0107, "SAS controller"},
1342 { 0x0180, "Storage controller"},
1343 { 0x0200, "Ethernet controller", "ethernet"},
1344 { 0x0201, "Token Ring controller", "token-ring"},
1345 { 0x0202, "FDDI controller", "fddi"},
1346 { 0x0203, "ATM controller", "atm"},
1347 { 0x0280, "Network controller"},
1348 { 0x0300, "VGA controller", "display", 0x00ff},
1349 { 0x0301, "XGA controller"},
1350 { 0x0302, "3D controller"},
1351 { 0x0380, "Display controller"},
1352 { 0x0400, "Video controller", "video"},
1353 { 0x0401, "Audio controller", "sound"},
1354 { 0x0402, "Phone"},
1355 { 0x0403, "Audio controller", "sound"},
1356 { 0x0480, "Multimedia controller"},
1357 { 0x0500, "RAM controller", "memory"},
1358 { 0x0501, "Flash controller", "flash"},
1359 { 0x0580, "Memory controller"},
1360 { 0x0600, "Host bridge", "host"},
1361 { 0x0601, "ISA bridge", "isa"},
1362 { 0x0602, "EISA bridge", "eisa"},
1363 { 0x0603, "MC bridge", "mca"},
1364 { 0x0604, "PCI bridge", "pci-bridge"},
1365 { 0x0605, "PCMCIA bridge", "pcmcia"},
1366 { 0x0606, "NUBUS bridge", "nubus"},
1367 { 0x0607, "CARDBUS bridge", "cardbus"},
1368 { 0x0608, "RACEWAY bridge"},
1369 { 0x0680, "Bridge"},
1370 { 0x0700, "Serial port", "serial"},
1371 { 0x0701, "Parallel port", "parallel"},
1372 { 0x0800, "Interrupt controller", "interrupt-controller"},
1373 { 0x0801, "DMA controller", "dma-controller"},
1374 { 0x0802, "Timer", "timer"},
1375 { 0x0803, "RTC", "rtc"},
1376 { 0x0900, "Keyboard", "keyboard"},
1377 { 0x0901, "Pen", "pen"},
1378 { 0x0902, "Mouse", "mouse"},
1379 { 0x0A00, "Dock station", "dock", 0x00ff},
1380 { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1381 { 0x0c00, "Fireware contorller", "fireware"},
1382 { 0x0c01, "Access bus controller", "access-bus"},
1383 { 0x0c02, "SSA controller", "ssa"},
1384 { 0x0c03, "USB controller", "usb"},
1385 { 0x0c04, "Fibre channel controller", "fibre-channel"},
1386 { 0x0c05, "SMBus"},
1387 { 0, NULL}
1390 static void pci_for_each_device_under_bus(PCIBus *bus,
1391 void (*fn)(PCIBus *b, PCIDevice *d,
1392 void *opaque),
1393 void *opaque)
1395 PCIDevice *d;
1396 int devfn;
1398 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1399 d = bus->devices[devfn];
1400 if (d) {
1401 fn(bus, d, opaque);
1406 void pci_for_each_device(PCIBus *bus, int bus_num,
1407 void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
1408 void *opaque)
1410 bus = pci_find_bus_nr(bus, bus_num);
1412 if (bus) {
1413 pci_for_each_device_under_bus(bus, fn, opaque);
1417 static const pci_class_desc *get_class_desc(int class)
1419 const pci_class_desc *desc;
1421 desc = pci_class_descriptions;
1422 while (desc->desc && class != desc->class) {
1423 desc++;
1426 return desc;
1429 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num);
1431 static PciMemoryRegionList *qmp_query_pci_regions(const PCIDevice *dev)
1433 PciMemoryRegionList *head = NULL, *cur_item = NULL;
1434 int i;
1436 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1437 const PCIIORegion *r = &dev->io_regions[i];
1438 PciMemoryRegionList *region;
1440 if (!r->size) {
1441 continue;
1444 region = g_malloc0(sizeof(*region));
1445 region->value = g_malloc0(sizeof(*region->value));
1447 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1448 region->value->type = g_strdup("io");
1449 } else {
1450 region->value->type = g_strdup("memory");
1451 region->value->has_prefetch = true;
1452 region->value->prefetch = !!(r->type & PCI_BASE_ADDRESS_MEM_PREFETCH);
1453 region->value->has_mem_type_64 = true;
1454 region->value->mem_type_64 = !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
1457 region->value->bar = i;
1458 region->value->address = r->addr;
1459 region->value->size = r->size;
1461 /* XXX: waiting for the qapi to support GSList */
1462 if (!cur_item) {
1463 head = cur_item = region;
1464 } else {
1465 cur_item->next = region;
1466 cur_item = region;
1470 return head;
1473 static PciBridgeInfo *qmp_query_pci_bridge(PCIDevice *dev, PCIBus *bus,
1474 int bus_num)
1476 PciBridgeInfo *info;
1477 PciMemoryRange *range;
1479 info = g_new0(PciBridgeInfo, 1);
1481 info->bus = g_new0(PciBusInfo, 1);
1482 info->bus->number = dev->config[PCI_PRIMARY_BUS];
1483 info->bus->secondary = dev->config[PCI_SECONDARY_BUS];
1484 info->bus->subordinate = dev->config[PCI_SUBORDINATE_BUS];
1486 range = info->bus->io_range = g_new0(PciMemoryRange, 1);
1487 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
1488 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
1490 range = info->bus->memory_range = g_new0(PciMemoryRange, 1);
1491 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1492 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1494 range = info->bus->prefetchable_range = g_new0(PciMemoryRange, 1);
1495 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1496 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1498 if (dev->config[PCI_SECONDARY_BUS] != 0) {
1499 PCIBus *child_bus = pci_find_bus_nr(bus, dev->config[PCI_SECONDARY_BUS]);
1500 if (child_bus) {
1501 info->has_devices = true;
1502 info->devices = qmp_query_pci_devices(child_bus, dev->config[PCI_SECONDARY_BUS]);
1506 return info;
1509 static PciDeviceInfo *qmp_query_pci_device(PCIDevice *dev, PCIBus *bus,
1510 int bus_num)
1512 const pci_class_desc *desc;
1513 PciDeviceInfo *info;
1514 uint8_t type;
1515 int class;
1517 info = g_new0(PciDeviceInfo, 1);
1518 info->bus = bus_num;
1519 info->slot = PCI_SLOT(dev->devfn);
1520 info->function = PCI_FUNC(dev->devfn);
1522 info->class_info = g_new0(PciDeviceClass, 1);
1523 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1524 info->class_info->q_class = class;
1525 desc = get_class_desc(class);
1526 if (desc->desc) {
1527 info->class_info->has_desc = true;
1528 info->class_info->desc = g_strdup(desc->desc);
1531 info->id = g_new0(PciDeviceId, 1);
1532 info->id->vendor = pci_get_word(dev->config + PCI_VENDOR_ID);
1533 info->id->device = pci_get_word(dev->config + PCI_DEVICE_ID);
1534 info->regions = qmp_query_pci_regions(dev);
1535 info->qdev_id = g_strdup(dev->qdev.id ? dev->qdev.id : "");
1537 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1538 info->has_irq = true;
1539 info->irq = dev->config[PCI_INTERRUPT_LINE];
1542 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1543 if (type == PCI_HEADER_TYPE_BRIDGE) {
1544 info->has_pci_bridge = true;
1545 info->pci_bridge = qmp_query_pci_bridge(dev, bus, bus_num);
1548 return info;
1551 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num)
1553 PciDeviceInfoList *info, *head = NULL, *cur_item = NULL;
1554 PCIDevice *dev;
1555 int devfn;
1557 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1558 dev = bus->devices[devfn];
1559 if (dev) {
1560 info = g_malloc0(sizeof(*info));
1561 info->value = qmp_query_pci_device(dev, bus, bus_num);
1563 /* XXX: waiting for the qapi to support GSList */
1564 if (!cur_item) {
1565 head = cur_item = info;
1566 } else {
1567 cur_item->next = info;
1568 cur_item = info;
1573 return head;
1576 static PciInfo *qmp_query_pci_bus(PCIBus *bus, int bus_num)
1578 PciInfo *info = NULL;
1580 bus = pci_find_bus_nr(bus, bus_num);
1581 if (bus) {
1582 info = g_malloc0(sizeof(*info));
1583 info->bus = bus_num;
1584 info->devices = qmp_query_pci_devices(bus, bus_num);
1587 return info;
1590 PciInfoList *qmp_query_pci(Error **errp)
1592 PciInfoList *info, *head = NULL, *cur_item = NULL;
1593 PCIHostState *host_bridge;
1595 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
1596 info = g_malloc0(sizeof(*info));
1597 info->value = qmp_query_pci_bus(host_bridge->bus, 0);
1599 /* XXX: waiting for the qapi to support GSList */
1600 if (!cur_item) {
1601 head = cur_item = info;
1602 } else {
1603 cur_item->next = info;
1604 cur_item = info;
1608 return head;
1611 static const char * const pci_nic_models[] = {
1612 "ne2k_pci",
1613 "i82551",
1614 "i82557b",
1615 "i82559er",
1616 "rtl8139",
1617 "e1000",
1618 "pcnet",
1619 "virtio",
1620 NULL
1623 static const char * const pci_nic_names[] = {
1624 "ne2k_pci",
1625 "i82551",
1626 "i82557b",
1627 "i82559er",
1628 "rtl8139",
1629 "e1000",
1630 "pcnet",
1631 "virtio-net-pci",
1632 NULL
1635 /* Initialize a PCI NIC. */
1636 PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1637 const char *default_model,
1638 const char *default_devaddr)
1640 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1641 Error *err = NULL;
1642 PCIBus *bus;
1643 PCIDevice *pci_dev;
1644 DeviceState *dev;
1645 int devfn;
1646 int i;
1648 if (qemu_show_nic_models(nd->model, pci_nic_models)) {
1649 exit(0);
1652 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1653 if (i < 0) {
1654 exit(1);
1657 bus = pci_get_bus_devfn(&devfn, rootbus, devaddr);
1658 if (!bus) {
1659 error_report("Invalid PCI device address %s for device %s",
1660 devaddr, pci_nic_names[i]);
1661 exit(1);
1664 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1665 dev = &pci_dev->qdev;
1666 qdev_set_nic_properties(dev, nd);
1668 object_property_set_bool(OBJECT(dev), true, "realized", &err);
1669 if (err) {
1670 error_report_err(err);
1671 object_unparent(OBJECT(dev));
1672 exit(1);
1675 return pci_dev;
1678 PCIDevice *pci_vga_init(PCIBus *bus)
1680 switch (vga_interface_type) {
1681 case VGA_CIRRUS:
1682 return pci_create_simple(bus, -1, "cirrus-vga");
1683 case VGA_QXL:
1684 return pci_create_simple(bus, -1, "qxl-vga");
1685 case VGA_STD:
1686 return pci_create_simple(bus, -1, "VGA");
1687 case VGA_VMWARE:
1688 return pci_create_simple(bus, -1, "vmware-svga");
1689 case VGA_NONE:
1690 default: /* Other non-PCI types. Checking for unsupported types is already
1691 done in vl.c. */
1692 return NULL;
1696 /* Whether a given bus number is in range of the secondary
1697 * bus of the given bridge device. */
1698 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1700 return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1701 PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1702 dev->config[PCI_SECONDARY_BUS] < bus_num &&
1703 bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1706 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1708 PCIBus *sec;
1710 if (!bus) {
1711 return NULL;
1714 if (pci_bus_num(bus) == bus_num) {
1715 return bus;
1718 /* Consider all bus numbers in range for the host pci bridge. */
1719 if (!pci_bus_is_root(bus) &&
1720 !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1721 return NULL;
1724 /* try child bus */
1725 for (; bus; bus = sec) {
1726 QLIST_FOREACH(sec, &bus->child, sibling) {
1727 assert(!pci_bus_is_root(sec));
1728 if (sec->parent_dev->config[PCI_SECONDARY_BUS] == bus_num) {
1729 return sec;
1731 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1732 break;
1737 return NULL;
1740 void pci_for_each_bus_depth_first(PCIBus *bus,
1741 void *(*begin)(PCIBus *bus, void *parent_state),
1742 void (*end)(PCIBus *bus, void *state),
1743 void *parent_state)
1745 PCIBus *sec;
1746 void *state;
1748 if (!bus) {
1749 return;
1752 if (begin) {
1753 state = begin(bus, parent_state);
1754 } else {
1755 state = parent_state;
1758 QLIST_FOREACH(sec, &bus->child, sibling) {
1759 pci_for_each_bus_depth_first(sec, begin, end, state);
1762 if (end) {
1763 end(bus, state);
1768 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1770 bus = pci_find_bus_nr(bus, bus_num);
1772 if (!bus)
1773 return NULL;
1775 return bus->devices[devfn];
1778 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
1780 PCIDevice *pci_dev = (PCIDevice *)qdev;
1781 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1782 Error *local_err = NULL;
1783 PCIBus *bus;
1784 bool is_default_rom;
1786 /* initialize cap_present for pci_is_express() and pci_config_size() */
1787 if (pc->is_express) {
1788 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1791 bus = PCI_BUS(qdev_get_parent_bus(qdev));
1792 pci_dev = do_pci_register_device(pci_dev, bus,
1793 object_get_typename(OBJECT(qdev)),
1794 pci_dev->devfn, errp);
1795 if (pci_dev == NULL)
1796 return;
1798 if (pc->realize) {
1799 pc->realize(pci_dev, &local_err);
1800 if (local_err) {
1801 error_propagate(errp, local_err);
1802 do_pci_unregister_device(pci_dev);
1803 return;
1807 /* rom loading */
1808 is_default_rom = false;
1809 if (pci_dev->romfile == NULL && pc->romfile != NULL) {
1810 pci_dev->romfile = g_strdup(pc->romfile);
1811 is_default_rom = true;
1814 pci_add_option_rom(pci_dev, is_default_rom, &local_err);
1815 if (local_err) {
1816 error_propagate(errp, local_err);
1817 pci_qdev_unrealize(DEVICE(pci_dev), NULL);
1818 return;
1822 static void pci_default_realize(PCIDevice *dev, Error **errp)
1824 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
1826 if (pc->init) {
1827 if (pc->init(dev) < 0) {
1828 error_setg(errp, "Device initialization failed");
1829 return;
1834 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1835 const char *name)
1837 DeviceState *dev;
1839 dev = qdev_create(&bus->qbus, name);
1840 qdev_prop_set_int32(dev, "addr", devfn);
1841 qdev_prop_set_bit(dev, "multifunction", multifunction);
1842 return PCI_DEVICE(dev);
1845 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1846 bool multifunction,
1847 const char *name)
1849 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1850 qdev_init_nofail(&dev->qdev);
1851 return dev;
1854 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1856 return pci_create_multifunction(bus, devfn, false, name);
1859 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1861 return pci_create_simple_multifunction(bus, devfn, false, name);
1864 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
1866 int offset = PCI_CONFIG_HEADER_SIZE;
1867 int i;
1868 for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
1869 if (pdev->used[i])
1870 offset = i + 1;
1871 else if (i - offset + 1 == size)
1872 return offset;
1874 return 0;
1877 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1878 uint8_t *prev_p)
1880 uint8_t next, prev;
1882 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1883 return 0;
1885 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1886 prev = next + PCI_CAP_LIST_NEXT)
1887 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1888 break;
1890 if (prev_p)
1891 *prev_p = prev;
1892 return next;
1895 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
1897 uint8_t next, prev, found = 0;
1899 if (!(pdev->used[offset])) {
1900 return 0;
1903 assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
1905 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1906 prev = next + PCI_CAP_LIST_NEXT) {
1907 if (next <= offset && next > found) {
1908 found = next;
1911 return found;
1914 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
1915 This is needed for an option rom which is used for more than one device. */
1916 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
1918 uint16_t vendor_id;
1919 uint16_t device_id;
1920 uint16_t rom_vendor_id;
1921 uint16_t rom_device_id;
1922 uint16_t rom_magic;
1923 uint16_t pcir_offset;
1924 uint8_t checksum;
1926 /* Words in rom data are little endian (like in PCI configuration),
1927 so they can be read / written with pci_get_word / pci_set_word. */
1929 /* Only a valid rom will be patched. */
1930 rom_magic = pci_get_word(ptr);
1931 if (rom_magic != 0xaa55) {
1932 PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
1933 return;
1935 pcir_offset = pci_get_word(ptr + 0x18);
1936 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
1937 PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
1938 return;
1941 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
1942 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
1943 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
1944 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
1946 PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
1947 vendor_id, device_id, rom_vendor_id, rom_device_id);
1949 checksum = ptr[6];
1951 if (vendor_id != rom_vendor_id) {
1952 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
1953 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
1954 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
1955 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1956 ptr[6] = checksum;
1957 pci_set_word(ptr + pcir_offset + 4, vendor_id);
1960 if (device_id != rom_device_id) {
1961 /* Patch device id and checksum (at offset 6 for etherboot roms). */
1962 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
1963 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
1964 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1965 ptr[6] = checksum;
1966 pci_set_word(ptr + pcir_offset + 6, device_id);
1970 /* Add an option rom for the device */
1971 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
1972 Error **errp)
1974 int size;
1975 char *path;
1976 void *ptr;
1977 char name[32];
1978 const VMStateDescription *vmsd;
1980 if (!pdev->romfile)
1981 return;
1982 if (strlen(pdev->romfile) == 0)
1983 return;
1985 if (!pdev->rom_bar) {
1987 * Load rom via fw_cfg instead of creating a rom bar,
1988 * for 0.11 compatibility.
1990 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
1993 * Hot-plugged devices can't use the option ROM
1994 * if the rom bar is disabled.
1996 if (DEVICE(pdev)->hotplugged) {
1997 error_setg(errp, "Hot-plugged device without ROM bar"
1998 " can't have an option ROM");
1999 return;
2002 if (class == 0x0300) {
2003 rom_add_vga(pdev->romfile);
2004 } else {
2005 rom_add_option(pdev->romfile, -1);
2007 return;
2010 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2011 if (path == NULL) {
2012 path = g_strdup(pdev->romfile);
2015 size = get_image_size(path);
2016 if (size < 0) {
2017 error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2018 g_free(path);
2019 return;
2020 } else if (size == 0) {
2021 error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2022 g_free(path);
2023 return;
2025 if (size & (size - 1)) {
2026 size = 1 << qemu_fls(size);
2029 vmsd = qdev_get_vmsd(DEVICE(pdev));
2031 if (vmsd) {
2032 snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2033 } else {
2034 snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2036 pdev->has_rom = true;
2037 memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_abort);
2038 vmstate_register_ram(&pdev->rom, &pdev->qdev);
2039 ptr = memory_region_get_ram_ptr(&pdev->rom);
2040 load_image(path, ptr);
2041 g_free(path);
2043 if (is_default_rom) {
2044 /* Only the default rom images will be patched (if needed). */
2045 pci_patch_ids(pdev, ptr, size);
2048 pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2051 static void pci_del_option_rom(PCIDevice *pdev)
2053 if (!pdev->has_rom)
2054 return;
2056 vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2057 pdev->has_rom = false;
2061 * if !offset
2062 * Reserve space and add capability to the linked list in pci config space
2064 * if offset = 0,
2065 * Find and reserve space and add capability to the linked list
2066 * in pci config space */
2067 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2068 uint8_t offset, uint8_t size)
2070 int ret;
2071 Error *local_err = NULL;
2073 ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err);
2074 if (local_err) {
2075 assert(ret < 0);
2076 error_report_err(local_err);
2077 } else {
2078 /* success implies a positive offset in config space */
2079 assert(ret > 0);
2081 return ret;
2084 int pci_add_capability2(PCIDevice *pdev, uint8_t cap_id,
2085 uint8_t offset, uint8_t size,
2086 Error **errp)
2088 uint8_t *config;
2089 int i, overlapping_cap;
2091 if (!offset) {
2092 offset = pci_find_space(pdev, size);
2093 if (!offset) {
2094 error_setg(errp, "out of PCI config space");
2095 return -ENOSPC;
2097 } else {
2098 /* Verify that capabilities don't overlap. Note: device assignment
2099 * depends on this check to verify that the device is not broken.
2100 * Should never trigger for emulated devices, but it's helpful
2101 * for debugging these. */
2102 for (i = offset; i < offset + size; i++) {
2103 overlapping_cap = pci_find_capability_at_offset(pdev, i);
2104 if (overlapping_cap) {
2105 error_setg(errp, "%s:%02x:%02x.%x "
2106 "Attempt to add PCI capability %x at offset "
2107 "%x overlaps existing capability %x at offset %x",
2108 pci_root_bus_path(pdev), pci_bus_num(pdev->bus),
2109 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2110 cap_id, offset, overlapping_cap, i);
2111 return -EINVAL;
2116 config = pdev->config + offset;
2117 config[PCI_CAP_LIST_ID] = cap_id;
2118 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2119 pdev->config[PCI_CAPABILITY_LIST] = offset;
2120 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2121 memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2122 /* Make capability read-only by default */
2123 memset(pdev->wmask + offset, 0, size);
2124 /* Check capability by default */
2125 memset(pdev->cmask + offset, 0xFF, size);
2126 return offset;
2129 /* Unlink capability from the pci config space. */
2130 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2132 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2133 if (!offset)
2134 return;
2135 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2136 /* Make capability writable again */
2137 memset(pdev->wmask + offset, 0xff, size);
2138 memset(pdev->w1cmask + offset, 0, size);
2139 /* Clear cmask as device-specific registers can't be checked */
2140 memset(pdev->cmask + offset, 0, size);
2141 memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2143 if (!pdev->config[PCI_CAPABILITY_LIST])
2144 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2147 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2149 return pci_find_capability_list(pdev, cap_id, NULL);
2152 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2154 PCIDevice *d = (PCIDevice *)dev;
2155 const pci_class_desc *desc;
2156 char ctxt[64];
2157 PCIIORegion *r;
2158 int i, class;
2160 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2161 desc = pci_class_descriptions;
2162 while (desc->desc && class != desc->class)
2163 desc++;
2164 if (desc->desc) {
2165 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2166 } else {
2167 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2170 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2171 "pci id %04x:%04x (sub %04x:%04x)\n",
2172 indent, "", ctxt, pci_bus_num(d->bus),
2173 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2174 pci_get_word(d->config + PCI_VENDOR_ID),
2175 pci_get_word(d->config + PCI_DEVICE_ID),
2176 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2177 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2178 for (i = 0; i < PCI_NUM_REGIONS; i++) {
2179 r = &d->io_regions[i];
2180 if (!r->size)
2181 continue;
2182 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2183 " [0x%"FMT_PCIBUS"]\n",
2184 indent, "",
2185 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2186 r->addr, r->addr + r->size - 1);
2190 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2192 PCIDevice *d = (PCIDevice *)dev;
2193 const char *name = NULL;
2194 const pci_class_desc *desc = pci_class_descriptions;
2195 int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2197 while (desc->desc &&
2198 (class & ~desc->fw_ign_bits) !=
2199 (desc->class & ~desc->fw_ign_bits)) {
2200 desc++;
2203 if (desc->desc) {
2204 name = desc->fw_name;
2207 if (name) {
2208 pstrcpy(buf, len, name);
2209 } else {
2210 snprintf(buf, len, "pci%04x,%04x",
2211 pci_get_word(d->config + PCI_VENDOR_ID),
2212 pci_get_word(d->config + PCI_DEVICE_ID));
2215 return buf;
2218 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2220 PCIDevice *d = (PCIDevice *)dev;
2221 char path[50], name[33];
2222 int off;
2224 off = snprintf(path, sizeof(path), "%s@%x",
2225 pci_dev_fw_name(dev, name, sizeof name),
2226 PCI_SLOT(d->devfn));
2227 if (PCI_FUNC(d->devfn))
2228 snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2229 return g_strdup(path);
2232 static char *pcibus_get_dev_path(DeviceState *dev)
2234 PCIDevice *d = container_of(dev, PCIDevice, qdev);
2235 PCIDevice *t;
2236 int slot_depth;
2237 /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2238 * 00 is added here to make this format compatible with
2239 * domain:Bus:Slot.Func for systems without nested PCI bridges.
2240 * Slot.Function list specifies the slot and function numbers for all
2241 * devices on the path from root to the specific device. */
2242 const char *root_bus_path;
2243 int root_bus_len;
2244 char slot[] = ":SS.F";
2245 int slot_len = sizeof slot - 1 /* For '\0' */;
2246 int path_len;
2247 char *path, *p;
2248 int s;
2250 root_bus_path = pci_root_bus_path(d);
2251 root_bus_len = strlen(root_bus_path);
2253 /* Calculate # of slots on path between device and root. */;
2254 slot_depth = 0;
2255 for (t = d; t; t = t->bus->parent_dev) {
2256 ++slot_depth;
2259 path_len = root_bus_len + slot_len * slot_depth;
2261 /* Allocate memory, fill in the terminating null byte. */
2262 path = g_malloc(path_len + 1 /* For '\0' */);
2263 path[path_len] = '\0';
2265 memcpy(path, root_bus_path, root_bus_len);
2267 /* Fill in slot numbers. We walk up from device to root, so need to print
2268 * them in the reverse order, last to first. */
2269 p = path + path_len;
2270 for (t = d; t; t = t->bus->parent_dev) {
2271 p -= slot_len;
2272 s = snprintf(slot, sizeof slot, ":%02x.%x",
2273 PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2274 assert(s == slot_len);
2275 memcpy(p, slot, slot_len);
2278 return path;
2281 static int pci_qdev_find_recursive(PCIBus *bus,
2282 const char *id, PCIDevice **pdev)
2284 DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2285 if (!qdev) {
2286 return -ENODEV;
2289 /* roughly check if given qdev is pci device */
2290 if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2291 *pdev = PCI_DEVICE(qdev);
2292 return 0;
2294 return -EINVAL;
2297 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2299 PCIHostState *host_bridge;
2300 int rc = -ENODEV;
2302 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2303 int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2304 if (!tmp) {
2305 rc = 0;
2306 break;
2308 if (tmp != -ENODEV) {
2309 rc = tmp;
2313 return rc;
2316 MemoryRegion *pci_address_space(PCIDevice *dev)
2318 return dev->bus->address_space_mem;
2321 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2323 return dev->bus->address_space_io;
2326 static void pci_device_class_init(ObjectClass *klass, void *data)
2328 DeviceClass *k = DEVICE_CLASS(klass);
2329 PCIDeviceClass *pc = PCI_DEVICE_CLASS(klass);
2331 k->realize = pci_qdev_realize;
2332 k->unrealize = pci_qdev_unrealize;
2333 k->bus_type = TYPE_PCI_BUS;
2334 k->props = pci_props;
2335 pc->realize = pci_default_realize;
2338 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2340 PCIBus *bus = PCI_BUS(dev->bus);
2342 if (bus->iommu_fn) {
2343 return bus->iommu_fn(bus, bus->iommu_opaque, dev->devfn);
2346 if (bus->parent_dev) {
2347 /** We are ignoring the bus master DMA bit of the bridge
2348 * as it would complicate things such as VFIO for no good reason */
2349 return pci_device_iommu_address_space(bus->parent_dev);
2352 return &address_space_memory;
2355 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2357 bus->iommu_fn = fn;
2358 bus->iommu_opaque = opaque;
2361 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2363 Range *range = opaque;
2364 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2365 uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2366 int i;
2368 if (!(cmd & PCI_COMMAND_MEMORY)) {
2369 return;
2372 if (pc->is_bridge) {
2373 pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2374 pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2376 base = MAX(base, 0x1ULL << 32);
2378 if (limit >= base) {
2379 Range pref_range;
2380 pref_range.begin = base;
2381 pref_range.end = limit + 1;
2382 range_extend(range, &pref_range);
2385 for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2386 PCIIORegion *r = &dev->io_regions[i];
2387 Range region_range;
2389 if (!r->size ||
2390 (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2391 !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2392 continue;
2394 region_range.begin = pci_bar_address(dev, i, r->type, r->size);
2395 region_range.end = region_range.begin + r->size;
2397 if (region_range.begin == PCI_BAR_UNMAPPED) {
2398 continue;
2401 region_range.begin = MAX(region_range.begin, 0x1ULL << 32);
2403 if (region_range.end - 1 >= region_range.begin) {
2404 range_extend(range, &region_range);
2409 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2411 range->begin = range->end = 0;
2412 pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2415 static const TypeInfo pci_device_type_info = {
2416 .name = TYPE_PCI_DEVICE,
2417 .parent = TYPE_DEVICE,
2418 .instance_size = sizeof(PCIDevice),
2419 .abstract = true,
2420 .class_size = sizeof(PCIDeviceClass),
2421 .class_init = pci_device_class_init,
2424 static void pci_register_types(void)
2426 type_register_static(&pci_bus_info);
2427 type_register_static(&pcie_bus_info);
2428 type_register_static(&pci_device_type_info);
2431 type_init(pci_register_types)