target-ppc: gdbstub: introduce avr_need_swap()
[qemu/ar7.git] / hw / pci / pci.c
blobd940f79de0c144cdffa76a56c3e408ba5ce91b68
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"
44 //#define DEBUG_PCI
45 #ifdef DEBUG_PCI
46 # define PCI_DPRINTF(format, ...) printf(format, ## __VA_ARGS__)
47 #else
48 # define PCI_DPRINTF(format, ...) do { } while (0)
49 #endif
51 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
52 static char *pcibus_get_dev_path(DeviceState *dev);
53 static char *pcibus_get_fw_dev_path(DeviceState *dev);
54 static void pcibus_reset(BusState *qbus);
56 static Property pci_props[] = {
57 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
58 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
59 DEFINE_PROP_UINT32("rombar", PCIDevice, rom_bar, 1),
60 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
61 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
62 DEFINE_PROP_BIT("command_serr_enable", PCIDevice, cap_present,
63 QEMU_PCI_CAP_SERR_BITNR, true),
64 DEFINE_PROP_END_OF_LIST()
67 static const VMStateDescription vmstate_pcibus = {
68 .name = "PCIBUS",
69 .version_id = 1,
70 .minimum_version_id = 1,
71 .fields = (VMStateField[]) {
72 VMSTATE_INT32_EQUAL(nirq, PCIBus),
73 VMSTATE_VARRAY_INT32(irq_count, PCIBus,
74 nirq, 0, vmstate_info_int32,
75 int32_t),
76 VMSTATE_END_OF_LIST()
80 static void pci_bus_realize(BusState *qbus, Error **errp)
82 PCIBus *bus = PCI_BUS(qbus);
84 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
87 static void pci_bus_unrealize(BusState *qbus, Error **errp)
89 PCIBus *bus = PCI_BUS(qbus);
91 vmstate_unregister(NULL, &vmstate_pcibus, bus);
94 static bool pcibus_is_root(PCIBus *bus)
96 return !bus->parent_dev;
99 static int pcibus_num(PCIBus *bus)
101 if (pcibus_is_root(bus)) {
102 return 0; /* pci host bridge */
104 return bus->parent_dev->config[PCI_SECONDARY_BUS];
107 static uint16_t pcibus_numa_node(PCIBus *bus)
109 return NUMA_NODE_UNASSIGNED;
112 static void pci_bus_class_init(ObjectClass *klass, void *data)
114 BusClass *k = BUS_CLASS(klass);
115 PCIBusClass *pbc = PCI_BUS_CLASS(klass);
117 k->print_dev = pcibus_dev_print;
118 k->get_dev_path = pcibus_get_dev_path;
119 k->get_fw_dev_path = pcibus_get_fw_dev_path;
120 k->realize = pci_bus_realize;
121 k->unrealize = pci_bus_unrealize;
122 k->reset = pcibus_reset;
124 pbc->is_root = pcibus_is_root;
125 pbc->bus_num = pcibus_num;
126 pbc->numa_node = pcibus_numa_node;
129 static const TypeInfo pci_bus_info = {
130 .name = TYPE_PCI_BUS,
131 .parent = TYPE_BUS,
132 .instance_size = sizeof(PCIBus),
133 .class_size = sizeof(PCIBusClass),
134 .class_init = pci_bus_class_init,
137 static const TypeInfo pcie_bus_info = {
138 .name = TYPE_PCIE_BUS,
139 .parent = TYPE_PCI_BUS,
142 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num);
143 static void pci_update_mappings(PCIDevice *d);
144 static void pci_irq_handler(void *opaque, int irq_num, int level);
145 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
146 static void pci_del_option_rom(PCIDevice *pdev);
148 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
149 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
151 static QLIST_HEAD(, PCIHostState) pci_host_bridges;
153 int pci_bar(PCIDevice *d, int reg)
155 uint8_t type;
157 if (reg != PCI_ROM_SLOT)
158 return PCI_BASE_ADDRESS_0 + reg * 4;
160 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
161 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
164 static inline int pci_irq_state(PCIDevice *d, int irq_num)
166 return (d->irq_state >> irq_num) & 0x1;
169 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
171 d->irq_state &= ~(0x1 << irq_num);
172 d->irq_state |= level << irq_num;
175 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
177 PCIBus *bus;
178 for (;;) {
179 bus = pci_dev->bus;
180 irq_num = bus->map_irq(pci_dev, irq_num);
181 if (bus->set_irq)
182 break;
183 pci_dev = bus->parent_dev;
185 bus->irq_count[irq_num] += change;
186 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
189 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
191 assert(irq_num >= 0);
192 assert(irq_num < bus->nirq);
193 return !!bus->irq_count[irq_num];
196 /* Update interrupt status bit in config space on interrupt
197 * state change. */
198 static void pci_update_irq_status(PCIDevice *dev)
200 if (dev->irq_state) {
201 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
202 } else {
203 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
207 void pci_device_deassert_intx(PCIDevice *dev)
209 int i;
210 for (i = 0; i < PCI_NUM_PINS; ++i) {
211 pci_irq_handler(dev, i, 0);
215 static void pci_do_device_reset(PCIDevice *dev)
217 int r;
219 pci_device_deassert_intx(dev);
220 assert(dev->irq_state == 0);
222 /* Clear all writable bits */
223 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
224 pci_get_word(dev->wmask + PCI_COMMAND) |
225 pci_get_word(dev->w1cmask + PCI_COMMAND));
226 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
227 pci_get_word(dev->wmask + PCI_STATUS) |
228 pci_get_word(dev->w1cmask + PCI_STATUS));
229 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
230 dev->config[PCI_INTERRUPT_LINE] = 0x0;
231 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
232 PCIIORegion *region = &dev->io_regions[r];
233 if (!region->size) {
234 continue;
237 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
238 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
239 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
240 } else {
241 pci_set_long(dev->config + pci_bar(dev, r), region->type);
244 pci_update_mappings(dev);
246 msi_reset(dev);
247 msix_reset(dev);
251 * This function is called on #RST and FLR.
252 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
254 void pci_device_reset(PCIDevice *dev)
256 qdev_reset_all(&dev->qdev);
257 pci_do_device_reset(dev);
261 * Trigger pci bus reset under a given bus.
262 * Called via qbus_reset_all on RST# assert, after the devices
263 * have been reset qdev_reset_all-ed already.
265 static void pcibus_reset(BusState *qbus)
267 PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
268 int i;
270 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
271 if (bus->devices[i]) {
272 pci_do_device_reset(bus->devices[i]);
276 for (i = 0; i < bus->nirq; i++) {
277 assert(bus->irq_count[i] == 0);
281 static void pci_host_bus_register(PCIBus *bus, DeviceState *parent)
283 PCIHostState *host_bridge = PCI_HOST_BRIDGE(parent);
285 QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
288 PCIBus *pci_find_primary_bus(void)
290 PCIBus *primary_bus = NULL;
291 PCIHostState *host;
293 QLIST_FOREACH(host, &pci_host_bridges, next) {
294 if (primary_bus) {
295 /* We have multiple root buses, refuse to select a primary */
296 return NULL;
298 primary_bus = host->bus;
301 return primary_bus;
304 PCIBus *pci_device_root_bus(const PCIDevice *d)
306 PCIBus *bus = d->bus;
308 while (!pci_bus_is_root(bus)) {
309 d = bus->parent_dev;
310 assert(d != NULL);
312 bus = d->bus;
315 return bus;
318 const char *pci_root_bus_path(PCIDevice *dev)
320 PCIBus *rootbus = pci_device_root_bus(dev);
321 PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
322 PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
324 assert(host_bridge->bus == rootbus);
326 if (hc->root_bus_path) {
327 return (*hc->root_bus_path)(host_bridge, rootbus);
330 return rootbus->qbus.name;
333 static void pci_bus_init(PCIBus *bus, DeviceState *parent,
334 const char *name,
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(bus, 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, name, address_space_mem,
368 address_space_io, devfn_min);
371 PCIBus *pci_bus_new(DeviceState *parent, const char *name,
372 MemoryRegion *address_space_mem,
373 MemoryRegion *address_space_io,
374 uint8_t devfn_min, const char *typename)
376 PCIBus *bus;
378 bus = PCI_BUS(qbus_create(typename, parent, name));
379 pci_bus_init(bus, parent, name, address_space_mem,
380 address_space_io, devfn_min);
381 return bus;
384 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
385 void *irq_opaque, int nirq)
387 bus->set_irq = set_irq;
388 bus->map_irq = map_irq;
389 bus->irq_opaque = irq_opaque;
390 bus->nirq = nirq;
391 bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
394 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
395 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
396 void *irq_opaque,
397 MemoryRegion *address_space_mem,
398 MemoryRegion *address_space_io,
399 uint8_t devfn_min, int nirq, const char *typename)
401 PCIBus *bus;
403 bus = pci_bus_new(parent, name, address_space_mem,
404 address_space_io, devfn_min, typename);
405 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
406 return bus;
409 int pci_bus_num(PCIBus *s)
411 return PCI_BUS_GET_CLASS(s)->bus_num(s);
414 int pci_bus_numa_node(PCIBus *bus)
416 return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
419 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
421 PCIDevice *s = container_of(pv, PCIDevice, config);
422 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(s);
423 uint8_t *config;
424 int i;
426 assert(size == pci_config_size(s));
427 config = g_malloc(size);
429 qemu_get_buffer(f, config, size);
430 for (i = 0; i < size; ++i) {
431 if ((config[i] ^ s->config[i]) &
432 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
433 error_report("%s: Bad config data: i=0x%x read: %x device: %x "
434 "cmask: %x wmask: %x w1cmask:%x", __func__,
435 i, config[i], s->config[i],
436 s->cmask[i], s->wmask[i], s->w1cmask[i]);
437 g_free(config);
438 return -EINVAL;
441 memcpy(s->config, config, size);
443 pci_update_mappings(s);
444 if (pc->is_bridge) {
445 PCIBridge *b = PCI_BRIDGE(s);
446 pci_bridge_update_mappings(b);
449 memory_region_set_enabled(&s->bus_master_enable_region,
450 pci_get_word(s->config + PCI_COMMAND)
451 & PCI_COMMAND_MASTER);
453 g_free(config);
454 return 0;
457 /* just put buffer */
458 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
460 const uint8_t **v = pv;
461 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
462 qemu_put_buffer(f, *v, size);
465 static VMStateInfo vmstate_info_pci_config = {
466 .name = "pci config",
467 .get = get_pci_config_device,
468 .put = put_pci_config_device,
471 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
473 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
474 uint32_t irq_state[PCI_NUM_PINS];
475 int i;
476 for (i = 0; i < PCI_NUM_PINS; ++i) {
477 irq_state[i] = qemu_get_be32(f);
478 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
479 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
480 irq_state[i]);
481 return -EINVAL;
485 for (i = 0; i < PCI_NUM_PINS; ++i) {
486 pci_set_irq_state(s, i, irq_state[i]);
489 return 0;
492 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
494 int i;
495 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
497 for (i = 0; i < PCI_NUM_PINS; ++i) {
498 qemu_put_be32(f, pci_irq_state(s, i));
502 static VMStateInfo vmstate_info_pci_irq_state = {
503 .name = "pci irq state",
504 .get = get_pci_irq_state,
505 .put = put_pci_irq_state,
508 const VMStateDescription vmstate_pci_device = {
509 .name = "PCIDevice",
510 .version_id = 2,
511 .minimum_version_id = 1,
512 .fields = (VMStateField[]) {
513 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
514 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
515 vmstate_info_pci_config,
516 PCI_CONFIG_SPACE_SIZE),
517 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
518 vmstate_info_pci_irq_state,
519 PCI_NUM_PINS * sizeof(int32_t)),
520 VMSTATE_END_OF_LIST()
524 const VMStateDescription vmstate_pcie_device = {
525 .name = "PCIEDevice",
526 .version_id = 2,
527 .minimum_version_id = 1,
528 .fields = (VMStateField[]) {
529 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
530 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
531 vmstate_info_pci_config,
532 PCIE_CONFIG_SPACE_SIZE),
533 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
534 vmstate_info_pci_irq_state,
535 PCI_NUM_PINS * sizeof(int32_t)),
536 VMSTATE_END_OF_LIST()
540 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
542 return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
545 void pci_device_save(PCIDevice *s, QEMUFile *f)
547 /* Clear interrupt status bit: it is implicit
548 * in irq_state which we are saving.
549 * This makes us compatible with old devices
550 * which never set or clear this bit. */
551 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
552 vmstate_save_state(f, pci_get_vmstate(s), s, NULL);
553 /* Restore the interrupt status bit. */
554 pci_update_irq_status(s);
557 int pci_device_load(PCIDevice *s, QEMUFile *f)
559 int ret;
560 ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
561 /* Restore the interrupt status bit. */
562 pci_update_irq_status(s);
563 return ret;
566 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
568 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
569 pci_default_sub_vendor_id);
570 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
571 pci_default_sub_device_id);
575 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
576 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
578 static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
579 unsigned int *slotp, unsigned int *funcp)
581 const char *p;
582 char *e;
583 unsigned long val;
584 unsigned long dom = 0, bus = 0;
585 unsigned int slot = 0;
586 unsigned int func = 0;
588 p = addr;
589 val = strtoul(p, &e, 16);
590 if (e == p)
591 return -1;
592 if (*e == ':') {
593 bus = val;
594 p = e + 1;
595 val = strtoul(p, &e, 16);
596 if (e == p)
597 return -1;
598 if (*e == ':') {
599 dom = bus;
600 bus = val;
601 p = e + 1;
602 val = strtoul(p, &e, 16);
603 if (e == p)
604 return -1;
608 slot = val;
610 if (funcp != NULL) {
611 if (*e != '.')
612 return -1;
614 p = e + 1;
615 val = strtoul(p, &e, 16);
616 if (e == p)
617 return -1;
619 func = val;
622 /* if funcp == NULL func is 0 */
623 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
624 return -1;
626 if (*e)
627 return -1;
629 *domp = dom;
630 *busp = bus;
631 *slotp = slot;
632 if (funcp != NULL)
633 *funcp = func;
634 return 0;
637 static PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root,
638 const char *devaddr)
640 int dom, bus;
641 unsigned slot;
643 if (!root) {
644 fprintf(stderr, "No primary PCI bus\n");
645 return NULL;
648 assert(!root->parent_dev);
650 if (!devaddr) {
651 *devfnp = -1;
652 return pci_find_bus_nr(root, 0);
655 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
656 return NULL;
659 if (dom != 0) {
660 fprintf(stderr, "No support for non-zero PCI domains\n");
661 return NULL;
664 *devfnp = PCI_DEVFN(slot, 0);
665 return pci_find_bus_nr(root, bus);
668 static void pci_init_cmask(PCIDevice *dev)
670 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
671 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
672 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
673 dev->cmask[PCI_REVISION_ID] = 0xff;
674 dev->cmask[PCI_CLASS_PROG] = 0xff;
675 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
676 dev->cmask[PCI_HEADER_TYPE] = 0xff;
677 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
680 static void pci_init_wmask(PCIDevice *dev)
682 int config_size = pci_config_size(dev);
684 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
685 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
686 pci_set_word(dev->wmask + PCI_COMMAND,
687 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
688 PCI_COMMAND_INTX_DISABLE);
689 if (dev->cap_present & QEMU_PCI_CAP_SERR) {
690 pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
693 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
694 config_size - PCI_CONFIG_HEADER_SIZE);
697 static void pci_init_w1cmask(PCIDevice *dev)
700 * Note: It's okay to set w1cmask even for readonly bits as
701 * long as their value is hardwired to 0.
703 pci_set_word(dev->w1cmask + PCI_STATUS,
704 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
705 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
706 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
709 static void pci_init_mask_bridge(PCIDevice *d)
711 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
712 PCI_SEC_LETENCY_TIMER */
713 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
715 /* base and limit */
716 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
717 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
718 pci_set_word(d->wmask + PCI_MEMORY_BASE,
719 PCI_MEMORY_RANGE_MASK & 0xffff);
720 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
721 PCI_MEMORY_RANGE_MASK & 0xffff);
722 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
723 PCI_PREF_RANGE_MASK & 0xffff);
724 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
725 PCI_PREF_RANGE_MASK & 0xffff);
727 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
728 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
730 /* Supported memory and i/o types */
731 d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
732 d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
733 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
734 PCI_PREF_RANGE_TYPE_64);
735 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
736 PCI_PREF_RANGE_TYPE_64);
739 * TODO: Bridges default to 10-bit VGA decoding but we currently only
740 * implement 16-bit decoding (no alias support).
742 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
743 PCI_BRIDGE_CTL_PARITY |
744 PCI_BRIDGE_CTL_SERR |
745 PCI_BRIDGE_CTL_ISA |
746 PCI_BRIDGE_CTL_VGA |
747 PCI_BRIDGE_CTL_VGA_16BIT |
748 PCI_BRIDGE_CTL_MASTER_ABORT |
749 PCI_BRIDGE_CTL_BUS_RESET |
750 PCI_BRIDGE_CTL_FAST_BACK |
751 PCI_BRIDGE_CTL_DISCARD |
752 PCI_BRIDGE_CTL_SEC_DISCARD |
753 PCI_BRIDGE_CTL_DISCARD_SERR);
754 /* Below does not do anything as we never set this bit, put here for
755 * completeness. */
756 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
757 PCI_BRIDGE_CTL_DISCARD_STATUS);
758 d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
759 d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
760 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
761 PCI_PREF_RANGE_TYPE_MASK);
762 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
763 PCI_PREF_RANGE_TYPE_MASK);
766 static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
768 uint8_t slot = PCI_SLOT(dev->devfn);
769 uint8_t func;
771 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
772 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
776 * multifunction bit is interpreted in two ways as follows.
777 * - all functions must set the bit to 1.
778 * Example: Intel X53
779 * - function 0 must set the bit, but the rest function (> 0)
780 * is allowed to leave the bit to 0.
781 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
783 * So OS (at least Linux) checks the bit of only function 0,
784 * and doesn't see the bit of function > 0.
786 * The below check allows both interpretation.
788 if (PCI_FUNC(dev->devfn)) {
789 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
790 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
791 /* function 0 should set multifunction bit */
792 error_setg(errp, "PCI: single function device can't be populated "
793 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
794 return;
796 return;
799 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
800 return;
802 /* function 0 indicates single function, so function > 0 must be NULL */
803 for (func = 1; func < PCI_FUNC_MAX; ++func) {
804 if (bus->devices[PCI_DEVFN(slot, func)]) {
805 error_setg(errp, "PCI: %x.0 indicates single function, "
806 "but %x.%x is already populated.",
807 slot, slot, func);
808 return;
813 static void pci_config_alloc(PCIDevice *pci_dev)
815 int config_size = pci_config_size(pci_dev);
817 pci_dev->config = g_malloc0(config_size);
818 pci_dev->cmask = g_malloc0(config_size);
819 pci_dev->wmask = g_malloc0(config_size);
820 pci_dev->w1cmask = g_malloc0(config_size);
821 pci_dev->used = g_malloc0(config_size);
824 static void pci_config_free(PCIDevice *pci_dev)
826 g_free(pci_dev->config);
827 g_free(pci_dev->cmask);
828 g_free(pci_dev->wmask);
829 g_free(pci_dev->w1cmask);
830 g_free(pci_dev->used);
833 static void do_pci_unregister_device(PCIDevice *pci_dev)
835 pci_dev->bus->devices[pci_dev->devfn] = NULL;
836 pci_config_free(pci_dev);
838 address_space_destroy(&pci_dev->bus_master_as);
841 /* -1 for devfn means auto assign */
842 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
843 const char *name, int devfn,
844 Error **errp)
846 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
847 PCIConfigReadFunc *config_read = pc->config_read;
848 PCIConfigWriteFunc *config_write = pc->config_write;
849 Error *local_err = NULL;
850 AddressSpace *dma_as;
851 DeviceState *dev = DEVICE(pci_dev);
853 pci_dev->bus = bus;
855 if (devfn < 0) {
856 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
857 devfn += PCI_FUNC_MAX) {
858 if (!bus->devices[devfn])
859 goto found;
861 error_setg(errp, "PCI: no slot/function available for %s, all in use",
862 name);
863 return NULL;
864 found: ;
865 } else if (bus->devices[devfn]) {
866 error_setg(errp, "PCI: slot %d function %d not available for %s,"
867 " in use by %s",
868 PCI_SLOT(devfn), PCI_FUNC(devfn), name,
869 bus->devices[devfn]->name);
870 return NULL;
871 } else if (dev->hotplugged &&
872 pci_get_function_0(pci_dev)) {
873 error_setg(errp, "PCI: slot %d function 0 already ocuppied by %s,"
874 " new func %s cannot be exposed to guest.",
875 PCI_SLOT(devfn),
876 bus->devices[PCI_DEVFN(PCI_SLOT(devfn), 0)]->name,
877 name);
879 return NULL;
882 pci_dev->devfn = devfn;
883 dma_as = pci_device_iommu_address_space(pci_dev);
885 memory_region_init_alias(&pci_dev->bus_master_enable_region,
886 OBJECT(pci_dev), "bus master",
887 dma_as->root, 0, memory_region_size(dma_as->root));
888 memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
889 address_space_init(&pci_dev->bus_master_as, &pci_dev->bus_master_enable_region,
890 name);
892 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
893 pci_dev->irq_state = 0;
894 pci_config_alloc(pci_dev);
896 pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
897 pci_config_set_device_id(pci_dev->config, pc->device_id);
898 pci_config_set_revision(pci_dev->config, pc->revision);
899 pci_config_set_class(pci_dev->config, pc->class_id);
901 if (!pc->is_bridge) {
902 if (pc->subsystem_vendor_id || pc->subsystem_id) {
903 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
904 pc->subsystem_vendor_id);
905 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
906 pc->subsystem_id);
907 } else {
908 pci_set_default_subsystem_id(pci_dev);
910 } else {
911 /* subsystem_vendor_id/subsystem_id are only for header type 0 */
912 assert(!pc->subsystem_vendor_id);
913 assert(!pc->subsystem_id);
915 pci_init_cmask(pci_dev);
916 pci_init_wmask(pci_dev);
917 pci_init_w1cmask(pci_dev);
918 if (pc->is_bridge) {
919 pci_init_mask_bridge(pci_dev);
921 pci_init_multifunction(bus, pci_dev, &local_err);
922 if (local_err) {
923 error_propagate(errp, local_err);
924 do_pci_unregister_device(pci_dev);
925 return NULL;
928 if (!config_read)
929 config_read = pci_default_read_config;
930 if (!config_write)
931 config_write = pci_default_write_config;
932 pci_dev->config_read = config_read;
933 pci_dev->config_write = config_write;
934 bus->devices[devfn] = pci_dev;
935 pci_dev->version_id = 2; /* Current pci device vmstate version */
936 return pci_dev;
939 static void pci_unregister_io_regions(PCIDevice *pci_dev)
941 PCIIORegion *r;
942 int i;
944 for(i = 0; i < PCI_NUM_REGIONS; i++) {
945 r = &pci_dev->io_regions[i];
946 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
947 continue;
948 memory_region_del_subregion(r->address_space, r->memory);
951 pci_unregister_vga(pci_dev);
954 static void pci_qdev_unrealize(DeviceState *dev, Error **errp)
956 PCIDevice *pci_dev = PCI_DEVICE(dev);
957 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
959 pci_unregister_io_regions(pci_dev);
960 pci_del_option_rom(pci_dev);
962 if (pc->exit) {
963 pc->exit(pci_dev);
966 do_pci_unregister_device(pci_dev);
969 void pci_register_bar(PCIDevice *pci_dev, int region_num,
970 uint8_t type, MemoryRegion *memory)
972 PCIIORegion *r;
973 uint32_t addr;
974 uint64_t wmask;
975 pcibus_t size = memory_region_size(memory);
977 assert(region_num >= 0);
978 assert(region_num < PCI_NUM_REGIONS);
979 if (size & (size-1)) {
980 fprintf(stderr, "ERROR: PCI region size must be pow2 "
981 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
982 exit(1);
985 r = &pci_dev->io_regions[region_num];
986 r->addr = PCI_BAR_UNMAPPED;
987 r->size = size;
988 r->type = type;
989 r->memory = NULL;
991 wmask = ~(size - 1);
992 addr = pci_bar(pci_dev, region_num);
993 if (region_num == PCI_ROM_SLOT) {
994 /* ROM enable bit is writable */
995 wmask |= PCI_ROM_ADDRESS_ENABLE;
997 pci_set_long(pci_dev->config + addr, type);
998 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
999 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1000 pci_set_quad(pci_dev->wmask + addr, wmask);
1001 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1002 } else {
1003 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1004 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1006 pci_dev->io_regions[region_num].memory = memory;
1007 pci_dev->io_regions[region_num].address_space
1008 = type & PCI_BASE_ADDRESS_SPACE_IO
1009 ? pci_dev->bus->address_space_io
1010 : pci_dev->bus->address_space_mem;
1013 static void pci_update_vga(PCIDevice *pci_dev)
1015 uint16_t cmd;
1017 if (!pci_dev->has_vga) {
1018 return;
1021 cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1023 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1024 cmd & PCI_COMMAND_MEMORY);
1025 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1026 cmd & PCI_COMMAND_IO);
1027 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1028 cmd & PCI_COMMAND_IO);
1031 void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1032 MemoryRegion *io_lo, MemoryRegion *io_hi)
1034 assert(!pci_dev->has_vga);
1036 assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1037 pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1038 memory_region_add_subregion_overlap(pci_dev->bus->address_space_mem,
1039 QEMU_PCI_VGA_MEM_BASE, mem, 1);
1041 assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1042 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1043 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1044 QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1046 assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1047 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1048 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1049 QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1050 pci_dev->has_vga = true;
1052 pci_update_vga(pci_dev);
1055 void pci_unregister_vga(PCIDevice *pci_dev)
1057 if (!pci_dev->has_vga) {
1058 return;
1061 memory_region_del_subregion(pci_dev->bus->address_space_mem,
1062 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1063 memory_region_del_subregion(pci_dev->bus->address_space_io,
1064 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1065 memory_region_del_subregion(pci_dev->bus->address_space_io,
1066 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1067 pci_dev->has_vga = false;
1070 pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1072 return pci_dev->io_regions[region_num].addr;
1075 static pcibus_t pci_bar_address(PCIDevice *d,
1076 int reg, uint8_t type, pcibus_t size)
1078 pcibus_t new_addr, last_addr;
1079 int bar = pci_bar(d, reg);
1080 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1081 Object *machine = qdev_get_machine();
1082 ObjectClass *oc = object_get_class(machine);
1083 MachineClass *mc = MACHINE_CLASS(oc);
1084 bool allow_0_address = mc->pci_allow_0_address;
1086 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1087 if (!(cmd & PCI_COMMAND_IO)) {
1088 return PCI_BAR_UNMAPPED;
1090 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
1091 last_addr = new_addr + size - 1;
1092 /* Check if 32 bit BAR wraps around explicitly.
1093 * TODO: make priorities correct and remove this work around.
1095 if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1096 (!allow_0_address && new_addr == 0)) {
1097 return PCI_BAR_UNMAPPED;
1099 return new_addr;
1102 if (!(cmd & PCI_COMMAND_MEMORY)) {
1103 return PCI_BAR_UNMAPPED;
1105 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1106 new_addr = pci_get_quad(d->config + bar);
1107 } else {
1108 new_addr = pci_get_long(d->config + bar);
1110 /* the ROM slot has a specific enable bit */
1111 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1112 return PCI_BAR_UNMAPPED;
1114 new_addr &= ~(size - 1);
1115 last_addr = new_addr + size - 1;
1116 /* NOTE: we do not support wrapping */
1117 /* XXX: as we cannot support really dynamic
1118 mappings, we handle specific values as invalid
1119 mappings. */
1120 if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1121 (!allow_0_address && new_addr == 0)) {
1122 return PCI_BAR_UNMAPPED;
1125 /* Now pcibus_t is 64bit.
1126 * Check if 32 bit BAR wraps around explicitly.
1127 * Without this, PC ide doesn't work well.
1128 * TODO: remove this work around.
1130 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1131 return PCI_BAR_UNMAPPED;
1135 * OS is allowed to set BAR beyond its addressable
1136 * bits. For example, 32 bit OS can set 64bit bar
1137 * to >4G. Check it. TODO: we might need to support
1138 * it in the future for e.g. PAE.
1140 if (last_addr >= HWADDR_MAX) {
1141 return PCI_BAR_UNMAPPED;
1144 return new_addr;
1147 static void pci_update_mappings(PCIDevice *d)
1149 PCIIORegion *r;
1150 int i;
1151 pcibus_t new_addr;
1153 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1154 r = &d->io_regions[i];
1156 /* this region isn't registered */
1157 if (!r->size)
1158 continue;
1160 new_addr = pci_bar_address(d, i, r->type, r->size);
1162 /* This bar isn't changed */
1163 if (new_addr == r->addr)
1164 continue;
1166 /* now do the real mapping */
1167 if (r->addr != PCI_BAR_UNMAPPED) {
1168 trace_pci_update_mappings_del(d, pci_bus_num(d->bus),
1169 PCI_SLOT(d->devfn),
1170 PCI_FUNC(d->devfn),
1171 i, r->addr, r->size);
1172 memory_region_del_subregion(r->address_space, r->memory);
1174 r->addr = new_addr;
1175 if (r->addr != PCI_BAR_UNMAPPED) {
1176 trace_pci_update_mappings_add(d, pci_bus_num(d->bus),
1177 PCI_SLOT(d->devfn),
1178 PCI_FUNC(d->devfn),
1179 i, r->addr, r->size);
1180 memory_region_add_subregion_overlap(r->address_space,
1181 r->addr, r->memory, 1);
1185 pci_update_vga(d);
1188 static inline int pci_irq_disabled(PCIDevice *d)
1190 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1193 /* Called after interrupt disabled field update in config space,
1194 * assert/deassert interrupts if necessary.
1195 * Gets original interrupt disable bit value (before update). */
1196 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1198 int i, disabled = pci_irq_disabled(d);
1199 if (disabled == was_irq_disabled)
1200 return;
1201 for (i = 0; i < PCI_NUM_PINS; ++i) {
1202 int state = pci_irq_state(d, i);
1203 pci_change_irq_level(d, i, disabled ? -state : state);
1207 uint32_t pci_default_read_config(PCIDevice *d,
1208 uint32_t address, int len)
1210 uint32_t val = 0;
1212 memcpy(&val, d->config + address, len);
1213 return le32_to_cpu(val);
1216 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1218 int i, was_irq_disabled = pci_irq_disabled(d);
1219 uint32_t val = val_in;
1221 for (i = 0; i < l; val >>= 8, ++i) {
1222 uint8_t wmask = d->wmask[addr + i];
1223 uint8_t w1cmask = d->w1cmask[addr + i];
1224 assert(!(wmask & w1cmask));
1225 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1226 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1228 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1229 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1230 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1231 range_covers_byte(addr, l, PCI_COMMAND))
1232 pci_update_mappings(d);
1234 if (range_covers_byte(addr, l, PCI_COMMAND)) {
1235 pci_update_irq_disabled(d, was_irq_disabled);
1236 memory_region_set_enabled(&d->bus_master_enable_region,
1237 pci_get_word(d->config + PCI_COMMAND)
1238 & PCI_COMMAND_MASTER);
1241 msi_write_config(d, addr, val_in, l);
1242 msix_write_config(d, addr, val_in, l);
1245 /***********************************************************/
1246 /* generic PCI irq support */
1248 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1249 static void pci_irq_handler(void *opaque, int irq_num, int level)
1251 PCIDevice *pci_dev = opaque;
1252 int change;
1254 change = level - pci_irq_state(pci_dev, irq_num);
1255 if (!change)
1256 return;
1258 pci_set_irq_state(pci_dev, irq_num, level);
1259 pci_update_irq_status(pci_dev);
1260 if (pci_irq_disabled(pci_dev))
1261 return;
1262 pci_change_irq_level(pci_dev, irq_num, change);
1265 static inline int pci_intx(PCIDevice *pci_dev)
1267 return pci_get_byte(pci_dev->config + PCI_INTERRUPT_PIN) - 1;
1270 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1272 int intx = pci_intx(pci_dev);
1274 return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1277 void pci_set_irq(PCIDevice *pci_dev, int level)
1279 int intx = pci_intx(pci_dev);
1280 pci_irq_handler(pci_dev, intx, level);
1283 /* Special hooks used by device assignment */
1284 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1286 assert(pci_bus_is_root(bus));
1287 bus->route_intx_to_irq = route_intx_to_irq;
1290 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1292 PCIBus *bus;
1294 do {
1295 bus = dev->bus;
1296 pin = bus->map_irq(dev, pin);
1297 dev = bus->parent_dev;
1298 } while (dev);
1300 if (!bus->route_intx_to_irq) {
1301 error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1302 object_get_typename(OBJECT(bus->qbus.parent)));
1303 return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1306 return bus->route_intx_to_irq(bus->irq_opaque, pin);
1309 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1311 return old->mode != new->mode || old->irq != new->irq;
1314 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1316 PCIDevice *dev;
1317 PCIBus *sec;
1318 int i;
1320 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1321 dev = bus->devices[i];
1322 if (dev && dev->intx_routing_notifier) {
1323 dev->intx_routing_notifier(dev);
1327 QLIST_FOREACH(sec, &bus->child, sibling) {
1328 pci_bus_fire_intx_routing_notifier(sec);
1332 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1333 PCIINTxRoutingNotifier notifier)
1335 dev->intx_routing_notifier = notifier;
1339 * PCI-to-PCI bridge specification
1340 * 9.1: Interrupt routing. Table 9-1
1342 * the PCI Express Base Specification, Revision 2.1
1343 * 2.2.8.1: INTx interrutp signaling - Rules
1344 * the Implementation Note
1345 * Table 2-20
1348 * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1349 * 0-origin unlike PCI interrupt pin register.
1351 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1353 return (pin + PCI_SLOT(pci_dev->devfn)) % PCI_NUM_PINS;
1356 /***********************************************************/
1357 /* monitor info on PCI */
1359 typedef struct {
1360 uint16_t class;
1361 const char *desc;
1362 const char *fw_name;
1363 uint16_t fw_ign_bits;
1364 } pci_class_desc;
1366 static const pci_class_desc pci_class_descriptions[] =
1368 { 0x0001, "VGA controller", "display"},
1369 { 0x0100, "SCSI controller", "scsi"},
1370 { 0x0101, "IDE controller", "ide"},
1371 { 0x0102, "Floppy controller", "fdc"},
1372 { 0x0103, "IPI controller", "ipi"},
1373 { 0x0104, "RAID controller", "raid"},
1374 { 0x0106, "SATA controller"},
1375 { 0x0107, "SAS controller"},
1376 { 0x0180, "Storage controller"},
1377 { 0x0200, "Ethernet controller", "ethernet"},
1378 { 0x0201, "Token Ring controller", "token-ring"},
1379 { 0x0202, "FDDI controller", "fddi"},
1380 { 0x0203, "ATM controller", "atm"},
1381 { 0x0280, "Network controller"},
1382 { 0x0300, "VGA controller", "display", 0x00ff},
1383 { 0x0301, "XGA controller"},
1384 { 0x0302, "3D controller"},
1385 { 0x0380, "Display controller"},
1386 { 0x0400, "Video controller", "video"},
1387 { 0x0401, "Audio controller", "sound"},
1388 { 0x0402, "Phone"},
1389 { 0x0403, "Audio controller", "sound"},
1390 { 0x0480, "Multimedia controller"},
1391 { 0x0500, "RAM controller", "memory"},
1392 { 0x0501, "Flash controller", "flash"},
1393 { 0x0580, "Memory controller"},
1394 { 0x0600, "Host bridge", "host"},
1395 { 0x0601, "ISA bridge", "isa"},
1396 { 0x0602, "EISA bridge", "eisa"},
1397 { 0x0603, "MC bridge", "mca"},
1398 { 0x0604, "PCI bridge", "pci-bridge"},
1399 { 0x0605, "PCMCIA bridge", "pcmcia"},
1400 { 0x0606, "NUBUS bridge", "nubus"},
1401 { 0x0607, "CARDBUS bridge", "cardbus"},
1402 { 0x0608, "RACEWAY bridge"},
1403 { 0x0680, "Bridge"},
1404 { 0x0700, "Serial port", "serial"},
1405 { 0x0701, "Parallel port", "parallel"},
1406 { 0x0800, "Interrupt controller", "interrupt-controller"},
1407 { 0x0801, "DMA controller", "dma-controller"},
1408 { 0x0802, "Timer", "timer"},
1409 { 0x0803, "RTC", "rtc"},
1410 { 0x0900, "Keyboard", "keyboard"},
1411 { 0x0901, "Pen", "pen"},
1412 { 0x0902, "Mouse", "mouse"},
1413 { 0x0A00, "Dock station", "dock", 0x00ff},
1414 { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1415 { 0x0c00, "Fireware contorller", "fireware"},
1416 { 0x0c01, "Access bus controller", "access-bus"},
1417 { 0x0c02, "SSA controller", "ssa"},
1418 { 0x0c03, "USB controller", "usb"},
1419 { 0x0c04, "Fibre channel controller", "fibre-channel"},
1420 { 0x0c05, "SMBus"},
1421 { 0, NULL}
1424 static void pci_for_each_device_under_bus(PCIBus *bus,
1425 void (*fn)(PCIBus *b, PCIDevice *d,
1426 void *opaque),
1427 void *opaque)
1429 PCIDevice *d;
1430 int devfn;
1432 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1433 d = bus->devices[devfn];
1434 if (d) {
1435 fn(bus, d, opaque);
1440 void pci_for_each_device(PCIBus *bus, int bus_num,
1441 void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
1442 void *opaque)
1444 bus = pci_find_bus_nr(bus, bus_num);
1446 if (bus) {
1447 pci_for_each_device_under_bus(bus, fn, opaque);
1451 static const pci_class_desc *get_class_desc(int class)
1453 const pci_class_desc *desc;
1455 desc = pci_class_descriptions;
1456 while (desc->desc && class != desc->class) {
1457 desc++;
1460 return desc;
1463 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num);
1465 static PciMemoryRegionList *qmp_query_pci_regions(const PCIDevice *dev)
1467 PciMemoryRegionList *head = NULL, *cur_item = NULL;
1468 int i;
1470 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1471 const PCIIORegion *r = &dev->io_regions[i];
1472 PciMemoryRegionList *region;
1474 if (!r->size) {
1475 continue;
1478 region = g_malloc0(sizeof(*region));
1479 region->value = g_malloc0(sizeof(*region->value));
1481 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1482 region->value->type = g_strdup("io");
1483 } else {
1484 region->value->type = g_strdup("memory");
1485 region->value->has_prefetch = true;
1486 region->value->prefetch = !!(r->type & PCI_BASE_ADDRESS_MEM_PREFETCH);
1487 region->value->has_mem_type_64 = true;
1488 region->value->mem_type_64 = !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
1491 region->value->bar = i;
1492 region->value->address = r->addr;
1493 region->value->size = r->size;
1495 /* XXX: waiting for the qapi to support GSList */
1496 if (!cur_item) {
1497 head = cur_item = region;
1498 } else {
1499 cur_item->next = region;
1500 cur_item = region;
1504 return head;
1507 static PciBridgeInfo *qmp_query_pci_bridge(PCIDevice *dev, PCIBus *bus,
1508 int bus_num)
1510 PciBridgeInfo *info;
1511 PciMemoryRange *range;
1513 info = g_new0(PciBridgeInfo, 1);
1515 info->bus = g_new0(PciBusInfo, 1);
1516 info->bus->number = dev->config[PCI_PRIMARY_BUS];
1517 info->bus->secondary = dev->config[PCI_SECONDARY_BUS];
1518 info->bus->subordinate = dev->config[PCI_SUBORDINATE_BUS];
1520 range = info->bus->io_range = g_new0(PciMemoryRange, 1);
1521 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
1522 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
1524 range = info->bus->memory_range = g_new0(PciMemoryRange, 1);
1525 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1526 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1528 range = info->bus->prefetchable_range = g_new0(PciMemoryRange, 1);
1529 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1530 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1532 if (dev->config[PCI_SECONDARY_BUS] != 0) {
1533 PCIBus *child_bus = pci_find_bus_nr(bus, dev->config[PCI_SECONDARY_BUS]);
1534 if (child_bus) {
1535 info->has_devices = true;
1536 info->devices = qmp_query_pci_devices(child_bus, dev->config[PCI_SECONDARY_BUS]);
1540 return info;
1543 static PciDeviceInfo *qmp_query_pci_device(PCIDevice *dev, PCIBus *bus,
1544 int bus_num)
1546 const pci_class_desc *desc;
1547 PciDeviceInfo *info;
1548 uint8_t type;
1549 int class;
1551 info = g_new0(PciDeviceInfo, 1);
1552 info->bus = bus_num;
1553 info->slot = PCI_SLOT(dev->devfn);
1554 info->function = PCI_FUNC(dev->devfn);
1556 info->class_info = g_new0(PciDeviceClass, 1);
1557 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1558 info->class_info->q_class = class;
1559 desc = get_class_desc(class);
1560 if (desc->desc) {
1561 info->class_info->has_desc = true;
1562 info->class_info->desc = g_strdup(desc->desc);
1565 info->id = g_new0(PciDeviceId, 1);
1566 info->id->vendor = pci_get_word(dev->config + PCI_VENDOR_ID);
1567 info->id->device = pci_get_word(dev->config + PCI_DEVICE_ID);
1568 info->regions = qmp_query_pci_regions(dev);
1569 info->qdev_id = g_strdup(dev->qdev.id ? dev->qdev.id : "");
1571 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1572 info->has_irq = true;
1573 info->irq = dev->config[PCI_INTERRUPT_LINE];
1576 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1577 if (type == PCI_HEADER_TYPE_BRIDGE) {
1578 info->has_pci_bridge = true;
1579 info->pci_bridge = qmp_query_pci_bridge(dev, bus, bus_num);
1582 return info;
1585 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num)
1587 PciDeviceInfoList *info, *head = NULL, *cur_item = NULL;
1588 PCIDevice *dev;
1589 int devfn;
1591 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1592 dev = bus->devices[devfn];
1593 if (dev) {
1594 info = g_malloc0(sizeof(*info));
1595 info->value = qmp_query_pci_device(dev, bus, bus_num);
1597 /* XXX: waiting for the qapi to support GSList */
1598 if (!cur_item) {
1599 head = cur_item = info;
1600 } else {
1601 cur_item->next = info;
1602 cur_item = info;
1607 return head;
1610 static PciInfo *qmp_query_pci_bus(PCIBus *bus, int bus_num)
1612 PciInfo *info = NULL;
1614 bus = pci_find_bus_nr(bus, bus_num);
1615 if (bus) {
1616 info = g_malloc0(sizeof(*info));
1617 info->bus = bus_num;
1618 info->devices = qmp_query_pci_devices(bus, bus_num);
1621 return info;
1624 PciInfoList *qmp_query_pci(Error **errp)
1626 PciInfoList *info, *head = NULL, *cur_item = NULL;
1627 PCIHostState *host_bridge;
1629 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
1630 info = g_malloc0(sizeof(*info));
1631 info->value = qmp_query_pci_bus(host_bridge->bus,
1632 pci_bus_num(host_bridge->bus));
1634 /* XXX: waiting for the qapi to support GSList */
1635 if (!cur_item) {
1636 head = cur_item = info;
1637 } else {
1638 cur_item->next = info;
1639 cur_item = info;
1643 return head;
1646 static const char * const pci_nic_models[] = {
1647 "ne2k_pci",
1648 "i82551",
1649 "i82557b",
1650 "i82559er",
1651 "rtl8139",
1652 "e1000",
1653 "pcnet",
1654 "virtio",
1655 NULL
1658 static const char * const pci_nic_names[] = {
1659 "ne2k_pci",
1660 "i82551",
1661 "i82557b",
1662 "i82559er",
1663 "rtl8139",
1664 "e1000",
1665 "pcnet",
1666 "virtio-net-pci",
1667 NULL
1670 /* Initialize a PCI NIC. */
1671 PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1672 const char *default_model,
1673 const char *default_devaddr)
1675 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1676 Error *err = NULL;
1677 PCIBus *bus;
1678 PCIDevice *pci_dev;
1679 DeviceState *dev;
1680 int devfn;
1681 int i;
1683 if (qemu_show_nic_models(nd->model, pci_nic_models)) {
1684 exit(0);
1687 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1688 if (i < 0) {
1689 exit(1);
1692 bus = pci_get_bus_devfn(&devfn, rootbus, devaddr);
1693 if (!bus) {
1694 error_report("Invalid PCI device address %s for device %s",
1695 devaddr, pci_nic_names[i]);
1696 exit(1);
1699 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1700 dev = &pci_dev->qdev;
1701 qdev_set_nic_properties(dev, nd);
1703 object_property_set_bool(OBJECT(dev), true, "realized", &err);
1704 if (err) {
1705 error_report_err(err);
1706 object_unparent(OBJECT(dev));
1707 exit(1);
1710 return pci_dev;
1713 PCIDevice *pci_vga_init(PCIBus *bus)
1715 switch (vga_interface_type) {
1716 case VGA_CIRRUS:
1717 return pci_create_simple(bus, -1, "cirrus-vga");
1718 case VGA_QXL:
1719 return pci_create_simple(bus, -1, "qxl-vga");
1720 case VGA_STD:
1721 return pci_create_simple(bus, -1, "VGA");
1722 case VGA_VMWARE:
1723 return pci_create_simple(bus, -1, "vmware-svga");
1724 case VGA_VIRTIO:
1725 return pci_create_simple(bus, -1, "virtio-vga");
1726 case VGA_NONE:
1727 default: /* Other non-PCI types. Checking for unsupported types is already
1728 done in vl.c. */
1729 return NULL;
1733 /* Whether a given bus number is in range of the secondary
1734 * bus of the given bridge device. */
1735 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1737 return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1738 PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1739 dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1740 bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1743 /* Whether a given bus number is in a range of a root bus */
1744 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1746 int i;
1748 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1749 PCIDevice *dev = bus->devices[i];
1751 if (dev && PCI_DEVICE_GET_CLASS(dev)->is_bridge) {
1752 if (pci_secondary_bus_in_range(dev, bus_num)) {
1753 return true;
1758 return false;
1761 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1763 PCIBus *sec;
1765 if (!bus) {
1766 return NULL;
1769 if (pci_bus_num(bus) == bus_num) {
1770 return bus;
1773 /* Consider all bus numbers in range for the host pci bridge. */
1774 if (!pci_bus_is_root(bus) &&
1775 !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1776 return NULL;
1779 /* try child bus */
1780 for (; bus; bus = sec) {
1781 QLIST_FOREACH(sec, &bus->child, sibling) {
1782 if (pci_bus_num(sec) == bus_num) {
1783 return sec;
1785 /* PXB buses assumed to be children of bus 0 */
1786 if (pci_bus_is_root(sec)) {
1787 if (pci_root_bus_in_range(sec, bus_num)) {
1788 break;
1790 } else {
1791 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1792 break;
1798 return NULL;
1801 void pci_for_each_bus_depth_first(PCIBus *bus,
1802 void *(*begin)(PCIBus *bus, void *parent_state),
1803 void (*end)(PCIBus *bus, void *state),
1804 void *parent_state)
1806 PCIBus *sec;
1807 void *state;
1809 if (!bus) {
1810 return;
1813 if (begin) {
1814 state = begin(bus, parent_state);
1815 } else {
1816 state = parent_state;
1819 QLIST_FOREACH(sec, &bus->child, sibling) {
1820 pci_for_each_bus_depth_first(sec, begin, end, state);
1823 if (end) {
1824 end(bus, state);
1829 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1831 bus = pci_find_bus_nr(bus, bus_num);
1833 if (!bus)
1834 return NULL;
1836 return bus->devices[devfn];
1839 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
1841 PCIDevice *pci_dev = (PCIDevice *)qdev;
1842 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1843 Error *local_err = NULL;
1844 PCIBus *bus;
1845 bool is_default_rom;
1847 /* initialize cap_present for pci_is_express() and pci_config_size() */
1848 if (pc->is_express) {
1849 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1852 bus = PCI_BUS(qdev_get_parent_bus(qdev));
1853 pci_dev = do_pci_register_device(pci_dev, bus,
1854 object_get_typename(OBJECT(qdev)),
1855 pci_dev->devfn, errp);
1856 if (pci_dev == NULL)
1857 return;
1859 if (pc->realize) {
1860 pc->realize(pci_dev, &local_err);
1861 if (local_err) {
1862 error_propagate(errp, local_err);
1863 do_pci_unregister_device(pci_dev);
1864 return;
1868 /* rom loading */
1869 is_default_rom = false;
1870 if (pci_dev->romfile == NULL && pc->romfile != NULL) {
1871 pci_dev->romfile = g_strdup(pc->romfile);
1872 is_default_rom = true;
1875 pci_add_option_rom(pci_dev, is_default_rom, &local_err);
1876 if (local_err) {
1877 error_propagate(errp, local_err);
1878 pci_qdev_unrealize(DEVICE(pci_dev), NULL);
1879 return;
1883 static void pci_default_realize(PCIDevice *dev, Error **errp)
1885 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
1887 if (pc->init) {
1888 if (pc->init(dev) < 0) {
1889 error_setg(errp, "Device initialization failed");
1890 return;
1895 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1896 const char *name)
1898 DeviceState *dev;
1900 dev = qdev_create(&bus->qbus, name);
1901 qdev_prop_set_int32(dev, "addr", devfn);
1902 qdev_prop_set_bit(dev, "multifunction", multifunction);
1903 return PCI_DEVICE(dev);
1906 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1907 bool multifunction,
1908 const char *name)
1910 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1911 qdev_init_nofail(&dev->qdev);
1912 return dev;
1915 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1917 return pci_create_multifunction(bus, devfn, false, name);
1920 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1922 return pci_create_simple_multifunction(bus, devfn, false, name);
1925 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
1927 int offset = PCI_CONFIG_HEADER_SIZE;
1928 int i;
1929 for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
1930 if (pdev->used[i])
1931 offset = i + 1;
1932 else if (i - offset + 1 == size)
1933 return offset;
1935 return 0;
1938 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1939 uint8_t *prev_p)
1941 uint8_t next, prev;
1943 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1944 return 0;
1946 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1947 prev = next + PCI_CAP_LIST_NEXT)
1948 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1949 break;
1951 if (prev_p)
1952 *prev_p = prev;
1953 return next;
1956 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
1958 uint8_t next, prev, found = 0;
1960 if (!(pdev->used[offset])) {
1961 return 0;
1964 assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
1966 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1967 prev = next + PCI_CAP_LIST_NEXT) {
1968 if (next <= offset && next > found) {
1969 found = next;
1972 return found;
1975 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
1976 This is needed for an option rom which is used for more than one device. */
1977 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
1979 uint16_t vendor_id;
1980 uint16_t device_id;
1981 uint16_t rom_vendor_id;
1982 uint16_t rom_device_id;
1983 uint16_t rom_magic;
1984 uint16_t pcir_offset;
1985 uint8_t checksum;
1987 /* Words in rom data are little endian (like in PCI configuration),
1988 so they can be read / written with pci_get_word / pci_set_word. */
1990 /* Only a valid rom will be patched. */
1991 rom_magic = pci_get_word(ptr);
1992 if (rom_magic != 0xaa55) {
1993 PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
1994 return;
1996 pcir_offset = pci_get_word(ptr + 0x18);
1997 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
1998 PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
1999 return;
2002 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2003 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2004 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2005 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2007 PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2008 vendor_id, device_id, rom_vendor_id, rom_device_id);
2010 checksum = ptr[6];
2012 if (vendor_id != rom_vendor_id) {
2013 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2014 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2015 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2016 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2017 ptr[6] = checksum;
2018 pci_set_word(ptr + pcir_offset + 4, vendor_id);
2021 if (device_id != rom_device_id) {
2022 /* Patch device id and checksum (at offset 6 for etherboot roms). */
2023 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2024 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2025 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2026 ptr[6] = checksum;
2027 pci_set_word(ptr + pcir_offset + 6, device_id);
2031 /* Add an option rom for the device */
2032 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2033 Error **errp)
2035 int size;
2036 char *path;
2037 void *ptr;
2038 char name[32];
2039 const VMStateDescription *vmsd;
2041 if (!pdev->romfile)
2042 return;
2043 if (strlen(pdev->romfile) == 0)
2044 return;
2046 if (!pdev->rom_bar) {
2048 * Load rom via fw_cfg instead of creating a rom bar,
2049 * for 0.11 compatibility.
2051 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2054 * Hot-plugged devices can't use the option ROM
2055 * if the rom bar is disabled.
2057 if (DEVICE(pdev)->hotplugged) {
2058 error_setg(errp, "Hot-plugged device without ROM bar"
2059 " can't have an option ROM");
2060 return;
2063 if (class == 0x0300) {
2064 rom_add_vga(pdev->romfile);
2065 } else {
2066 rom_add_option(pdev->romfile, -1);
2068 return;
2071 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2072 if (path == NULL) {
2073 path = g_strdup(pdev->romfile);
2076 size = get_image_size(path);
2077 if (size < 0) {
2078 error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2079 g_free(path);
2080 return;
2081 } else if (size == 0) {
2082 error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2083 g_free(path);
2084 return;
2086 size = pow2ceil(size);
2088 vmsd = qdev_get_vmsd(DEVICE(pdev));
2090 if (vmsd) {
2091 snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2092 } else {
2093 snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2095 pdev->has_rom = true;
2096 memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_fatal);
2097 vmstate_register_ram(&pdev->rom, &pdev->qdev);
2098 ptr = memory_region_get_ram_ptr(&pdev->rom);
2099 load_image(path, ptr);
2100 g_free(path);
2102 if (is_default_rom) {
2103 /* Only the default rom images will be patched (if needed). */
2104 pci_patch_ids(pdev, ptr, size);
2107 pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2110 static void pci_del_option_rom(PCIDevice *pdev)
2112 if (!pdev->has_rom)
2113 return;
2115 vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2116 pdev->has_rom = false;
2120 * if offset = 0,
2121 * Find and reserve space and add capability to the linked list
2122 * in pci config space
2124 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2125 uint8_t offset, uint8_t size)
2127 int ret;
2128 Error *local_err = NULL;
2130 ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err);
2131 if (local_err) {
2132 assert(ret < 0);
2133 error_report_err(local_err);
2134 } else {
2135 /* success implies a positive offset in config space */
2136 assert(ret > 0);
2138 return ret;
2141 int pci_add_capability2(PCIDevice *pdev, uint8_t cap_id,
2142 uint8_t offset, uint8_t size,
2143 Error **errp)
2145 uint8_t *config;
2146 int i, overlapping_cap;
2148 if (!offset) {
2149 offset = pci_find_space(pdev, size);
2150 if (!offset) {
2151 error_setg(errp, "out of PCI config space");
2152 return -ENOSPC;
2154 } else {
2155 /* Verify that capabilities don't overlap. Note: device assignment
2156 * depends on this check to verify that the device is not broken.
2157 * Should never trigger for emulated devices, but it's helpful
2158 * for debugging these. */
2159 for (i = offset; i < offset + size; i++) {
2160 overlapping_cap = pci_find_capability_at_offset(pdev, i);
2161 if (overlapping_cap) {
2162 error_setg(errp, "%s:%02x:%02x.%x "
2163 "Attempt to add PCI capability %x at offset "
2164 "%x overlaps existing capability %x at offset %x",
2165 pci_root_bus_path(pdev), pci_bus_num(pdev->bus),
2166 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2167 cap_id, offset, overlapping_cap, i);
2168 return -EINVAL;
2173 config = pdev->config + offset;
2174 config[PCI_CAP_LIST_ID] = cap_id;
2175 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2176 pdev->config[PCI_CAPABILITY_LIST] = offset;
2177 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2178 memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2179 /* Make capability read-only by default */
2180 memset(pdev->wmask + offset, 0, size);
2181 /* Check capability by default */
2182 memset(pdev->cmask + offset, 0xFF, size);
2183 return offset;
2186 /* Unlink capability from the pci config space. */
2187 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2189 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2190 if (!offset)
2191 return;
2192 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2193 /* Make capability writable again */
2194 memset(pdev->wmask + offset, 0xff, size);
2195 memset(pdev->w1cmask + offset, 0, size);
2196 /* Clear cmask as device-specific registers can't be checked */
2197 memset(pdev->cmask + offset, 0, size);
2198 memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2200 if (!pdev->config[PCI_CAPABILITY_LIST])
2201 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2204 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2206 return pci_find_capability_list(pdev, cap_id, NULL);
2209 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2211 PCIDevice *d = (PCIDevice *)dev;
2212 const pci_class_desc *desc;
2213 char ctxt[64];
2214 PCIIORegion *r;
2215 int i, class;
2217 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2218 desc = pci_class_descriptions;
2219 while (desc->desc && class != desc->class)
2220 desc++;
2221 if (desc->desc) {
2222 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2223 } else {
2224 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2227 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2228 "pci id %04x:%04x (sub %04x:%04x)\n",
2229 indent, "", ctxt, pci_bus_num(d->bus),
2230 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2231 pci_get_word(d->config + PCI_VENDOR_ID),
2232 pci_get_word(d->config + PCI_DEVICE_ID),
2233 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2234 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2235 for (i = 0; i < PCI_NUM_REGIONS; i++) {
2236 r = &d->io_regions[i];
2237 if (!r->size)
2238 continue;
2239 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2240 " [0x%"FMT_PCIBUS"]\n",
2241 indent, "",
2242 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2243 r->addr, r->addr + r->size - 1);
2247 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2249 PCIDevice *d = (PCIDevice *)dev;
2250 const char *name = NULL;
2251 const pci_class_desc *desc = pci_class_descriptions;
2252 int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2254 while (desc->desc &&
2255 (class & ~desc->fw_ign_bits) !=
2256 (desc->class & ~desc->fw_ign_bits)) {
2257 desc++;
2260 if (desc->desc) {
2261 name = desc->fw_name;
2264 if (name) {
2265 pstrcpy(buf, len, name);
2266 } else {
2267 snprintf(buf, len, "pci%04x,%04x",
2268 pci_get_word(d->config + PCI_VENDOR_ID),
2269 pci_get_word(d->config + PCI_DEVICE_ID));
2272 return buf;
2275 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2277 PCIDevice *d = (PCIDevice *)dev;
2278 char path[50], name[33];
2279 int off;
2281 off = snprintf(path, sizeof(path), "%s@%x",
2282 pci_dev_fw_name(dev, name, sizeof name),
2283 PCI_SLOT(d->devfn));
2284 if (PCI_FUNC(d->devfn))
2285 snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2286 return g_strdup(path);
2289 static char *pcibus_get_dev_path(DeviceState *dev)
2291 PCIDevice *d = container_of(dev, PCIDevice, qdev);
2292 PCIDevice *t;
2293 int slot_depth;
2294 /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2295 * 00 is added here to make this format compatible with
2296 * domain:Bus:Slot.Func for systems without nested PCI bridges.
2297 * Slot.Function list specifies the slot and function numbers for all
2298 * devices on the path from root to the specific device. */
2299 const char *root_bus_path;
2300 int root_bus_len;
2301 char slot[] = ":SS.F";
2302 int slot_len = sizeof slot - 1 /* For '\0' */;
2303 int path_len;
2304 char *path, *p;
2305 int s;
2307 root_bus_path = pci_root_bus_path(d);
2308 root_bus_len = strlen(root_bus_path);
2310 /* Calculate # of slots on path between device and root. */;
2311 slot_depth = 0;
2312 for (t = d; t; t = t->bus->parent_dev) {
2313 ++slot_depth;
2316 path_len = root_bus_len + slot_len * slot_depth;
2318 /* Allocate memory, fill in the terminating null byte. */
2319 path = g_malloc(path_len + 1 /* For '\0' */);
2320 path[path_len] = '\0';
2322 memcpy(path, root_bus_path, root_bus_len);
2324 /* Fill in slot numbers. We walk up from device to root, so need to print
2325 * them in the reverse order, last to first. */
2326 p = path + path_len;
2327 for (t = d; t; t = t->bus->parent_dev) {
2328 p -= slot_len;
2329 s = snprintf(slot, sizeof slot, ":%02x.%x",
2330 PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2331 assert(s == slot_len);
2332 memcpy(p, slot, slot_len);
2335 return path;
2338 static int pci_qdev_find_recursive(PCIBus *bus,
2339 const char *id, PCIDevice **pdev)
2341 DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2342 if (!qdev) {
2343 return -ENODEV;
2346 /* roughly check if given qdev is pci device */
2347 if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2348 *pdev = PCI_DEVICE(qdev);
2349 return 0;
2351 return -EINVAL;
2354 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2356 PCIHostState *host_bridge;
2357 int rc = -ENODEV;
2359 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2360 int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2361 if (!tmp) {
2362 rc = 0;
2363 break;
2365 if (tmp != -ENODEV) {
2366 rc = tmp;
2370 return rc;
2373 MemoryRegion *pci_address_space(PCIDevice *dev)
2375 return dev->bus->address_space_mem;
2378 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2380 return dev->bus->address_space_io;
2383 static void pci_device_class_init(ObjectClass *klass, void *data)
2385 DeviceClass *k = DEVICE_CLASS(klass);
2386 PCIDeviceClass *pc = PCI_DEVICE_CLASS(klass);
2388 k->realize = pci_qdev_realize;
2389 k->unrealize = pci_qdev_unrealize;
2390 k->bus_type = TYPE_PCI_BUS;
2391 k->props = pci_props;
2392 pc->realize = pci_default_realize;
2395 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2397 PCIBus *bus = PCI_BUS(dev->bus);
2398 PCIBus *iommu_bus = bus;
2400 while(iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2401 iommu_bus = PCI_BUS(iommu_bus->parent_dev->bus);
2403 if (iommu_bus && iommu_bus->iommu_fn) {
2404 return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, dev->devfn);
2406 return &address_space_memory;
2409 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2411 bus->iommu_fn = fn;
2412 bus->iommu_opaque = opaque;
2415 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2417 Range *range = opaque;
2418 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2419 uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2420 int i;
2422 if (!(cmd & PCI_COMMAND_MEMORY)) {
2423 return;
2426 if (pc->is_bridge) {
2427 pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2428 pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2430 base = MAX(base, 0x1ULL << 32);
2432 if (limit >= base) {
2433 Range pref_range;
2434 pref_range.begin = base;
2435 pref_range.end = limit + 1;
2436 range_extend(range, &pref_range);
2439 for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2440 PCIIORegion *r = &dev->io_regions[i];
2441 Range region_range;
2443 if (!r->size ||
2444 (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2445 !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2446 continue;
2448 region_range.begin = pci_bar_address(dev, i, r->type, r->size);
2449 region_range.end = region_range.begin + r->size;
2451 if (region_range.begin == PCI_BAR_UNMAPPED) {
2452 continue;
2455 region_range.begin = MAX(region_range.begin, 0x1ULL << 32);
2457 if (region_range.end - 1 >= region_range.begin) {
2458 range_extend(range, &region_range);
2463 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2465 range->begin = range->end = 0;
2466 pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2469 static bool pcie_has_upstream_port(PCIDevice *dev)
2471 PCIDevice *parent_dev = pci_bridge_get_device(dev->bus);
2473 /* Device associated with an upstream port.
2474 * As there are several types of these, it's easier to check the
2475 * parent device: upstream ports are always connected to
2476 * root or downstream ports.
2478 return parent_dev &&
2479 pci_is_express(parent_dev) &&
2480 parent_dev->exp.exp_cap &&
2481 (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2482 pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2485 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2487 if(pcie_has_upstream_port(pci_dev)) {
2488 /* With an upstream PCIe port, we only support 1 device at slot 0 */
2489 return pci_dev->bus->devices[0];
2490 } else {
2491 /* Other bus types might support multiple devices at slots 0-31 */
2492 return pci_dev->bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2496 static const TypeInfo pci_device_type_info = {
2497 .name = TYPE_PCI_DEVICE,
2498 .parent = TYPE_DEVICE,
2499 .instance_size = sizeof(PCIDevice),
2500 .abstract = true,
2501 .class_size = sizeof(PCIDeviceClass),
2502 .class_init = pci_device_class_init,
2505 static void pci_register_types(void)
2507 type_register_static(&pci_bus_info);
2508 type_register_static(&pcie_bus_info);
2509 type_register_static(&pci_device_type_info);
2512 type_init(pci_register_types)