virtio-pci: Convert fprintf() to error_report()
[qemu/mdroth.git] / hw / pci.c
blob438c0d169169ce6c7573e8044efd5bb496dd098a
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);
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 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
147 dev->config[PCI_INTERRUPT_LINE] = 0x0;
148 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
149 PCIIORegion *region = &dev->io_regions[r];
150 if (!region->size) {
151 continue;
154 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
155 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
156 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
157 } else {
158 pci_set_long(dev->config + pci_bar(dev, r), region->type);
161 pci_update_mappings(dev);
164 static void pci_bus_reset(void *opaque)
166 PCIBus *bus = opaque;
167 int i;
169 for (i = 0; i < bus->nirq; i++) {
170 bus->irq_count[i] = 0;
172 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
173 if (bus->devices[i]) {
174 pci_device_reset(bus->devices[i]);
179 static void pci_host_bus_register(int domain, PCIBus *bus)
181 struct PCIHostBus *host;
182 host = qemu_mallocz(sizeof(*host));
183 host->domain = domain;
184 host->bus = bus;
185 QLIST_INSERT_HEAD(&host_buses, host, next);
188 PCIBus *pci_find_root_bus(int domain)
190 struct PCIHostBus *host;
192 QLIST_FOREACH(host, &host_buses, next) {
193 if (host->domain == domain) {
194 return host->bus;
198 return NULL;
201 int pci_find_domain(const PCIBus *bus)
203 PCIDevice *d;
204 struct PCIHostBus *host;
206 /* obtain root bus */
207 while ((d = bus->parent_dev) != NULL) {
208 bus = d->bus;
211 QLIST_FOREACH(host, &host_buses, next) {
212 if (host->bus == bus) {
213 return host->domain;
217 abort(); /* should not be reached */
218 return -1;
221 void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
222 const char *name, int devfn_min)
224 qbus_create_inplace(&bus->qbus, &pci_bus_info, parent, name);
225 assert(PCI_FUNC(devfn_min) == 0);
226 bus->devfn_min = devfn_min;
228 /* host bridge */
229 QLIST_INIT(&bus->child);
230 pci_host_bus_register(0, bus); /* for now only pci domain 0 is supported */
232 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
233 qemu_register_reset(pci_bus_reset, bus);
236 PCIBus *pci_bus_new(DeviceState *parent, const char *name, int devfn_min)
238 PCIBus *bus;
240 bus = qemu_mallocz(sizeof(*bus));
241 bus->qbus.qdev_allocated = 1;
242 pci_bus_new_inplace(bus, parent, name, devfn_min);
243 return bus;
246 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
247 void *irq_opaque, int nirq)
249 bus->set_irq = set_irq;
250 bus->map_irq = map_irq;
251 bus->irq_opaque = irq_opaque;
252 bus->nirq = nirq;
253 bus->irq_count = qemu_mallocz(nirq * sizeof(bus->irq_count[0]));
256 void pci_bus_hotplug(PCIBus *bus, pci_hotplug_fn hotplug, DeviceState *qdev)
258 bus->qbus.allow_hotplug = 1;
259 bus->hotplug = hotplug;
260 bus->hotplug_qdev = qdev;
263 void pci_bus_set_mem_base(PCIBus *bus, target_phys_addr_t base)
265 bus->mem_base = base;
268 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
269 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
270 void *irq_opaque, int devfn_min, int nirq)
272 PCIBus *bus;
274 bus = pci_bus_new(parent, name, devfn_min);
275 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
276 return bus;
279 int pci_bus_num(PCIBus *s)
281 if (!s->parent_dev)
282 return 0; /* pci host bridge */
283 return s->parent_dev->config[PCI_SECONDARY_BUS];
286 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
288 PCIDevice *s = container_of(pv, PCIDevice, config);
289 uint8_t *config;
290 int i;
292 assert(size == pci_config_size(s));
293 config = qemu_malloc(size);
295 qemu_get_buffer(f, config, size);
296 for (i = 0; i < size; ++i) {
297 if ((config[i] ^ s->config[i]) &
298 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
299 qemu_free(config);
300 return -EINVAL;
303 memcpy(s->config, config, size);
305 pci_update_mappings(s);
307 qemu_free(config);
308 return 0;
311 /* just put buffer */
312 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
314 const uint8_t **v = pv;
315 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
316 qemu_put_buffer(f, *v, size);
319 static VMStateInfo vmstate_info_pci_config = {
320 .name = "pci config",
321 .get = get_pci_config_device,
322 .put = put_pci_config_device,
325 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
327 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
328 uint32_t irq_state[PCI_NUM_PINS];
329 int i;
330 for (i = 0; i < PCI_NUM_PINS; ++i) {
331 irq_state[i] = qemu_get_be32(f);
332 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
333 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
334 irq_state[i]);
335 return -EINVAL;
339 for (i = 0; i < PCI_NUM_PINS; ++i) {
340 pci_set_irq_state(s, i, irq_state[i]);
343 return 0;
346 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
348 int i;
349 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
351 for (i = 0; i < PCI_NUM_PINS; ++i) {
352 qemu_put_be32(f, pci_irq_state(s, i));
356 static VMStateInfo vmstate_info_pci_irq_state = {
357 .name = "pci irq state",
358 .get = get_pci_irq_state,
359 .put = put_pci_irq_state,
362 const VMStateDescription vmstate_pci_device = {
363 .name = "PCIDevice",
364 .version_id = 2,
365 .minimum_version_id = 1,
366 .minimum_version_id_old = 1,
367 .fields = (VMStateField []) {
368 VMSTATE_INT32_LE(version_id, PCIDevice),
369 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
370 vmstate_info_pci_config,
371 PCI_CONFIG_SPACE_SIZE),
372 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
373 vmstate_info_pci_irq_state,
374 PCI_NUM_PINS * sizeof(int32_t)),
375 VMSTATE_END_OF_LIST()
379 const VMStateDescription vmstate_pcie_device = {
380 .name = "PCIDevice",
381 .version_id = 2,
382 .minimum_version_id = 1,
383 .minimum_version_id_old = 1,
384 .fields = (VMStateField []) {
385 VMSTATE_INT32_LE(version_id, PCIDevice),
386 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
387 vmstate_info_pci_config,
388 PCIE_CONFIG_SPACE_SIZE),
389 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
390 vmstate_info_pci_irq_state,
391 PCI_NUM_PINS * sizeof(int32_t)),
392 VMSTATE_END_OF_LIST()
396 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
398 return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
401 void pci_device_save(PCIDevice *s, QEMUFile *f)
403 /* Clear interrupt status bit: it is implicit
404 * in irq_state which we are saving.
405 * This makes us compatible with old devices
406 * which never set or clear this bit. */
407 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
408 vmstate_save_state(f, pci_get_vmstate(s), s);
409 /* Restore the interrupt status bit. */
410 pci_update_irq_status(s);
413 int pci_device_load(PCIDevice *s, QEMUFile *f)
415 int ret;
416 ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
417 /* Restore the interrupt status bit. */
418 pci_update_irq_status(s);
419 return ret;
422 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
424 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
425 pci_default_sub_vendor_id);
426 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
427 pci_default_sub_device_id);
431 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
432 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
434 int pci_parse_devaddr(const char *addr, int *domp, int *busp,
435 unsigned int *slotp, unsigned int *funcp)
437 const char *p;
438 char *e;
439 unsigned long val;
440 unsigned long dom = 0, bus = 0;
441 unsigned int slot = 0;
442 unsigned int func = 0;
444 p = addr;
445 val = strtoul(p, &e, 16);
446 if (e == p)
447 return -1;
448 if (*e == ':') {
449 bus = val;
450 p = e + 1;
451 val = strtoul(p, &e, 16);
452 if (e == p)
453 return -1;
454 if (*e == ':') {
455 dom = bus;
456 bus = val;
457 p = e + 1;
458 val = strtoul(p, &e, 16);
459 if (e == p)
460 return -1;
464 slot = val;
466 if (funcp != NULL) {
467 if (*e != '.')
468 return -1;
470 p = e + 1;
471 val = strtoul(p, &e, 16);
472 if (e == p)
473 return -1;
475 func = val;
478 /* if funcp == NULL func is 0 */
479 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
480 return -1;
482 if (*e)
483 return -1;
485 /* Note: QEMU doesn't implement domains other than 0 */
486 if (!pci_find_bus(pci_find_root_bus(dom), bus))
487 return -1;
489 *domp = dom;
490 *busp = bus;
491 *slotp = slot;
492 if (funcp != NULL)
493 *funcp = func;
494 return 0;
497 int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
498 unsigned *slotp)
500 /* strip legacy tag */
501 if (!strncmp(addr, "pci_addr=", 9)) {
502 addr += 9;
504 if (pci_parse_devaddr(addr, domp, busp, slotp, NULL)) {
505 monitor_printf(mon, "Invalid pci address\n");
506 return -1;
508 return 0;
511 PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
513 int dom, bus;
514 unsigned slot;
516 if (!devaddr) {
517 *devfnp = -1;
518 return pci_find_bus(pci_find_root_bus(0), 0);
521 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
522 return NULL;
525 *devfnp = slot << 3;
526 return pci_find_bus(pci_find_root_bus(dom), bus);
529 static void pci_init_cmask(PCIDevice *dev)
531 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
532 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
533 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
534 dev->cmask[PCI_REVISION_ID] = 0xff;
535 dev->cmask[PCI_CLASS_PROG] = 0xff;
536 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
537 dev->cmask[PCI_HEADER_TYPE] = 0xff;
538 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
541 static void pci_init_wmask(PCIDevice *dev)
543 int config_size = pci_config_size(dev);
545 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
546 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
547 pci_set_word(dev->wmask + PCI_COMMAND,
548 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
549 PCI_COMMAND_INTX_DISABLE);
551 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
552 config_size - PCI_CONFIG_HEADER_SIZE);
555 static void pci_init_wmask_bridge(PCIDevice *d)
557 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
558 PCI_SEC_LETENCY_TIMER */
559 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
561 /* base and limit */
562 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
563 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
564 pci_set_word(d->wmask + PCI_MEMORY_BASE,
565 PCI_MEMORY_RANGE_MASK & 0xffff);
566 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
567 PCI_MEMORY_RANGE_MASK & 0xffff);
568 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
569 PCI_PREF_RANGE_MASK & 0xffff);
570 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
571 PCI_PREF_RANGE_MASK & 0xffff);
573 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
574 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
576 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL, 0xffff);
579 static int pci_init_multifunction(PCIBus *bus, PCIDevice *dev)
581 uint8_t slot = PCI_SLOT(dev->devfn);
582 uint8_t func;
584 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
585 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
589 * multifunction bit is interpreted in two ways as follows.
590 * - all functions must set the bit to 1.
591 * Example: Intel X53
592 * - function 0 must set the bit, but the rest function (> 0)
593 * is allowed to leave the bit to 0.
594 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
596 * So OS (at least Linux) checks the bit of only function 0,
597 * and doesn't see the bit of function > 0.
599 * The below check allows both interpretation.
601 if (PCI_FUNC(dev->devfn)) {
602 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
603 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
604 /* function 0 should set multifunction bit */
605 error_report("PCI: single function device can't be populated "
606 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
607 return -1;
609 return 0;
612 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
613 return 0;
615 /* function 0 indicates single function, so function > 0 must be NULL */
616 for (func = 1; func < PCI_FUNC_MAX; ++func) {
617 if (bus->devices[PCI_DEVFN(slot, func)]) {
618 error_report("PCI: %x.0 indicates single function, "
619 "but %x.%x is already populated.",
620 slot, slot, func);
621 return -1;
624 return 0;
627 static void pci_config_alloc(PCIDevice *pci_dev)
629 int config_size = pci_config_size(pci_dev);
631 pci_dev->config = qemu_mallocz(config_size);
632 pci_dev->cmask = qemu_mallocz(config_size);
633 pci_dev->wmask = qemu_mallocz(config_size);
634 pci_dev->w1cmask = qemu_mallocz(config_size);
635 pci_dev->used = qemu_mallocz(config_size);
638 static void pci_config_free(PCIDevice *pci_dev)
640 qemu_free(pci_dev->config);
641 qemu_free(pci_dev->cmask);
642 qemu_free(pci_dev->wmask);
643 qemu_free(pci_dev->w1cmask);
644 qemu_free(pci_dev->used);
647 /* -1 for devfn means auto assign */
648 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
649 const char *name, int devfn,
650 PCIConfigReadFunc *config_read,
651 PCIConfigWriteFunc *config_write,
652 bool is_bridge)
654 if (devfn < 0) {
655 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
656 devfn += PCI_FUNC_MAX) {
657 if (!bus->devices[devfn])
658 goto found;
660 error_report("PCI: no slot/function available for %s, all in use", name);
661 return NULL;
662 found: ;
663 } else if (bus->devices[devfn]) {
664 error_report("PCI: slot %d function %d not available for %s, in use by %s",
665 PCI_SLOT(devfn), PCI_FUNC(devfn), name, bus->devices[devfn]->name);
666 return NULL;
668 pci_dev->bus = bus;
669 pci_dev->devfn = devfn;
670 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
671 pci_dev->irq_state = 0;
672 pci_config_alloc(pci_dev);
674 if (!is_bridge) {
675 pci_set_default_subsystem_id(pci_dev);
677 pci_init_cmask(pci_dev);
678 pci_init_wmask(pci_dev);
679 if (is_bridge) {
680 pci_init_wmask_bridge(pci_dev);
682 if (pci_init_multifunction(bus, pci_dev)) {
683 pci_config_free(pci_dev);
684 return NULL;
687 if (!config_read)
688 config_read = pci_default_read_config;
689 if (!config_write)
690 config_write = pci_default_write_config;
691 pci_dev->config_read = config_read;
692 pci_dev->config_write = config_write;
693 bus->devices[devfn] = pci_dev;
694 pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
695 pci_dev->version_id = 2; /* Current pci device vmstate version */
696 return pci_dev;
699 static void do_pci_unregister_device(PCIDevice *pci_dev)
701 qemu_free_irqs(pci_dev->irq);
702 pci_dev->bus->devices[pci_dev->devfn] = NULL;
703 pci_config_free(pci_dev);
706 PCIDevice *pci_register_device(PCIBus *bus, const char *name,
707 int instance_size, int devfn,
708 PCIConfigReadFunc *config_read,
709 PCIConfigWriteFunc *config_write)
711 PCIDevice *pci_dev;
713 pci_dev = qemu_mallocz(instance_size);
714 pci_dev = do_pci_register_device(pci_dev, bus, name, devfn,
715 config_read, config_write,
716 PCI_HEADER_TYPE_NORMAL);
717 if (pci_dev == NULL) {
718 hw_error("PCI: can't register device\n");
720 return pci_dev;
723 static target_phys_addr_t pci_to_cpu_addr(PCIBus *bus,
724 target_phys_addr_t addr)
726 return addr + bus->mem_base;
729 static void pci_unregister_io_regions(PCIDevice *pci_dev)
731 PCIIORegion *r;
732 int i;
734 for(i = 0; i < PCI_NUM_REGIONS; i++) {
735 r = &pci_dev->io_regions[i];
736 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
737 continue;
738 if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
739 isa_unassign_ioport(r->addr, r->filtered_size);
740 } else {
741 cpu_register_physical_memory(pci_to_cpu_addr(pci_dev->bus,
742 r->addr),
743 r->filtered_size,
744 IO_MEM_UNASSIGNED);
749 static int pci_unregister_device(DeviceState *dev)
751 PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
752 PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
753 int ret = 0;
755 if (info->exit)
756 ret = info->exit(pci_dev);
757 if (ret)
758 return ret;
760 pci_unregister_io_regions(pci_dev);
761 pci_del_option_rom(pci_dev);
762 do_pci_unregister_device(pci_dev);
763 return 0;
766 void pci_register_bar(PCIDevice *pci_dev, int region_num,
767 pcibus_t size, uint8_t type,
768 PCIMapIORegionFunc *map_func)
770 PCIIORegion *r;
771 uint32_t addr;
772 uint64_t wmask;
774 assert(region_num >= 0);
775 assert(region_num < PCI_NUM_REGIONS);
776 if (size & (size-1)) {
777 fprintf(stderr, "ERROR: PCI region size must be pow2 "
778 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
779 exit(1);
782 r = &pci_dev->io_regions[region_num];
783 r->addr = PCI_BAR_UNMAPPED;
784 r->size = size;
785 r->filtered_size = size;
786 r->type = type;
787 r->map_func = map_func;
789 wmask = ~(size - 1);
790 addr = pci_bar(pci_dev, region_num);
791 if (region_num == PCI_ROM_SLOT) {
792 /* ROM enable bit is writeable */
793 wmask |= PCI_ROM_ADDRESS_ENABLE;
795 pci_set_long(pci_dev->config + addr, type);
796 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
797 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
798 pci_set_quad(pci_dev->wmask + addr, wmask);
799 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
800 } else {
801 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
802 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
806 static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
807 uint8_t type)
809 pcibus_t base = *addr;
810 pcibus_t limit = *addr + *size - 1;
811 PCIDevice *br;
813 for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
814 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
816 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
817 if (!(cmd & PCI_COMMAND_IO)) {
818 goto no_map;
820 } else {
821 if (!(cmd & PCI_COMMAND_MEMORY)) {
822 goto no_map;
826 base = MAX(base, pci_bridge_get_base(br, type));
827 limit = MIN(limit, pci_bridge_get_limit(br, type));
830 if (base > limit) {
831 goto no_map;
833 *addr = base;
834 *size = limit - base + 1;
835 return;
836 no_map:
837 *addr = PCI_BAR_UNMAPPED;
838 *size = 0;
841 static pcibus_t pci_bar_address(PCIDevice *d,
842 int reg, uint8_t type, pcibus_t size)
844 pcibus_t new_addr, last_addr;
845 int bar = pci_bar(d, reg);
846 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
848 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
849 if (!(cmd & PCI_COMMAND_IO)) {
850 return PCI_BAR_UNMAPPED;
852 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
853 last_addr = new_addr + size - 1;
854 /* NOTE: we have only 64K ioports on PC */
855 if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
856 return PCI_BAR_UNMAPPED;
858 return new_addr;
861 if (!(cmd & PCI_COMMAND_MEMORY)) {
862 return PCI_BAR_UNMAPPED;
864 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
865 new_addr = pci_get_quad(d->config + bar);
866 } else {
867 new_addr = pci_get_long(d->config + bar);
869 /* the ROM slot has a specific enable bit */
870 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
871 return PCI_BAR_UNMAPPED;
873 new_addr &= ~(size - 1);
874 last_addr = new_addr + size - 1;
875 /* NOTE: we do not support wrapping */
876 /* XXX: as we cannot support really dynamic
877 mappings, we handle specific values as invalid
878 mappings. */
879 if (last_addr <= new_addr || new_addr == 0 ||
880 last_addr == PCI_BAR_UNMAPPED) {
881 return PCI_BAR_UNMAPPED;
884 /* Now pcibus_t is 64bit.
885 * Check if 32 bit BAR wraps around explicitly.
886 * Without this, PC ide doesn't work well.
887 * TODO: remove this work around.
889 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
890 return PCI_BAR_UNMAPPED;
894 * OS is allowed to set BAR beyond its addressable
895 * bits. For example, 32 bit OS can set 64bit bar
896 * to >4G. Check it. TODO: we might need to support
897 * it in the future for e.g. PAE.
899 if (last_addr >= TARGET_PHYS_ADDR_MAX) {
900 return PCI_BAR_UNMAPPED;
903 return new_addr;
906 static void pci_update_mappings(PCIDevice *d)
908 PCIIORegion *r;
909 int i;
910 pcibus_t new_addr, filtered_size;
912 for(i = 0; i < PCI_NUM_REGIONS; i++) {
913 r = &d->io_regions[i];
915 /* this region isn't registered */
916 if (!r->size)
917 continue;
919 new_addr = pci_bar_address(d, i, r->type, r->size);
921 /* bridge filtering */
922 filtered_size = r->size;
923 if (new_addr != PCI_BAR_UNMAPPED) {
924 pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
927 /* This bar isn't changed */
928 if (new_addr == r->addr && filtered_size == r->filtered_size)
929 continue;
931 /* now do the real mapping */
932 if (r->addr != PCI_BAR_UNMAPPED) {
933 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
934 int class;
935 /* NOTE: specific hack for IDE in PC case:
936 only one byte must be mapped. */
937 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
938 if (class == 0x0101 && r->size == 4) {
939 isa_unassign_ioport(r->addr + 2, 1);
940 } else {
941 isa_unassign_ioport(r->addr, r->filtered_size);
943 } else {
944 cpu_register_physical_memory(pci_to_cpu_addr(d->bus, r->addr),
945 r->filtered_size,
946 IO_MEM_UNASSIGNED);
947 qemu_unregister_coalesced_mmio(r->addr, r->filtered_size);
950 r->addr = new_addr;
951 r->filtered_size = filtered_size;
952 if (r->addr != PCI_BAR_UNMAPPED) {
954 * TODO: currently almost all the map funcions assumes
955 * filtered_size == size and addr & ~(size - 1) == addr.
956 * However with bridge filtering, they aren't always true.
957 * Teach them such cases, such that filtered_size < size and
958 * addr & (size - 1) != 0.
960 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
961 r->map_func(d, i, r->addr, r->filtered_size, r->type);
962 } else {
963 r->map_func(d, i, pci_to_cpu_addr(d->bus, r->addr),
964 r->filtered_size, r->type);
970 static inline int pci_irq_disabled(PCIDevice *d)
972 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
975 /* Called after interrupt disabled field update in config space,
976 * assert/deassert interrupts if necessary.
977 * Gets original interrupt disable bit value (before update). */
978 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
980 int i, disabled = pci_irq_disabled(d);
981 if (disabled == was_irq_disabled)
982 return;
983 for (i = 0; i < PCI_NUM_PINS; ++i) {
984 int state = pci_irq_state(d, i);
985 pci_change_irq_level(d, i, disabled ? -state : state);
989 uint32_t pci_default_read_config(PCIDevice *d,
990 uint32_t address, int len)
992 uint32_t val = 0;
993 assert(len == 1 || len == 2 || len == 4);
994 len = MIN(len, pci_config_size(d) - address);
995 memcpy(&val, d->config + address, len);
996 return le32_to_cpu(val);
999 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
1001 int i, was_irq_disabled = pci_irq_disabled(d);
1002 uint32_t config_size = pci_config_size(d);
1004 for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
1005 uint8_t wmask = d->wmask[addr + i];
1006 uint8_t w1cmask = d->w1cmask[addr + i];
1007 assert(!(wmask & w1cmask));
1008 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1009 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1011 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1012 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1013 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1014 range_covers_byte(addr, l, PCI_COMMAND))
1015 pci_update_mappings(d);
1017 if (range_covers_byte(addr, l, PCI_COMMAND))
1018 pci_update_irq_disabled(d, was_irq_disabled);
1021 /***********************************************************/
1022 /* generic PCI irq support */
1024 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1025 static void pci_set_irq(void *opaque, int irq_num, int level)
1027 PCIDevice *pci_dev = opaque;
1028 int change;
1030 change = level - pci_irq_state(pci_dev, irq_num);
1031 if (!change)
1032 return;
1034 pci_set_irq_state(pci_dev, irq_num, level);
1035 pci_update_irq_status(pci_dev);
1036 if (pci_irq_disabled(pci_dev))
1037 return;
1038 pci_change_irq_level(pci_dev, irq_num, change);
1041 bool pci_msi_enabled(PCIDevice *dev)
1043 return msix_enabled(dev) || msi_enabled(dev);
1046 void pci_msi_notify(PCIDevice *dev, unsigned int vector)
1048 if (msix_enabled(dev)) {
1049 msix_notify(dev, vector);
1050 } else if (msi_enabled(dev)) {
1051 msi_notify(dev, vector);
1052 } else {
1053 /* MSI/MSI-X must be enabled */
1054 abort();
1058 /***********************************************************/
1059 /* monitor info on PCI */
1061 typedef struct {
1062 uint16_t class;
1063 const char *desc;
1064 } pci_class_desc;
1066 static const pci_class_desc pci_class_descriptions[] =
1068 { 0x0100, "SCSI controller"},
1069 { 0x0101, "IDE controller"},
1070 { 0x0102, "Floppy controller"},
1071 { 0x0103, "IPI controller"},
1072 { 0x0104, "RAID controller"},
1073 { 0x0106, "SATA controller"},
1074 { 0x0107, "SAS controller"},
1075 { 0x0180, "Storage controller"},
1076 { 0x0200, "Ethernet controller"},
1077 { 0x0201, "Token Ring controller"},
1078 { 0x0202, "FDDI controller"},
1079 { 0x0203, "ATM controller"},
1080 { 0x0280, "Network controller"},
1081 { 0x0300, "VGA controller"},
1082 { 0x0301, "XGA controller"},
1083 { 0x0302, "3D controller"},
1084 { 0x0380, "Display controller"},
1085 { 0x0400, "Video controller"},
1086 { 0x0401, "Audio controller"},
1087 { 0x0402, "Phone"},
1088 { 0x0480, "Multimedia controller"},
1089 { 0x0500, "RAM controller"},
1090 { 0x0501, "Flash controller"},
1091 { 0x0580, "Memory controller"},
1092 { 0x0600, "Host bridge"},
1093 { 0x0601, "ISA bridge"},
1094 { 0x0602, "EISA bridge"},
1095 { 0x0603, "MC bridge"},
1096 { 0x0604, "PCI bridge"},
1097 { 0x0605, "PCMCIA bridge"},
1098 { 0x0606, "NUBUS bridge"},
1099 { 0x0607, "CARDBUS bridge"},
1100 { 0x0608, "RACEWAY bridge"},
1101 { 0x0680, "Bridge"},
1102 { 0x0c03, "USB controller"},
1103 { 0, NULL}
1106 static void pci_for_each_device_under_bus(PCIBus *bus,
1107 void (*fn)(PCIBus *b, PCIDevice *d))
1109 PCIDevice *d;
1110 int devfn;
1112 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1113 d = bus->devices[devfn];
1114 if (d) {
1115 fn(bus, d);
1120 void pci_for_each_device(PCIBus *bus, int bus_num,
1121 void (*fn)(PCIBus *b, PCIDevice *d))
1123 bus = pci_find_bus(bus, bus_num);
1125 if (bus) {
1126 pci_for_each_device_under_bus(bus, fn);
1130 static void pci_device_print(Monitor *mon, QDict *device)
1132 QDict *qdict;
1133 QListEntry *entry;
1134 uint64_t addr, size;
1136 monitor_printf(mon, " Bus %2" PRId64 ", ", qdict_get_int(device, "bus"));
1137 monitor_printf(mon, "device %3" PRId64 ", function %" PRId64 ":\n",
1138 qdict_get_int(device, "slot"),
1139 qdict_get_int(device, "function"));
1140 monitor_printf(mon, " ");
1142 qdict = qdict_get_qdict(device, "class_info");
1143 if (qdict_haskey(qdict, "desc")) {
1144 monitor_printf(mon, "%s", qdict_get_str(qdict, "desc"));
1145 } else {
1146 monitor_printf(mon, "Class %04" PRId64, qdict_get_int(qdict, "class"));
1149 qdict = qdict_get_qdict(device, "id");
1150 monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
1151 qdict_get_int(qdict, "device"),
1152 qdict_get_int(qdict, "vendor"));
1154 if (qdict_haskey(device, "irq")) {
1155 monitor_printf(mon, " IRQ %" PRId64 ".\n",
1156 qdict_get_int(device, "irq"));
1159 if (qdict_haskey(device, "pci_bridge")) {
1160 QDict *info;
1162 qdict = qdict_get_qdict(device, "pci_bridge");
1164 info = qdict_get_qdict(qdict, "bus");
1165 monitor_printf(mon, " BUS %" PRId64 ".\n",
1166 qdict_get_int(info, "number"));
1167 monitor_printf(mon, " secondary bus %" PRId64 ".\n",
1168 qdict_get_int(info, "secondary"));
1169 monitor_printf(mon, " subordinate bus %" PRId64 ".\n",
1170 qdict_get_int(info, "subordinate"));
1172 info = qdict_get_qdict(qdict, "io_range");
1173 monitor_printf(mon, " IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1174 qdict_get_int(info, "base"),
1175 qdict_get_int(info, "limit"));
1177 info = qdict_get_qdict(qdict, "memory_range");
1178 monitor_printf(mon,
1179 " memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1180 qdict_get_int(info, "base"),
1181 qdict_get_int(info, "limit"));
1183 info = qdict_get_qdict(qdict, "prefetchable_range");
1184 monitor_printf(mon, " prefetchable memory range "
1185 "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
1186 qdict_get_int(info, "base"),
1187 qdict_get_int(info, "limit"));
1190 QLIST_FOREACH_ENTRY(qdict_get_qlist(device, "regions"), entry) {
1191 qdict = qobject_to_qdict(qlist_entry_obj(entry));
1192 monitor_printf(mon, " BAR%d: ", (int) qdict_get_int(qdict, "bar"));
1194 addr = qdict_get_int(qdict, "address");
1195 size = qdict_get_int(qdict, "size");
1197 if (!strcmp(qdict_get_str(qdict, "type"), "io")) {
1198 monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1199 " [0x%04"FMT_PCIBUS"].\n",
1200 addr, addr + size - 1);
1201 } else {
1202 monitor_printf(mon, "%d bit%s memory at 0x%08"FMT_PCIBUS
1203 " [0x%08"FMT_PCIBUS"].\n",
1204 qdict_get_bool(qdict, "mem_type_64") ? 64 : 32,
1205 qdict_get_bool(qdict, "prefetch") ?
1206 " prefetchable" : "", addr, addr + size - 1);
1210 monitor_printf(mon, " id \"%s\"\n", qdict_get_str(device, "qdev_id"));
1212 if (qdict_haskey(device, "pci_bridge")) {
1213 qdict = qdict_get_qdict(device, "pci_bridge");
1214 if (qdict_haskey(qdict, "devices")) {
1215 QListEntry *dev;
1216 QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1217 pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1223 void do_pci_info_print(Monitor *mon, const QObject *data)
1225 QListEntry *bus, *dev;
1227 QLIST_FOREACH_ENTRY(qobject_to_qlist(data), bus) {
1228 QDict *qdict = qobject_to_qdict(qlist_entry_obj(bus));
1229 QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1230 pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1235 static QObject *pci_get_dev_class(const PCIDevice *dev)
1237 int class;
1238 const pci_class_desc *desc;
1240 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1241 desc = pci_class_descriptions;
1242 while (desc->desc && class != desc->class)
1243 desc++;
1245 if (desc->desc) {
1246 return qobject_from_jsonf("{ 'desc': %s, 'class': %d }",
1247 desc->desc, class);
1248 } else {
1249 return qobject_from_jsonf("{ 'class': %d }", class);
1253 static QObject *pci_get_dev_id(const PCIDevice *dev)
1255 return qobject_from_jsonf("{ 'device': %d, 'vendor': %d }",
1256 pci_get_word(dev->config + PCI_VENDOR_ID),
1257 pci_get_word(dev->config + PCI_DEVICE_ID));
1260 static QObject *pci_get_regions_list(const PCIDevice *dev)
1262 int i;
1263 QList *regions_list;
1265 regions_list = qlist_new();
1267 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1268 QObject *obj;
1269 const PCIIORegion *r = &dev->io_regions[i];
1271 if (!r->size) {
1272 continue;
1275 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1276 obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'io', "
1277 "'address': %" PRId64 ", "
1278 "'size': %" PRId64 " }",
1279 i, r->addr, r->size);
1280 } else {
1281 int mem_type_64 = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64;
1283 obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'memory', "
1284 "'mem_type_64': %i, 'prefetch': %i, "
1285 "'address': %" PRId64 ", "
1286 "'size': %" PRId64 " }",
1287 i, mem_type_64,
1288 r->type & PCI_BASE_ADDRESS_MEM_PREFETCH,
1289 r->addr, r->size);
1292 qlist_append_obj(regions_list, obj);
1295 return QOBJECT(regions_list);
1298 static QObject *pci_get_devices_list(PCIBus *bus, int bus_num);
1300 static QObject *pci_get_dev_dict(PCIDevice *dev, PCIBus *bus, int bus_num)
1302 uint8_t type;
1303 QObject *obj;
1305 obj = qobject_from_jsonf("{ 'bus': %d, 'slot': %d, 'function': %d," "'class_info': %p, 'id': %p, 'regions': %p,"
1306 " 'qdev_id': %s }",
1307 bus_num,
1308 PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
1309 pci_get_dev_class(dev), pci_get_dev_id(dev),
1310 pci_get_regions_list(dev),
1311 dev->qdev.id ? dev->qdev.id : "");
1313 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1314 QDict *qdict = qobject_to_qdict(obj);
1315 qdict_put(qdict, "irq", qint_from_int(dev->config[PCI_INTERRUPT_LINE]));
1318 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1319 if (type == PCI_HEADER_TYPE_BRIDGE) {
1320 QDict *qdict;
1321 QObject *pci_bridge;
1323 pci_bridge = qobject_from_jsonf("{ 'bus': "
1324 "{ 'number': %d, 'secondary': %d, 'subordinate': %d }, "
1325 "'io_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1326 "'memory_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1327 "'prefetchable_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "} }",
1328 dev->config[PCI_PRIMARY_BUS], dev->config[PCI_SECONDARY_BUS],
1329 dev->config[PCI_SUBORDINATE_BUS],
1330 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO),
1331 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO),
1332 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1333 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1334 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1335 PCI_BASE_ADDRESS_MEM_PREFETCH),
1336 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1337 PCI_BASE_ADDRESS_MEM_PREFETCH));
1339 if (dev->config[PCI_SECONDARY_BUS] != 0) {
1340 PCIBus *child_bus = pci_find_bus(bus, dev->config[PCI_SECONDARY_BUS]);
1342 if (child_bus) {
1343 qdict = qobject_to_qdict(pci_bridge);
1344 qdict_put_obj(qdict, "devices",
1345 pci_get_devices_list(child_bus,
1346 dev->config[PCI_SECONDARY_BUS]));
1349 qdict = qobject_to_qdict(obj);
1350 qdict_put_obj(qdict, "pci_bridge", pci_bridge);
1353 return obj;
1356 static QObject *pci_get_devices_list(PCIBus *bus, int bus_num)
1358 int devfn;
1359 PCIDevice *dev;
1360 QList *dev_list;
1362 dev_list = qlist_new();
1364 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1365 dev = bus->devices[devfn];
1366 if (dev) {
1367 qlist_append_obj(dev_list, pci_get_dev_dict(dev, bus, bus_num));
1371 return QOBJECT(dev_list);
1374 static QObject *pci_get_bus_dict(PCIBus *bus, int bus_num)
1376 bus = pci_find_bus(bus, bus_num);
1377 if (bus) {
1378 return qobject_from_jsonf("{ 'bus': %d, 'devices': %p }",
1379 bus_num, pci_get_devices_list(bus, bus_num));
1382 return NULL;
1385 void do_pci_info(Monitor *mon, QObject **ret_data)
1387 QList *bus_list;
1388 struct PCIHostBus *host;
1390 bus_list = qlist_new();
1392 QLIST_FOREACH(host, &host_buses, next) {
1393 QObject *obj = pci_get_bus_dict(host->bus, 0);
1394 if (obj) {
1395 qlist_append_obj(bus_list, obj);
1399 *ret_data = QOBJECT(bus_list);
1402 static const char * const pci_nic_models[] = {
1403 "ne2k_pci",
1404 "i82551",
1405 "i82557b",
1406 "i82559er",
1407 "rtl8139",
1408 "e1000",
1409 "pcnet",
1410 "virtio",
1411 NULL
1414 static const char * const pci_nic_names[] = {
1415 "ne2k_pci",
1416 "i82551",
1417 "i82557b",
1418 "i82559er",
1419 "rtl8139",
1420 "e1000",
1421 "pcnet",
1422 "virtio-net-pci",
1423 NULL
1426 /* Initialize a PCI NIC. */
1427 /* FIXME callers should check for failure, but don't */
1428 PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1429 const char *default_devaddr)
1431 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1432 PCIBus *bus;
1433 int devfn;
1434 PCIDevice *pci_dev;
1435 DeviceState *dev;
1436 int i;
1438 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1439 if (i < 0)
1440 return NULL;
1442 bus = pci_get_bus_devfn(&devfn, devaddr);
1443 if (!bus) {
1444 error_report("Invalid PCI device address %s for device %s",
1445 devaddr, pci_nic_names[i]);
1446 return NULL;
1449 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1450 dev = &pci_dev->qdev;
1451 qdev_set_nic_properties(dev, nd);
1452 if (qdev_init(dev) < 0)
1453 return NULL;
1454 return pci_dev;
1457 PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1458 const char *default_devaddr)
1460 PCIDevice *res;
1462 if (qemu_show_nic_models(nd->model, pci_nic_models))
1463 exit(0);
1465 res = pci_nic_init(nd, default_model, default_devaddr);
1466 if (!res)
1467 exit(1);
1468 return res;
1471 static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1473 pci_update_mappings(d);
1476 void pci_bridge_update_mappings(PCIBus *b)
1478 PCIBus *child;
1480 pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1482 QLIST_FOREACH(child, &b->child, sibling) {
1483 pci_bridge_update_mappings(child);
1487 PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1489 PCIBus *sec;
1491 if (!bus) {
1492 return NULL;
1495 if (pci_bus_num(bus) == bus_num) {
1496 return bus;
1499 /* try child bus */
1500 if (!bus->parent_dev /* host pci bridge */ ||
1501 (bus->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1502 bus_num <= bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {
1503 for (; bus; bus = sec) {
1504 QLIST_FOREACH(sec, &bus->child, sibling) {
1505 assert(sec->parent_dev);
1506 if (sec->parent_dev->config[PCI_SECONDARY_BUS] == bus_num) {
1507 return sec;
1509 if (sec->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1510 bus_num <= sec->parent_dev->config[PCI_SUBORDINATE_BUS]) {
1511 break;
1517 return NULL;
1520 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function)
1522 bus = pci_find_bus(bus, bus_num);
1524 if (!bus)
1525 return NULL;
1527 return bus->devices[PCI_DEVFN(slot, function)];
1530 static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1532 PCIDevice *pci_dev = (PCIDevice *)qdev;
1533 PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1534 PCIBus *bus;
1535 int devfn, rc;
1537 /* initialize cap_present for pci_is_express() and pci_config_size() */
1538 if (info->is_express) {
1539 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1542 bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1543 devfn = pci_dev->devfn;
1544 pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
1545 info->config_read, info->config_write,
1546 info->is_bridge);
1547 if (pci_dev == NULL)
1548 return -1;
1549 rc = info->init(pci_dev);
1550 if (rc != 0) {
1551 do_pci_unregister_device(pci_dev);
1552 return rc;
1555 /* rom loading */
1556 if (pci_dev->romfile == NULL && info->romfile != NULL)
1557 pci_dev->romfile = qemu_strdup(info->romfile);
1558 pci_add_option_rom(pci_dev);
1560 if (bus->hotplug) {
1561 /* Let buses differentiate between hotplug and when device is
1562 * enabled during qemu machine creation. */
1563 rc = bus->hotplug(bus->hotplug_qdev, pci_dev,
1564 qdev->hotplugged ? PCI_HOTPLUG_ENABLED:
1565 PCI_COLDPLUG_ENABLED);
1566 if (rc != 0) {
1567 int r = pci_unregister_device(&pci_dev->qdev);
1568 assert(!r);
1569 return rc;
1572 return 0;
1575 static int pci_unplug_device(DeviceState *qdev)
1577 PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1579 return dev->bus->hotplug(dev->bus->hotplug_qdev, dev,
1580 PCI_HOTPLUG_DISABLED);
1583 void pci_qdev_register(PCIDeviceInfo *info)
1585 info->qdev.init = pci_qdev_init;
1586 info->qdev.unplug = pci_unplug_device;
1587 info->qdev.exit = pci_unregister_device;
1588 info->qdev.bus_info = &pci_bus_info;
1589 qdev_register(&info->qdev);
1592 void pci_qdev_register_many(PCIDeviceInfo *info)
1594 while (info->qdev.name) {
1595 pci_qdev_register(info);
1596 info++;
1600 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1601 const char *name)
1603 DeviceState *dev;
1605 dev = qdev_create(&bus->qbus, name);
1606 qdev_prop_set_uint32(dev, "addr", devfn);
1607 qdev_prop_set_bit(dev, "multifunction", multifunction);
1608 return DO_UPCAST(PCIDevice, qdev, dev);
1611 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1612 bool multifunction,
1613 const char *name)
1615 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1616 qdev_init_nofail(&dev->qdev);
1617 return dev;
1620 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1622 return pci_create_multifunction(bus, devfn, false, name);
1625 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1627 return pci_create_simple_multifunction(bus, devfn, false, name);
1630 static int pci_find_space(PCIDevice *pdev, uint8_t size)
1632 int config_size = pci_config_size(pdev);
1633 int offset = PCI_CONFIG_HEADER_SIZE;
1634 int i;
1635 for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1636 if (pdev->used[i])
1637 offset = i + 1;
1638 else if (i - offset + 1 == size)
1639 return offset;
1640 return 0;
1643 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1644 uint8_t *prev_p)
1646 uint8_t next, prev;
1648 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1649 return 0;
1651 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1652 prev = next + PCI_CAP_LIST_NEXT)
1653 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1654 break;
1656 if (prev_p)
1657 *prev_p = prev;
1658 return next;
1661 static void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1663 cpu_register_physical_memory(addr, size, pdev->rom_offset);
1666 /* Add an option rom for the device */
1667 static int pci_add_option_rom(PCIDevice *pdev)
1669 int size;
1670 char *path;
1671 void *ptr;
1672 char name[32];
1674 if (!pdev->romfile)
1675 return 0;
1676 if (strlen(pdev->romfile) == 0)
1677 return 0;
1679 if (!pdev->rom_bar) {
1681 * Load rom via fw_cfg instead of creating a rom bar,
1682 * for 0.11 compatibility.
1684 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
1685 if (class == 0x0300) {
1686 rom_add_vga(pdev->romfile);
1687 } else {
1688 rom_add_option(pdev->romfile);
1690 return 0;
1693 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1694 if (path == NULL) {
1695 path = qemu_strdup(pdev->romfile);
1698 size = get_image_size(path);
1699 if (size < 0) {
1700 error_report("%s: failed to find romfile \"%s\"",
1701 __FUNCTION__, pdev->romfile);
1702 return -1;
1704 if (size & (size - 1)) {
1705 size = 1 << qemu_fls(size);
1708 if (pdev->qdev.info->vmsd)
1709 snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);
1710 else
1711 snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);
1712 pdev->rom_offset = qemu_ram_alloc(&pdev->qdev, name, size);
1714 ptr = qemu_get_ram_ptr(pdev->rom_offset);
1715 load_image(path, ptr);
1716 qemu_free(path);
1718 pci_register_bar(pdev, PCI_ROM_SLOT, size,
1719 0, pci_map_option_rom);
1721 return 0;
1724 static void pci_del_option_rom(PCIDevice *pdev)
1726 if (!pdev->rom_offset)
1727 return;
1729 qemu_ram_free(pdev->rom_offset);
1730 pdev->rom_offset = 0;
1734 * if !offset
1735 * Reserve space and add capability to the linked list in pci config space
1737 * if offset = 0,
1738 * Find and reserve space and add capability to the linked list
1739 * in pci config space */
1740 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
1741 uint8_t offset, uint8_t size)
1743 uint8_t *config;
1744 if (!offset) {
1745 offset = pci_find_space(pdev, size);
1746 if (!offset) {
1747 return -ENOSPC;
1751 config = pdev->config + offset;
1752 config[PCI_CAP_LIST_ID] = cap_id;
1753 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1754 pdev->config[PCI_CAPABILITY_LIST] = offset;
1755 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1756 memset(pdev->used + offset, 0xFF, size);
1757 /* Make capability read-only by default */
1758 memset(pdev->wmask + offset, 0, size);
1759 /* Check capability by default */
1760 memset(pdev->cmask + offset, 0xFF, size);
1761 return offset;
1764 /* Unlink capability from the pci config space. */
1765 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1767 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
1768 if (!offset)
1769 return;
1770 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
1771 /* Make capability writeable again */
1772 memset(pdev->wmask + offset, 0xff, size);
1773 memset(pdev->w1cmask + offset, 0, size);
1774 /* Clear cmask as device-specific registers can't be checked */
1775 memset(pdev->cmask + offset, 0, size);
1776 memset(pdev->used + offset, 0, size);
1778 if (!pdev->config[PCI_CAPABILITY_LIST])
1779 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
1782 /* Reserve space for capability at a known offset (to call after load). */
1783 void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
1785 memset(pdev->used + offset, 0xff, size);
1788 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
1790 return pci_find_capability_list(pdev, cap_id, NULL);
1793 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
1795 PCIDevice *d = (PCIDevice *)dev;
1796 const pci_class_desc *desc;
1797 char ctxt[64];
1798 PCIIORegion *r;
1799 int i, class;
1801 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1802 desc = pci_class_descriptions;
1803 while (desc->desc && class != desc->class)
1804 desc++;
1805 if (desc->desc) {
1806 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
1807 } else {
1808 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
1811 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
1812 "pci id %04x:%04x (sub %04x:%04x)\n",
1813 indent, "", ctxt, pci_bus_num(d->bus),
1814 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
1815 pci_get_word(d->config + PCI_VENDOR_ID),
1816 pci_get_word(d->config + PCI_DEVICE_ID),
1817 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
1818 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
1819 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1820 r = &d->io_regions[i];
1821 if (!r->size)
1822 continue;
1823 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
1824 " [0x%"FMT_PCIBUS"]\n",
1825 indent, "",
1826 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
1827 r->addr, r->addr + r->size - 1);
1831 static char *pcibus_get_dev_path(DeviceState *dev)
1833 PCIDevice *d = (PCIDevice *)dev;
1834 char path[16];
1836 snprintf(path, sizeof(path), "%04x:%02x:%02x.%x",
1837 pci_find_domain(d->bus), d->config[PCI_SECONDARY_BUS],
1838 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));
1840 return strdup(path);