pci: Automatically patch PCI vendor id and device id in PCI ROM
[qemu/stefanha.git] / hw / pci.c
blobc0a825876a28db0c15f51a414f10ee50616afb3c
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.h"
25 #include "pci.h"
26 #include "pci_bridge.h"
27 #include "pci_internals.h"
28 #include "msix.h"
29 #include "msi.h"
30 #include "monitor.h"
31 #include "net.h"
32 #include "sysemu.h"
33 #include "loader.h"
34 #include "qemu-objects.h"
35 #include "range.h"
37 //#define DEBUG_PCI
38 #ifdef DEBUG_PCI
39 # define PCI_DPRINTF(format, ...) printf(format, ## __VA_ARGS__)
40 #else
41 # define PCI_DPRINTF(format, ...) do { } while (0)
42 #endif
44 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
45 static char *pcibus_get_dev_path(DeviceState *dev);
47 struct BusInfo pci_bus_info = {
48 .name = "PCI",
49 .size = sizeof(PCIBus),
50 .print_dev = pcibus_dev_print,
51 .get_dev_path = pcibus_get_dev_path,
52 .props = (Property[]) {
53 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
54 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
55 DEFINE_PROP_UINT32("rombar", PCIDevice, rom_bar, 1),
56 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
57 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
58 DEFINE_PROP_END_OF_LIST()
62 static void pci_update_mappings(PCIDevice *d);
63 static void pci_set_irq(void *opaque, int irq_num, int level);
64 static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom);
65 static void pci_del_option_rom(PCIDevice *pdev);
67 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
68 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
70 struct PCIHostBus {
71 int domain;
72 struct PCIBus *bus;
73 QLIST_ENTRY(PCIHostBus) next;
75 static QLIST_HEAD(, PCIHostBus) host_buses;
77 static const VMStateDescription vmstate_pcibus = {
78 .name = "PCIBUS",
79 .version_id = 1,
80 .minimum_version_id = 1,
81 .minimum_version_id_old = 1,
82 .fields = (VMStateField []) {
83 VMSTATE_INT32_EQUAL(nirq, PCIBus),
84 VMSTATE_VARRAY_INT32(irq_count, PCIBus, nirq, 0, vmstate_info_int32, int32_t),
85 VMSTATE_END_OF_LIST()
89 static int pci_bar(PCIDevice *d, int reg)
91 uint8_t type;
93 if (reg != PCI_ROM_SLOT)
94 return PCI_BASE_ADDRESS_0 + reg * 4;
96 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
97 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
100 static inline int pci_irq_state(PCIDevice *d, int irq_num)
102 return (d->irq_state >> irq_num) & 0x1;
105 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
107 d->irq_state &= ~(0x1 << irq_num);
108 d->irq_state |= level << irq_num;
111 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
113 PCIBus *bus;
114 for (;;) {
115 bus = pci_dev->bus;
116 irq_num = bus->map_irq(pci_dev, irq_num);
117 if (bus->set_irq)
118 break;
119 pci_dev = bus->parent_dev;
121 bus->irq_count[irq_num] += change;
122 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
125 /* Update interrupt status bit in config space on interrupt
126 * state change. */
127 static void pci_update_irq_status(PCIDevice *dev)
129 if (dev->irq_state) {
130 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
131 } else {
132 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
136 static void pci_device_reset(PCIDevice *dev)
138 int r;
140 dev->irq_state = 0;
141 pci_update_irq_status(dev);
142 /* Clear all writeable bits */
143 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
144 pci_get_word(dev->wmask + PCI_COMMAND) |
145 pci_get_word(dev->w1cmask + PCI_COMMAND));
146 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
147 pci_get_word(dev->wmask + PCI_STATUS) |
148 pci_get_word(dev->w1cmask + PCI_STATUS));
149 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
150 dev->config[PCI_INTERRUPT_LINE] = 0x0;
151 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
152 PCIIORegion *region = &dev->io_regions[r];
153 if (!region->size) {
154 continue;
157 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
158 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
159 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
160 } else {
161 pci_set_long(dev->config + pci_bar(dev, r), region->type);
164 pci_update_mappings(dev);
167 static void pci_bus_reset(void *opaque)
169 PCIBus *bus = opaque;
170 int i;
172 for (i = 0; i < bus->nirq; i++) {
173 bus->irq_count[i] = 0;
175 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
176 if (bus->devices[i]) {
177 pci_device_reset(bus->devices[i]);
182 static void pci_host_bus_register(int domain, PCIBus *bus)
184 struct PCIHostBus *host;
185 host = qemu_mallocz(sizeof(*host));
186 host->domain = domain;
187 host->bus = bus;
188 QLIST_INSERT_HEAD(&host_buses, host, next);
191 PCIBus *pci_find_root_bus(int domain)
193 struct PCIHostBus *host;
195 QLIST_FOREACH(host, &host_buses, next) {
196 if (host->domain == domain) {
197 return host->bus;
201 return NULL;
204 int pci_find_domain(const PCIBus *bus)
206 PCIDevice *d;
207 struct PCIHostBus *host;
209 /* obtain root bus */
210 while ((d = bus->parent_dev) != NULL) {
211 bus = d->bus;
214 QLIST_FOREACH(host, &host_buses, next) {
215 if (host->bus == bus) {
216 return host->domain;
220 abort(); /* should not be reached */
221 return -1;
224 void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
225 const char *name, int devfn_min)
227 qbus_create_inplace(&bus->qbus, &pci_bus_info, parent, name);
228 assert(PCI_FUNC(devfn_min) == 0);
229 bus->devfn_min = devfn_min;
231 /* host bridge */
232 QLIST_INIT(&bus->child);
233 pci_host_bus_register(0, bus); /* for now only pci domain 0 is supported */
235 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
236 qemu_register_reset(pci_bus_reset, bus);
239 PCIBus *pci_bus_new(DeviceState *parent, const char *name, int devfn_min)
241 PCIBus *bus;
243 bus = qemu_mallocz(sizeof(*bus));
244 bus->qbus.qdev_allocated = 1;
245 pci_bus_new_inplace(bus, parent, name, devfn_min);
246 return bus;
249 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
250 void *irq_opaque, int nirq)
252 bus->set_irq = set_irq;
253 bus->map_irq = map_irq;
254 bus->irq_opaque = irq_opaque;
255 bus->nirq = nirq;
256 bus->irq_count = qemu_mallocz(nirq * sizeof(bus->irq_count[0]));
259 void pci_bus_hotplug(PCIBus *bus, pci_hotplug_fn hotplug, DeviceState *qdev)
261 bus->qbus.allow_hotplug = 1;
262 bus->hotplug = hotplug;
263 bus->hotplug_qdev = qdev;
266 void pci_bus_set_mem_base(PCIBus *bus, target_phys_addr_t base)
268 bus->mem_base = base;
271 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
272 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
273 void *irq_opaque, int devfn_min, int nirq)
275 PCIBus *bus;
277 bus = pci_bus_new(parent, name, devfn_min);
278 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
279 return bus;
282 int pci_bus_num(PCIBus *s)
284 if (!s->parent_dev)
285 return 0; /* pci host bridge */
286 return s->parent_dev->config[PCI_SECONDARY_BUS];
289 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
291 PCIDevice *s = container_of(pv, PCIDevice, config);
292 uint8_t *config;
293 int i;
295 assert(size == pci_config_size(s));
296 config = qemu_malloc(size);
298 qemu_get_buffer(f, config, size);
299 for (i = 0; i < size; ++i) {
300 if ((config[i] ^ s->config[i]) &
301 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
302 qemu_free(config);
303 return -EINVAL;
306 memcpy(s->config, config, size);
308 pci_update_mappings(s);
310 qemu_free(config);
311 return 0;
314 /* just put buffer */
315 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
317 const uint8_t **v = pv;
318 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
319 qemu_put_buffer(f, *v, size);
322 static VMStateInfo vmstate_info_pci_config = {
323 .name = "pci config",
324 .get = get_pci_config_device,
325 .put = put_pci_config_device,
328 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
330 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
331 uint32_t irq_state[PCI_NUM_PINS];
332 int i;
333 for (i = 0; i < PCI_NUM_PINS; ++i) {
334 irq_state[i] = qemu_get_be32(f);
335 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
336 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
337 irq_state[i]);
338 return -EINVAL;
342 for (i = 0; i < PCI_NUM_PINS; ++i) {
343 pci_set_irq_state(s, i, irq_state[i]);
346 return 0;
349 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
351 int i;
352 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
354 for (i = 0; i < PCI_NUM_PINS; ++i) {
355 qemu_put_be32(f, pci_irq_state(s, i));
359 static VMStateInfo vmstate_info_pci_irq_state = {
360 .name = "pci irq state",
361 .get = get_pci_irq_state,
362 .put = put_pci_irq_state,
365 const VMStateDescription vmstate_pci_device = {
366 .name = "PCIDevice",
367 .version_id = 2,
368 .minimum_version_id = 1,
369 .minimum_version_id_old = 1,
370 .fields = (VMStateField []) {
371 VMSTATE_INT32_LE(version_id, PCIDevice),
372 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
373 vmstate_info_pci_config,
374 PCI_CONFIG_SPACE_SIZE),
375 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
376 vmstate_info_pci_irq_state,
377 PCI_NUM_PINS * sizeof(int32_t)),
378 VMSTATE_END_OF_LIST()
382 const VMStateDescription vmstate_pcie_device = {
383 .name = "PCIDevice",
384 .version_id = 2,
385 .minimum_version_id = 1,
386 .minimum_version_id_old = 1,
387 .fields = (VMStateField []) {
388 VMSTATE_INT32_LE(version_id, PCIDevice),
389 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
390 vmstate_info_pci_config,
391 PCIE_CONFIG_SPACE_SIZE),
392 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
393 vmstate_info_pci_irq_state,
394 PCI_NUM_PINS * sizeof(int32_t)),
395 VMSTATE_END_OF_LIST()
399 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
401 return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
404 void pci_device_save(PCIDevice *s, QEMUFile *f)
406 /* Clear interrupt status bit: it is implicit
407 * in irq_state which we are saving.
408 * This makes us compatible with old devices
409 * which never set or clear this bit. */
410 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
411 vmstate_save_state(f, pci_get_vmstate(s), s);
412 /* Restore the interrupt status bit. */
413 pci_update_irq_status(s);
416 int pci_device_load(PCIDevice *s, QEMUFile *f)
418 int ret;
419 ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
420 /* Restore the interrupt status bit. */
421 pci_update_irq_status(s);
422 return ret;
425 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
427 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
428 pci_default_sub_vendor_id);
429 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
430 pci_default_sub_device_id);
434 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
435 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
437 int pci_parse_devaddr(const char *addr, int *domp, int *busp,
438 unsigned int *slotp, unsigned int *funcp)
440 const char *p;
441 char *e;
442 unsigned long val;
443 unsigned long dom = 0, bus = 0;
444 unsigned int slot = 0;
445 unsigned int func = 0;
447 p = addr;
448 val = strtoul(p, &e, 16);
449 if (e == p)
450 return -1;
451 if (*e == ':') {
452 bus = val;
453 p = e + 1;
454 val = strtoul(p, &e, 16);
455 if (e == p)
456 return -1;
457 if (*e == ':') {
458 dom = bus;
459 bus = val;
460 p = e + 1;
461 val = strtoul(p, &e, 16);
462 if (e == p)
463 return -1;
467 slot = val;
469 if (funcp != NULL) {
470 if (*e != '.')
471 return -1;
473 p = e + 1;
474 val = strtoul(p, &e, 16);
475 if (e == p)
476 return -1;
478 func = val;
481 /* if funcp == NULL func is 0 */
482 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
483 return -1;
485 if (*e)
486 return -1;
488 /* Note: QEMU doesn't implement domains other than 0 */
489 if (!pci_find_bus(pci_find_root_bus(dom), bus))
490 return -1;
492 *domp = dom;
493 *busp = bus;
494 *slotp = slot;
495 if (funcp != NULL)
496 *funcp = func;
497 return 0;
500 int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
501 unsigned *slotp)
503 /* strip legacy tag */
504 if (!strncmp(addr, "pci_addr=", 9)) {
505 addr += 9;
507 if (pci_parse_devaddr(addr, domp, busp, slotp, NULL)) {
508 monitor_printf(mon, "Invalid pci address\n");
509 return -1;
511 return 0;
514 PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
516 int dom, bus;
517 unsigned slot;
519 if (!devaddr) {
520 *devfnp = -1;
521 return pci_find_bus(pci_find_root_bus(0), 0);
524 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
525 return NULL;
528 *devfnp = slot << 3;
529 return pci_find_bus(pci_find_root_bus(dom), bus);
532 static void pci_init_cmask(PCIDevice *dev)
534 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
535 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
536 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
537 dev->cmask[PCI_REVISION_ID] = 0xff;
538 dev->cmask[PCI_CLASS_PROG] = 0xff;
539 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
540 dev->cmask[PCI_HEADER_TYPE] = 0xff;
541 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
544 static void pci_init_wmask(PCIDevice *dev)
546 int config_size = pci_config_size(dev);
548 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
549 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
550 pci_set_word(dev->wmask + PCI_COMMAND,
551 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
552 PCI_COMMAND_INTX_DISABLE);
554 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
555 config_size - PCI_CONFIG_HEADER_SIZE);
558 static void pci_init_w1cmask(PCIDevice *dev)
561 * Note: It's okay to set w1cmask even for readonly bits as
562 * long as their value is hardwired to 0.
564 pci_set_word(dev->w1cmask + PCI_STATUS,
565 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
566 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
567 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
570 static void pci_init_wmask_bridge(PCIDevice *d)
572 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
573 PCI_SEC_LETENCY_TIMER */
574 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
576 /* base and limit */
577 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
578 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
579 pci_set_word(d->wmask + PCI_MEMORY_BASE,
580 PCI_MEMORY_RANGE_MASK & 0xffff);
581 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
582 PCI_MEMORY_RANGE_MASK & 0xffff);
583 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
584 PCI_PREF_RANGE_MASK & 0xffff);
585 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
586 PCI_PREF_RANGE_MASK & 0xffff);
588 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
589 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
591 /* TODO: add this define to pci_regs.h in linux and then in qemu. */
592 #define PCI_BRIDGE_CTL_VGA_16BIT 0x10 /* VGA 16-bit decode */
593 #define PCI_BRIDGE_CTL_DISCARD 0x100 /* Primary discard timer */
594 #define PCI_BRIDGE_CTL_SEC_DISCARD 0x200 /* Secondary discard timer */
595 #define PCI_BRIDGE_CTL_DISCARD_STATUS 0x400 /* Discard timer status */
596 #define PCI_BRIDGE_CTL_DISCARD_SERR 0x800 /* Discard timer SERR# enable */
597 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
598 PCI_BRIDGE_CTL_PARITY |
599 PCI_BRIDGE_CTL_SERR |
600 PCI_BRIDGE_CTL_ISA |
601 PCI_BRIDGE_CTL_VGA |
602 PCI_BRIDGE_CTL_VGA_16BIT |
603 PCI_BRIDGE_CTL_MASTER_ABORT |
604 PCI_BRIDGE_CTL_BUS_RESET |
605 PCI_BRIDGE_CTL_FAST_BACK |
606 PCI_BRIDGE_CTL_DISCARD |
607 PCI_BRIDGE_CTL_SEC_DISCARD |
608 PCI_BRIDGE_CTL_DISCARD_STATUS |
609 PCI_BRIDGE_CTL_DISCARD_SERR);
610 /* Below does not do anything as we never set this bit, put here for
611 * completeness. */
612 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
613 PCI_BRIDGE_CTL_DISCARD_STATUS);
616 static int pci_init_multifunction(PCIBus *bus, PCIDevice *dev)
618 uint8_t slot = PCI_SLOT(dev->devfn);
619 uint8_t func;
621 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
622 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
626 * multifunction bit is interpreted in two ways as follows.
627 * - all functions must set the bit to 1.
628 * Example: Intel X53
629 * - function 0 must set the bit, but the rest function (> 0)
630 * is allowed to leave the bit to 0.
631 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
633 * So OS (at least Linux) checks the bit of only function 0,
634 * and doesn't see the bit of function > 0.
636 * The below check allows both interpretation.
638 if (PCI_FUNC(dev->devfn)) {
639 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
640 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
641 /* function 0 should set multifunction bit */
642 error_report("PCI: single function device can't be populated "
643 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
644 return -1;
646 return 0;
649 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
650 return 0;
652 /* function 0 indicates single function, so function > 0 must be NULL */
653 for (func = 1; func < PCI_FUNC_MAX; ++func) {
654 if (bus->devices[PCI_DEVFN(slot, func)]) {
655 error_report("PCI: %x.0 indicates single function, "
656 "but %x.%x is already populated.",
657 slot, slot, func);
658 return -1;
661 return 0;
664 static void pci_config_alloc(PCIDevice *pci_dev)
666 int config_size = pci_config_size(pci_dev);
668 pci_dev->config = qemu_mallocz(config_size);
669 pci_dev->cmask = qemu_mallocz(config_size);
670 pci_dev->wmask = qemu_mallocz(config_size);
671 pci_dev->w1cmask = qemu_mallocz(config_size);
672 pci_dev->used = qemu_mallocz(config_size);
675 static void pci_config_free(PCIDevice *pci_dev)
677 qemu_free(pci_dev->config);
678 qemu_free(pci_dev->cmask);
679 qemu_free(pci_dev->wmask);
680 qemu_free(pci_dev->w1cmask);
681 qemu_free(pci_dev->used);
684 /* -1 for devfn means auto assign */
685 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
686 const char *name, int devfn,
687 PCIConfigReadFunc *config_read,
688 PCIConfigWriteFunc *config_write,
689 bool is_bridge)
691 if (devfn < 0) {
692 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
693 devfn += PCI_FUNC_MAX) {
694 if (!bus->devices[devfn])
695 goto found;
697 error_report("PCI: no slot/function available for %s, all in use", name);
698 return NULL;
699 found: ;
700 } else if (bus->devices[devfn]) {
701 error_report("PCI: slot %d function %d not available for %s, in use by %s",
702 PCI_SLOT(devfn), PCI_FUNC(devfn), name, bus->devices[devfn]->name);
703 return NULL;
705 pci_dev->bus = bus;
706 pci_dev->devfn = devfn;
707 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
708 pci_dev->irq_state = 0;
709 pci_config_alloc(pci_dev);
711 if (!is_bridge) {
712 pci_set_default_subsystem_id(pci_dev);
714 pci_init_cmask(pci_dev);
715 pci_init_wmask(pci_dev);
716 pci_init_w1cmask(pci_dev);
717 if (is_bridge) {
718 pci_init_wmask_bridge(pci_dev);
720 if (pci_init_multifunction(bus, pci_dev)) {
721 pci_config_free(pci_dev);
722 return NULL;
725 if (!config_read)
726 config_read = pci_default_read_config;
727 if (!config_write)
728 config_write = pci_default_write_config;
729 pci_dev->config_read = config_read;
730 pci_dev->config_write = config_write;
731 bus->devices[devfn] = pci_dev;
732 pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
733 pci_dev->version_id = 2; /* Current pci device vmstate version */
734 return pci_dev;
737 static void do_pci_unregister_device(PCIDevice *pci_dev)
739 qemu_free_irqs(pci_dev->irq);
740 pci_dev->bus->devices[pci_dev->devfn] = NULL;
741 pci_config_free(pci_dev);
744 PCIDevice *pci_register_device(PCIBus *bus, const char *name,
745 int instance_size, int devfn,
746 PCIConfigReadFunc *config_read,
747 PCIConfigWriteFunc *config_write)
749 PCIDevice *pci_dev;
751 pci_dev = qemu_mallocz(instance_size);
752 pci_dev = do_pci_register_device(pci_dev, bus, name, devfn,
753 config_read, config_write,
754 PCI_HEADER_TYPE_NORMAL);
755 if (pci_dev == NULL) {
756 hw_error("PCI: can't register device\n");
758 return pci_dev;
761 static target_phys_addr_t pci_to_cpu_addr(PCIBus *bus,
762 target_phys_addr_t addr)
764 return addr + bus->mem_base;
767 static void pci_unregister_io_regions(PCIDevice *pci_dev)
769 PCIIORegion *r;
770 int i;
772 for(i = 0; i < PCI_NUM_REGIONS; i++) {
773 r = &pci_dev->io_regions[i];
774 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
775 continue;
776 if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
777 isa_unassign_ioport(r->addr, r->filtered_size);
778 } else {
779 cpu_register_physical_memory(pci_to_cpu_addr(pci_dev->bus,
780 r->addr),
781 r->filtered_size,
782 IO_MEM_UNASSIGNED);
787 static int pci_unregister_device(DeviceState *dev)
789 PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
790 PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
791 int ret = 0;
793 if (info->exit)
794 ret = info->exit(pci_dev);
795 if (ret)
796 return ret;
798 pci_unregister_io_regions(pci_dev);
799 pci_del_option_rom(pci_dev);
800 do_pci_unregister_device(pci_dev);
801 return 0;
804 void pci_register_bar(PCIDevice *pci_dev, int region_num,
805 pcibus_t size, uint8_t type,
806 PCIMapIORegionFunc *map_func)
808 PCIIORegion *r;
809 uint32_t addr;
810 uint64_t wmask;
812 assert(region_num >= 0);
813 assert(region_num < PCI_NUM_REGIONS);
814 if (size & (size-1)) {
815 fprintf(stderr, "ERROR: PCI region size must be pow2 "
816 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
817 exit(1);
820 r = &pci_dev->io_regions[region_num];
821 r->addr = PCI_BAR_UNMAPPED;
822 r->size = size;
823 r->filtered_size = size;
824 r->type = type;
825 r->map_func = map_func;
827 wmask = ~(size - 1);
828 addr = pci_bar(pci_dev, region_num);
829 if (region_num == PCI_ROM_SLOT) {
830 /* ROM enable bit is writeable */
831 wmask |= PCI_ROM_ADDRESS_ENABLE;
833 pci_set_long(pci_dev->config + addr, type);
834 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
835 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
836 pci_set_quad(pci_dev->wmask + addr, wmask);
837 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
838 } else {
839 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
840 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
844 static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
845 uint8_t type)
847 pcibus_t base = *addr;
848 pcibus_t limit = *addr + *size - 1;
849 PCIDevice *br;
851 for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
852 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
854 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
855 if (!(cmd & PCI_COMMAND_IO)) {
856 goto no_map;
858 } else {
859 if (!(cmd & PCI_COMMAND_MEMORY)) {
860 goto no_map;
864 base = MAX(base, pci_bridge_get_base(br, type));
865 limit = MIN(limit, pci_bridge_get_limit(br, type));
868 if (base > limit) {
869 goto no_map;
871 *addr = base;
872 *size = limit - base + 1;
873 return;
874 no_map:
875 *addr = PCI_BAR_UNMAPPED;
876 *size = 0;
879 static pcibus_t pci_bar_address(PCIDevice *d,
880 int reg, uint8_t type, pcibus_t size)
882 pcibus_t new_addr, last_addr;
883 int bar = pci_bar(d, reg);
884 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
886 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
887 if (!(cmd & PCI_COMMAND_IO)) {
888 return PCI_BAR_UNMAPPED;
890 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
891 last_addr = new_addr + size - 1;
892 /* NOTE: we have only 64K ioports on PC */
893 if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
894 return PCI_BAR_UNMAPPED;
896 return new_addr;
899 if (!(cmd & PCI_COMMAND_MEMORY)) {
900 return PCI_BAR_UNMAPPED;
902 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
903 new_addr = pci_get_quad(d->config + bar);
904 } else {
905 new_addr = pci_get_long(d->config + bar);
907 /* the ROM slot has a specific enable bit */
908 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
909 return PCI_BAR_UNMAPPED;
911 new_addr &= ~(size - 1);
912 last_addr = new_addr + size - 1;
913 /* NOTE: we do not support wrapping */
914 /* XXX: as we cannot support really dynamic
915 mappings, we handle specific values as invalid
916 mappings. */
917 if (last_addr <= new_addr || new_addr == 0 ||
918 last_addr == PCI_BAR_UNMAPPED) {
919 return PCI_BAR_UNMAPPED;
922 /* Now pcibus_t is 64bit.
923 * Check if 32 bit BAR wraps around explicitly.
924 * Without this, PC ide doesn't work well.
925 * TODO: remove this work around.
927 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
928 return PCI_BAR_UNMAPPED;
932 * OS is allowed to set BAR beyond its addressable
933 * bits. For example, 32 bit OS can set 64bit bar
934 * to >4G. Check it. TODO: we might need to support
935 * it in the future for e.g. PAE.
937 if (last_addr >= TARGET_PHYS_ADDR_MAX) {
938 return PCI_BAR_UNMAPPED;
941 return new_addr;
944 static void pci_update_mappings(PCIDevice *d)
946 PCIIORegion *r;
947 int i;
948 pcibus_t new_addr, filtered_size;
950 for(i = 0; i < PCI_NUM_REGIONS; i++) {
951 r = &d->io_regions[i];
953 /* this region isn't registered */
954 if (!r->size)
955 continue;
957 new_addr = pci_bar_address(d, i, r->type, r->size);
959 /* bridge filtering */
960 filtered_size = r->size;
961 if (new_addr != PCI_BAR_UNMAPPED) {
962 pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
965 /* This bar isn't changed */
966 if (new_addr == r->addr && filtered_size == r->filtered_size)
967 continue;
969 /* now do the real mapping */
970 if (r->addr != PCI_BAR_UNMAPPED) {
971 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
972 int class;
973 /* NOTE: specific hack for IDE in PC case:
974 only one byte must be mapped. */
975 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
976 if (class == 0x0101 && r->size == 4) {
977 isa_unassign_ioport(r->addr + 2, 1);
978 } else {
979 isa_unassign_ioport(r->addr, r->filtered_size);
981 } else {
982 cpu_register_physical_memory(pci_to_cpu_addr(d->bus, r->addr),
983 r->filtered_size,
984 IO_MEM_UNASSIGNED);
985 qemu_unregister_coalesced_mmio(r->addr, r->filtered_size);
988 r->addr = new_addr;
989 r->filtered_size = filtered_size;
990 if (r->addr != PCI_BAR_UNMAPPED) {
992 * TODO: currently almost all the map funcions assumes
993 * filtered_size == size and addr & ~(size - 1) == addr.
994 * However with bridge filtering, they aren't always true.
995 * Teach them such cases, such that filtered_size < size and
996 * addr & (size - 1) != 0.
998 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
999 r->map_func(d, i, r->addr, r->filtered_size, r->type);
1000 } else {
1001 r->map_func(d, i, pci_to_cpu_addr(d->bus, r->addr),
1002 r->filtered_size, r->type);
1008 static inline int pci_irq_disabled(PCIDevice *d)
1010 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1013 /* Called after interrupt disabled field update in config space,
1014 * assert/deassert interrupts if necessary.
1015 * Gets original interrupt disable bit value (before update). */
1016 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1018 int i, disabled = pci_irq_disabled(d);
1019 if (disabled == was_irq_disabled)
1020 return;
1021 for (i = 0; i < PCI_NUM_PINS; ++i) {
1022 int state = pci_irq_state(d, i);
1023 pci_change_irq_level(d, i, disabled ? -state : state);
1027 uint32_t pci_default_read_config(PCIDevice *d,
1028 uint32_t address, int len)
1030 uint32_t val = 0;
1031 assert(len == 1 || len == 2 || len == 4);
1032 len = MIN(len, pci_config_size(d) - address);
1033 memcpy(&val, d->config + address, len);
1034 return le32_to_cpu(val);
1037 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
1039 int i, was_irq_disabled = pci_irq_disabled(d);
1040 uint32_t config_size = pci_config_size(d);
1042 for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
1043 uint8_t wmask = d->wmask[addr + i];
1044 uint8_t w1cmask = d->w1cmask[addr + i];
1045 assert(!(wmask & w1cmask));
1046 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1047 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1049 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1050 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1051 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1052 range_covers_byte(addr, l, PCI_COMMAND))
1053 pci_update_mappings(d);
1055 if (range_covers_byte(addr, l, PCI_COMMAND))
1056 pci_update_irq_disabled(d, was_irq_disabled);
1059 /***********************************************************/
1060 /* generic PCI irq support */
1062 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1063 static void pci_set_irq(void *opaque, int irq_num, int level)
1065 PCIDevice *pci_dev = opaque;
1066 int change;
1068 change = level - pci_irq_state(pci_dev, irq_num);
1069 if (!change)
1070 return;
1072 pci_set_irq_state(pci_dev, irq_num, level);
1073 pci_update_irq_status(pci_dev);
1074 if (pci_irq_disabled(pci_dev))
1075 return;
1076 pci_change_irq_level(pci_dev, irq_num, change);
1079 bool pci_msi_enabled(PCIDevice *dev)
1081 return msix_enabled(dev) || msi_enabled(dev);
1084 void pci_msi_notify(PCIDevice *dev, unsigned int vector)
1086 if (msix_enabled(dev)) {
1087 msix_notify(dev, vector);
1088 } else if (msi_enabled(dev)) {
1089 msi_notify(dev, vector);
1090 } else {
1091 /* MSI/MSI-X must be enabled */
1092 abort();
1096 /***********************************************************/
1097 /* monitor info on PCI */
1099 typedef struct {
1100 uint16_t class;
1101 const char *desc;
1102 } pci_class_desc;
1104 static const pci_class_desc pci_class_descriptions[] =
1106 { 0x0100, "SCSI controller"},
1107 { 0x0101, "IDE controller"},
1108 { 0x0102, "Floppy controller"},
1109 { 0x0103, "IPI controller"},
1110 { 0x0104, "RAID controller"},
1111 { 0x0106, "SATA controller"},
1112 { 0x0107, "SAS controller"},
1113 { 0x0180, "Storage controller"},
1114 { 0x0200, "Ethernet controller"},
1115 { 0x0201, "Token Ring controller"},
1116 { 0x0202, "FDDI controller"},
1117 { 0x0203, "ATM controller"},
1118 { 0x0280, "Network controller"},
1119 { 0x0300, "VGA controller"},
1120 { 0x0301, "XGA controller"},
1121 { 0x0302, "3D controller"},
1122 { 0x0380, "Display controller"},
1123 { 0x0400, "Video controller"},
1124 { 0x0401, "Audio controller"},
1125 { 0x0402, "Phone"},
1126 { 0x0480, "Multimedia controller"},
1127 { 0x0500, "RAM controller"},
1128 { 0x0501, "Flash controller"},
1129 { 0x0580, "Memory controller"},
1130 { 0x0600, "Host bridge"},
1131 { 0x0601, "ISA bridge"},
1132 { 0x0602, "EISA bridge"},
1133 { 0x0603, "MC bridge"},
1134 { 0x0604, "PCI bridge"},
1135 { 0x0605, "PCMCIA bridge"},
1136 { 0x0606, "NUBUS bridge"},
1137 { 0x0607, "CARDBUS bridge"},
1138 { 0x0608, "RACEWAY bridge"},
1139 { 0x0680, "Bridge"},
1140 { 0x0c03, "USB controller"},
1141 { 0, NULL}
1144 static void pci_for_each_device_under_bus(PCIBus *bus,
1145 void (*fn)(PCIBus *b, PCIDevice *d))
1147 PCIDevice *d;
1148 int devfn;
1150 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1151 d = bus->devices[devfn];
1152 if (d) {
1153 fn(bus, d);
1158 void pci_for_each_device(PCIBus *bus, int bus_num,
1159 void (*fn)(PCIBus *b, PCIDevice *d))
1161 bus = pci_find_bus(bus, bus_num);
1163 if (bus) {
1164 pci_for_each_device_under_bus(bus, fn);
1168 static void pci_device_print(Monitor *mon, QDict *device)
1170 QDict *qdict;
1171 QListEntry *entry;
1172 uint64_t addr, size;
1174 monitor_printf(mon, " Bus %2" PRId64 ", ", qdict_get_int(device, "bus"));
1175 monitor_printf(mon, "device %3" PRId64 ", function %" PRId64 ":\n",
1176 qdict_get_int(device, "slot"),
1177 qdict_get_int(device, "function"));
1178 monitor_printf(mon, " ");
1180 qdict = qdict_get_qdict(device, "class_info");
1181 if (qdict_haskey(qdict, "desc")) {
1182 monitor_printf(mon, "%s", qdict_get_str(qdict, "desc"));
1183 } else {
1184 monitor_printf(mon, "Class %04" PRId64, qdict_get_int(qdict, "class"));
1187 qdict = qdict_get_qdict(device, "id");
1188 monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
1189 qdict_get_int(qdict, "device"),
1190 qdict_get_int(qdict, "vendor"));
1192 if (qdict_haskey(device, "irq")) {
1193 monitor_printf(mon, " IRQ %" PRId64 ".\n",
1194 qdict_get_int(device, "irq"));
1197 if (qdict_haskey(device, "pci_bridge")) {
1198 QDict *info;
1200 qdict = qdict_get_qdict(device, "pci_bridge");
1202 info = qdict_get_qdict(qdict, "bus");
1203 monitor_printf(mon, " BUS %" PRId64 ".\n",
1204 qdict_get_int(info, "number"));
1205 monitor_printf(mon, " secondary bus %" PRId64 ".\n",
1206 qdict_get_int(info, "secondary"));
1207 monitor_printf(mon, " subordinate bus %" PRId64 ".\n",
1208 qdict_get_int(info, "subordinate"));
1210 info = qdict_get_qdict(qdict, "io_range");
1211 monitor_printf(mon, " IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1212 qdict_get_int(info, "base"),
1213 qdict_get_int(info, "limit"));
1215 info = qdict_get_qdict(qdict, "memory_range");
1216 monitor_printf(mon,
1217 " memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1218 qdict_get_int(info, "base"),
1219 qdict_get_int(info, "limit"));
1221 info = qdict_get_qdict(qdict, "prefetchable_range");
1222 monitor_printf(mon, " prefetchable memory range "
1223 "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
1224 qdict_get_int(info, "base"),
1225 qdict_get_int(info, "limit"));
1228 QLIST_FOREACH_ENTRY(qdict_get_qlist(device, "regions"), entry) {
1229 qdict = qobject_to_qdict(qlist_entry_obj(entry));
1230 monitor_printf(mon, " BAR%d: ", (int) qdict_get_int(qdict, "bar"));
1232 addr = qdict_get_int(qdict, "address");
1233 size = qdict_get_int(qdict, "size");
1235 if (!strcmp(qdict_get_str(qdict, "type"), "io")) {
1236 monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1237 " [0x%04"FMT_PCIBUS"].\n",
1238 addr, addr + size - 1);
1239 } else {
1240 monitor_printf(mon, "%d bit%s memory at 0x%08"FMT_PCIBUS
1241 " [0x%08"FMT_PCIBUS"].\n",
1242 qdict_get_bool(qdict, "mem_type_64") ? 64 : 32,
1243 qdict_get_bool(qdict, "prefetch") ?
1244 " prefetchable" : "", addr, addr + size - 1);
1248 monitor_printf(mon, " id \"%s\"\n", qdict_get_str(device, "qdev_id"));
1250 if (qdict_haskey(device, "pci_bridge")) {
1251 qdict = qdict_get_qdict(device, "pci_bridge");
1252 if (qdict_haskey(qdict, "devices")) {
1253 QListEntry *dev;
1254 QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1255 pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1261 void do_pci_info_print(Monitor *mon, const QObject *data)
1263 QListEntry *bus, *dev;
1265 QLIST_FOREACH_ENTRY(qobject_to_qlist(data), bus) {
1266 QDict *qdict = qobject_to_qdict(qlist_entry_obj(bus));
1267 QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1268 pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1273 static QObject *pci_get_dev_class(const PCIDevice *dev)
1275 int class;
1276 const pci_class_desc *desc;
1278 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1279 desc = pci_class_descriptions;
1280 while (desc->desc && class != desc->class)
1281 desc++;
1283 if (desc->desc) {
1284 return qobject_from_jsonf("{ 'desc': %s, 'class': %d }",
1285 desc->desc, class);
1286 } else {
1287 return qobject_from_jsonf("{ 'class': %d }", class);
1291 static QObject *pci_get_dev_id(const PCIDevice *dev)
1293 return qobject_from_jsonf("{ 'device': %d, 'vendor': %d }",
1294 pci_get_word(dev->config + PCI_VENDOR_ID),
1295 pci_get_word(dev->config + PCI_DEVICE_ID));
1298 static QObject *pci_get_regions_list(const PCIDevice *dev)
1300 int i;
1301 QList *regions_list;
1303 regions_list = qlist_new();
1305 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1306 QObject *obj;
1307 const PCIIORegion *r = &dev->io_regions[i];
1309 if (!r->size) {
1310 continue;
1313 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1314 obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'io', "
1315 "'address': %" PRId64 ", "
1316 "'size': %" PRId64 " }",
1317 i, r->addr, r->size);
1318 } else {
1319 int mem_type_64 = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64;
1321 obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'memory', "
1322 "'mem_type_64': %i, 'prefetch': %i, "
1323 "'address': %" PRId64 ", "
1324 "'size': %" PRId64 " }",
1325 i, mem_type_64,
1326 r->type & PCI_BASE_ADDRESS_MEM_PREFETCH,
1327 r->addr, r->size);
1330 qlist_append_obj(regions_list, obj);
1333 return QOBJECT(regions_list);
1336 static QObject *pci_get_devices_list(PCIBus *bus, int bus_num);
1338 static QObject *pci_get_dev_dict(PCIDevice *dev, PCIBus *bus, int bus_num)
1340 uint8_t type;
1341 QObject *obj;
1343 obj = qobject_from_jsonf("{ 'bus': %d, 'slot': %d, 'function': %d," "'class_info': %p, 'id': %p, 'regions': %p,"
1344 " 'qdev_id': %s }",
1345 bus_num,
1346 PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
1347 pci_get_dev_class(dev), pci_get_dev_id(dev),
1348 pci_get_regions_list(dev),
1349 dev->qdev.id ? dev->qdev.id : "");
1351 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1352 QDict *qdict = qobject_to_qdict(obj);
1353 qdict_put(qdict, "irq", qint_from_int(dev->config[PCI_INTERRUPT_LINE]));
1356 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1357 if (type == PCI_HEADER_TYPE_BRIDGE) {
1358 QDict *qdict;
1359 QObject *pci_bridge;
1361 pci_bridge = qobject_from_jsonf("{ 'bus': "
1362 "{ 'number': %d, 'secondary': %d, 'subordinate': %d }, "
1363 "'io_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1364 "'memory_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1365 "'prefetchable_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "} }",
1366 dev->config[PCI_PRIMARY_BUS], dev->config[PCI_SECONDARY_BUS],
1367 dev->config[PCI_SUBORDINATE_BUS],
1368 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO),
1369 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO),
1370 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1371 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1372 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1373 PCI_BASE_ADDRESS_MEM_PREFETCH),
1374 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1375 PCI_BASE_ADDRESS_MEM_PREFETCH));
1377 if (dev->config[PCI_SECONDARY_BUS] != 0) {
1378 PCIBus *child_bus = pci_find_bus(bus, dev->config[PCI_SECONDARY_BUS]);
1380 if (child_bus) {
1381 qdict = qobject_to_qdict(pci_bridge);
1382 qdict_put_obj(qdict, "devices",
1383 pci_get_devices_list(child_bus,
1384 dev->config[PCI_SECONDARY_BUS]));
1387 qdict = qobject_to_qdict(obj);
1388 qdict_put_obj(qdict, "pci_bridge", pci_bridge);
1391 return obj;
1394 static QObject *pci_get_devices_list(PCIBus *bus, int bus_num)
1396 int devfn;
1397 PCIDevice *dev;
1398 QList *dev_list;
1400 dev_list = qlist_new();
1402 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1403 dev = bus->devices[devfn];
1404 if (dev) {
1405 qlist_append_obj(dev_list, pci_get_dev_dict(dev, bus, bus_num));
1409 return QOBJECT(dev_list);
1412 static QObject *pci_get_bus_dict(PCIBus *bus, int bus_num)
1414 bus = pci_find_bus(bus, bus_num);
1415 if (bus) {
1416 return qobject_from_jsonf("{ 'bus': %d, 'devices': %p }",
1417 bus_num, pci_get_devices_list(bus, bus_num));
1420 return NULL;
1423 void do_pci_info(Monitor *mon, QObject **ret_data)
1425 QList *bus_list;
1426 struct PCIHostBus *host;
1428 bus_list = qlist_new();
1430 QLIST_FOREACH(host, &host_buses, next) {
1431 QObject *obj = pci_get_bus_dict(host->bus, 0);
1432 if (obj) {
1433 qlist_append_obj(bus_list, obj);
1437 *ret_data = QOBJECT(bus_list);
1440 static const char * const pci_nic_models[] = {
1441 "ne2k_pci",
1442 "i82551",
1443 "i82557b",
1444 "i82559er",
1445 "rtl8139",
1446 "e1000",
1447 "pcnet",
1448 "virtio",
1449 NULL
1452 static const char * const pci_nic_names[] = {
1453 "ne2k_pci",
1454 "i82551",
1455 "i82557b",
1456 "i82559er",
1457 "rtl8139",
1458 "e1000",
1459 "pcnet",
1460 "virtio-net-pci",
1461 NULL
1464 /* Initialize a PCI NIC. */
1465 /* FIXME callers should check for failure, but don't */
1466 PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1467 const char *default_devaddr)
1469 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1470 PCIBus *bus;
1471 int devfn;
1472 PCIDevice *pci_dev;
1473 DeviceState *dev;
1474 int i;
1476 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1477 if (i < 0)
1478 return NULL;
1480 bus = pci_get_bus_devfn(&devfn, devaddr);
1481 if (!bus) {
1482 error_report("Invalid PCI device address %s for device %s",
1483 devaddr, pci_nic_names[i]);
1484 return NULL;
1487 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1488 dev = &pci_dev->qdev;
1489 qdev_set_nic_properties(dev, nd);
1490 if (qdev_init(dev) < 0)
1491 return NULL;
1492 return pci_dev;
1495 PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1496 const char *default_devaddr)
1498 PCIDevice *res;
1500 if (qemu_show_nic_models(nd->model, pci_nic_models))
1501 exit(0);
1503 res = pci_nic_init(nd, default_model, default_devaddr);
1504 if (!res)
1505 exit(1);
1506 return res;
1509 static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1511 pci_update_mappings(d);
1514 void pci_bridge_update_mappings(PCIBus *b)
1516 PCIBus *child;
1518 pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1520 QLIST_FOREACH(child, &b->child, sibling) {
1521 pci_bridge_update_mappings(child);
1525 PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1527 PCIBus *sec;
1529 if (!bus) {
1530 return NULL;
1533 if (pci_bus_num(bus) == bus_num) {
1534 return bus;
1537 /* try child bus */
1538 if (!bus->parent_dev /* host pci bridge */ ||
1539 (bus->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1540 bus_num <= bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {
1541 for (; bus; bus = sec) {
1542 QLIST_FOREACH(sec, &bus->child, sibling) {
1543 assert(sec->parent_dev);
1544 if (sec->parent_dev->config[PCI_SECONDARY_BUS] == bus_num) {
1545 return sec;
1547 if (sec->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1548 bus_num <= sec->parent_dev->config[PCI_SUBORDINATE_BUS]) {
1549 break;
1555 return NULL;
1558 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function)
1560 bus = pci_find_bus(bus, bus_num);
1562 if (!bus)
1563 return NULL;
1565 return bus->devices[PCI_DEVFN(slot, function)];
1568 static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1570 PCIDevice *pci_dev = (PCIDevice *)qdev;
1571 PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1572 PCIBus *bus;
1573 int devfn, rc;
1574 bool is_default_rom;
1576 /* initialize cap_present for pci_is_express() and pci_config_size() */
1577 if (info->is_express) {
1578 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1581 bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1582 devfn = pci_dev->devfn;
1583 pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
1584 info->config_read, info->config_write,
1585 info->is_bridge);
1586 if (pci_dev == NULL)
1587 return -1;
1588 rc = info->init(pci_dev);
1589 if (rc != 0) {
1590 do_pci_unregister_device(pci_dev);
1591 return rc;
1594 /* rom loading */
1595 is_default_rom = false;
1596 if (pci_dev->romfile == NULL && info->romfile != NULL) {
1597 pci_dev->romfile = qemu_strdup(info->romfile);
1598 is_default_rom = true;
1600 pci_add_option_rom(pci_dev, is_default_rom);
1602 if (bus->hotplug) {
1603 /* Let buses differentiate between hotplug and when device is
1604 * enabled during qemu machine creation. */
1605 rc = bus->hotplug(bus->hotplug_qdev, pci_dev,
1606 qdev->hotplugged ? PCI_HOTPLUG_ENABLED:
1607 PCI_COLDPLUG_ENABLED);
1608 if (rc != 0) {
1609 int r = pci_unregister_device(&pci_dev->qdev);
1610 assert(!r);
1611 return rc;
1614 return 0;
1617 static int pci_unplug_device(DeviceState *qdev)
1619 PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1621 return dev->bus->hotplug(dev->bus->hotplug_qdev, dev,
1622 PCI_HOTPLUG_DISABLED);
1625 void pci_qdev_register(PCIDeviceInfo *info)
1627 info->qdev.init = pci_qdev_init;
1628 info->qdev.unplug = pci_unplug_device;
1629 info->qdev.exit = pci_unregister_device;
1630 info->qdev.bus_info = &pci_bus_info;
1631 qdev_register(&info->qdev);
1634 void pci_qdev_register_many(PCIDeviceInfo *info)
1636 while (info->qdev.name) {
1637 pci_qdev_register(info);
1638 info++;
1642 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1643 const char *name)
1645 DeviceState *dev;
1647 dev = qdev_create(&bus->qbus, name);
1648 qdev_prop_set_uint32(dev, "addr", devfn);
1649 qdev_prop_set_bit(dev, "multifunction", multifunction);
1650 return DO_UPCAST(PCIDevice, qdev, dev);
1653 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1654 bool multifunction,
1655 const char *name)
1657 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1658 qdev_init_nofail(&dev->qdev);
1659 return dev;
1662 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1664 return pci_create_multifunction(bus, devfn, false, name);
1667 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1669 return pci_create_simple_multifunction(bus, devfn, false, name);
1672 static int pci_find_space(PCIDevice *pdev, uint8_t size)
1674 int config_size = pci_config_size(pdev);
1675 int offset = PCI_CONFIG_HEADER_SIZE;
1676 int i;
1677 for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1678 if (pdev->used[i])
1679 offset = i + 1;
1680 else if (i - offset + 1 == size)
1681 return offset;
1682 return 0;
1685 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1686 uint8_t *prev_p)
1688 uint8_t next, prev;
1690 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1691 return 0;
1693 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1694 prev = next + PCI_CAP_LIST_NEXT)
1695 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1696 break;
1698 if (prev_p)
1699 *prev_p = prev;
1700 return next;
1703 static void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1705 cpu_register_physical_memory(addr, size, pdev->rom_offset);
1708 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
1709 This is needed for an option rom which is used for more than one device. */
1710 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
1712 uint16_t vendor_id;
1713 uint16_t device_id;
1714 uint16_t rom_vendor_id;
1715 uint16_t rom_device_id;
1716 uint16_t rom_magic;
1717 uint16_t pcir_offset;
1718 uint8_t checksum;
1720 /* Words in rom data are little endian (like in PCI configuration),
1721 so they can be read / written with pci_get_word / pci_set_word. */
1723 /* Only a valid rom will be patched. */
1724 rom_magic = pci_get_word(ptr);
1725 if (rom_magic != 0xaa55) {
1726 PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
1727 return;
1729 pcir_offset = pci_get_word(ptr + 0x18);
1730 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
1731 PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
1732 return;
1735 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
1736 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
1737 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
1738 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
1740 PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
1741 vendor_id, device_id, rom_vendor_id, rom_device_id);
1743 checksum = ptr[6];
1745 if (vendor_id != rom_vendor_id) {
1746 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
1747 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
1748 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
1749 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1750 ptr[6] = checksum;
1751 pci_set_word(ptr + pcir_offset + 4, vendor_id);
1754 if (device_id != rom_device_id) {
1755 /* Patch device id and checksum (at offset 6 for etherboot roms). */
1756 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
1757 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
1758 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1759 ptr[6] = checksum;
1760 pci_set_word(ptr + pcir_offset + 6, device_id);
1764 /* Add an option rom for the device */
1765 static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom)
1767 int size;
1768 char *path;
1769 void *ptr;
1770 char name[32];
1772 if (!pdev->romfile)
1773 return 0;
1774 if (strlen(pdev->romfile) == 0)
1775 return 0;
1777 if (!pdev->rom_bar) {
1779 * Load rom via fw_cfg instead of creating a rom bar,
1780 * for 0.11 compatibility.
1782 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
1783 if (class == 0x0300) {
1784 rom_add_vga(pdev->romfile);
1785 } else {
1786 rom_add_option(pdev->romfile);
1788 return 0;
1791 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1792 if (path == NULL) {
1793 path = qemu_strdup(pdev->romfile);
1796 size = get_image_size(path);
1797 if (size < 0) {
1798 error_report("%s: failed to find romfile \"%s\"",
1799 __FUNCTION__, pdev->romfile);
1800 return -1;
1802 if (size & (size - 1)) {
1803 size = 1 << qemu_fls(size);
1806 if (pdev->qdev.info->vmsd)
1807 snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);
1808 else
1809 snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);
1810 pdev->rom_offset = qemu_ram_alloc(&pdev->qdev, name, size);
1812 ptr = qemu_get_ram_ptr(pdev->rom_offset);
1813 load_image(path, ptr);
1814 qemu_free(path);
1816 if (is_default_rom) {
1817 /* Only the default rom images will be patched (if needed). */
1818 pci_patch_ids(pdev, ptr, size);
1821 pci_register_bar(pdev, PCI_ROM_SLOT, size,
1822 0, pci_map_option_rom);
1824 return 0;
1827 static void pci_del_option_rom(PCIDevice *pdev)
1829 if (!pdev->rom_offset)
1830 return;
1832 qemu_ram_free(pdev->rom_offset);
1833 pdev->rom_offset = 0;
1837 * if !offset
1838 * Reserve space and add capability to the linked list in pci config space
1840 * if offset = 0,
1841 * Find and reserve space and add capability to the linked list
1842 * in pci config space */
1843 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
1844 uint8_t offset, uint8_t size)
1846 uint8_t *config;
1847 if (!offset) {
1848 offset = pci_find_space(pdev, size);
1849 if (!offset) {
1850 return -ENOSPC;
1854 config = pdev->config + offset;
1855 config[PCI_CAP_LIST_ID] = cap_id;
1856 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1857 pdev->config[PCI_CAPABILITY_LIST] = offset;
1858 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1859 memset(pdev->used + offset, 0xFF, size);
1860 /* Make capability read-only by default */
1861 memset(pdev->wmask + offset, 0, size);
1862 /* Check capability by default */
1863 memset(pdev->cmask + offset, 0xFF, size);
1864 return offset;
1867 /* Unlink capability from the pci config space. */
1868 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1870 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
1871 if (!offset)
1872 return;
1873 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
1874 /* Make capability writeable again */
1875 memset(pdev->wmask + offset, 0xff, size);
1876 memset(pdev->w1cmask + offset, 0, size);
1877 /* Clear cmask as device-specific registers can't be checked */
1878 memset(pdev->cmask + offset, 0, size);
1879 memset(pdev->used + offset, 0, size);
1881 if (!pdev->config[PCI_CAPABILITY_LIST])
1882 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
1885 /* Reserve space for capability at a known offset (to call after load). */
1886 void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
1888 memset(pdev->used + offset, 0xff, size);
1891 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
1893 return pci_find_capability_list(pdev, cap_id, NULL);
1896 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
1898 PCIDevice *d = (PCIDevice *)dev;
1899 const pci_class_desc *desc;
1900 char ctxt[64];
1901 PCIIORegion *r;
1902 int i, class;
1904 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1905 desc = pci_class_descriptions;
1906 while (desc->desc && class != desc->class)
1907 desc++;
1908 if (desc->desc) {
1909 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
1910 } else {
1911 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
1914 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
1915 "pci id %04x:%04x (sub %04x:%04x)\n",
1916 indent, "", ctxt, pci_bus_num(d->bus),
1917 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
1918 pci_get_word(d->config + PCI_VENDOR_ID),
1919 pci_get_word(d->config + PCI_DEVICE_ID),
1920 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
1921 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
1922 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1923 r = &d->io_regions[i];
1924 if (!r->size)
1925 continue;
1926 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
1927 " [0x%"FMT_PCIBUS"]\n",
1928 indent, "",
1929 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
1930 r->addr, r->addr + r->size - 1);
1934 static char *pcibus_get_dev_path(DeviceState *dev)
1936 PCIDevice *d = (PCIDevice *)dev;
1937 char path[16];
1939 snprintf(path, sizeof(path), "%04x:%02x:%02x.%x",
1940 pci_find_domain(d->bus), d->config[PCI_SECONDARY_BUS],
1941 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));
1943 return strdup(path);