Merge branch 'master' of git://git.qemu.org/qemu into next
[qemu/qemu-dev-zwu.git] / hw / pci.c
blob5deaa04eedfc5f40af9bfe7644549ebf20a4f47f
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 "monitor.h"
29 #include "net.h"
30 #include "sysemu.h"
31 #include "loader.h"
32 #include "hw/pc.h"
33 #include "kvm.h"
34 #include "device-assignment.h"
35 #include "qemu-objects.h"
36 #include "range.h"
37 #include "msi.h"
39 //#define DEBUG_PCI
40 #ifdef DEBUG_PCI
41 # define PCI_DPRINTF(format, ...) printf(format, ## __VA_ARGS__)
42 #else
43 # define PCI_DPRINTF(format, ...) do { } while (0)
44 #endif
46 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
47 static char *pcibus_get_dev_path(DeviceState *dev);
48 static char *pcibus_get_fw_dev_path(DeviceState *dev);
49 static int pcibus_reset(BusState *qbus);
51 struct BusInfo pci_bus_info = {
52 .name = "PCI",
53 .size = sizeof(PCIBus),
54 .print_dev = pcibus_dev_print,
55 .get_dev_path = pcibus_get_dev_path,
56 .get_fw_dev_path = pcibus_get_fw_dev_path,
57 .reset = pcibus_reset,
58 .props = (Property[]) {
59 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
60 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
61 DEFINE_PROP_UINT32("rombar", PCIDevice, rom_bar, 1),
62 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
63 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
64 DEFINE_PROP_BIT("command_serr_enable", PCIDevice, cap_present,
65 QEMU_PCI_CAP_SERR_BITNR, true),
66 DEFINE_PROP_END_OF_LIST()
70 static void pci_update_mappings(PCIDevice *d);
71 static void pci_set_irq(void *opaque, int irq_num, int level);
72 static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom);
73 static void pci_del_option_rom(PCIDevice *pdev);
75 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
76 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
78 struct PCIHostBus {
79 int domain;
80 struct PCIBus *bus;
81 QLIST_ENTRY(PCIHostBus) next;
83 static QLIST_HEAD(, PCIHostBus) host_buses;
85 static const VMStateDescription vmstate_pcibus = {
86 .name = "PCIBUS",
87 .version_id = 1,
88 .minimum_version_id = 1,
89 .minimum_version_id_old = 1,
90 .fields = (VMStateField []) {
91 VMSTATE_INT32_EQUAL(nirq, PCIBus),
92 VMSTATE_VARRAY_INT32(irq_count, PCIBus, nirq, 0, vmstate_info_int32, int32_t),
93 VMSTATE_END_OF_LIST()
97 static int pci_bar(PCIDevice *d, int reg)
99 uint8_t type;
101 if (reg != PCI_ROM_SLOT)
102 return PCI_BASE_ADDRESS_0 + reg * 4;
104 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
105 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
108 static inline int pci_irq_state(PCIDevice *d, int irq_num)
110 return (d->irq_state >> irq_num) & 0x1;
113 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
115 d->irq_state &= ~(0x1 << irq_num);
116 d->irq_state |= level << irq_num;
119 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
121 PCIBus *bus;
122 for (;;) {
123 bus = pci_dev->bus;
124 irq_num = bus->map_irq(pci_dev, irq_num);
125 if (bus->set_irq)
126 break;
127 pci_dev = bus->parent_dev;
129 bus->irq_count[irq_num] += change;
130 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
133 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
135 assert(irq_num >= 0);
136 assert(irq_num < bus->nirq);
137 return !!bus->irq_count[irq_num];
140 /* Update interrupt status bit in config space on interrupt
141 * state change. */
142 static void pci_update_irq_status(PCIDevice *dev)
144 if (dev->irq_state) {
145 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
146 } else {
147 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
151 void pci_device_deassert_intx(PCIDevice *dev)
153 int i;
154 for (i = 0; i < PCI_NUM_PINS; ++i) {
155 qemu_set_irq(dev->irq[i], 0);
160 * This function is called on #RST and FLR.
161 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
163 void pci_device_reset(PCIDevice *dev)
165 int r;
166 /* TODO: call the below unconditionally once all pci devices
167 * are qdevified */
168 if (dev->qdev.info) {
169 qdev_reset_all(&dev->qdev);
172 dev->irq_state = 0;
173 pci_update_irq_status(dev);
174 pci_device_deassert_intx(dev);
175 /* Clear all writable bits */
176 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
177 pci_get_word(dev->wmask + PCI_COMMAND) |
178 pci_get_word(dev->w1cmask + PCI_COMMAND));
179 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
180 pci_get_word(dev->wmask + PCI_STATUS) |
181 pci_get_word(dev->w1cmask + PCI_STATUS));
182 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
183 dev->config[PCI_INTERRUPT_LINE] = 0x0;
184 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
185 PCIIORegion *region = &dev->io_regions[r];
186 if (!region->size) {
187 continue;
190 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
191 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
192 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
193 } else {
194 pci_set_long(dev->config + pci_bar(dev, r), region->type);
197 pci_update_mappings(dev);
201 * Trigger pci bus reset under a given bus.
202 * To be called on RST# assert.
204 void pci_bus_reset(PCIBus *bus)
206 int i;
208 for (i = 0; i < bus->nirq; i++) {
209 bus->irq_count[i] = 0;
211 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
212 if (bus->devices[i]) {
213 pci_device_reset(bus->devices[i]);
218 static int pcibus_reset(BusState *qbus)
220 pci_bus_reset(DO_UPCAST(PCIBus, qbus, qbus));
222 /* topology traverse is done by pci_bus_reset().
223 Tell qbus/qdev walker not to traverse the tree */
224 return 1;
227 static void pci_host_bus_register(int domain, PCIBus *bus)
229 struct PCIHostBus *host;
230 host = qemu_mallocz(sizeof(*host));
231 host->domain = domain;
232 host->bus = bus;
233 QLIST_INSERT_HEAD(&host_buses, host, next);
236 PCIBus *pci_find_root_bus(int domain)
238 struct PCIHostBus *host;
240 QLIST_FOREACH(host, &host_buses, next) {
241 if (host->domain == domain) {
242 return host->bus;
246 return NULL;
249 int pci_find_domain(const PCIBus *bus)
251 PCIDevice *d;
252 struct PCIHostBus *host;
254 /* obtain root bus */
255 while ((d = bus->parent_dev) != NULL) {
256 bus = d->bus;
259 QLIST_FOREACH(host, &host_buses, next) {
260 if (host->bus == bus) {
261 return host->domain;
265 abort(); /* should not be reached */
266 return -1;
269 void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
270 const char *name, uint8_t devfn_min)
272 qbus_create_inplace(&bus->qbus, &pci_bus_info, parent, name);
273 assert(PCI_FUNC(devfn_min) == 0);
274 bus->devfn_min = devfn_min;
276 /* host bridge */
277 QLIST_INIT(&bus->child);
278 pci_host_bus_register(0, bus); /* for now only pci domain 0 is supported */
280 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
283 PCIBus *pci_bus_new(DeviceState *parent, const char *name, uint8_t devfn_min)
285 PCIBus *bus;
287 bus = qemu_mallocz(sizeof(*bus));
288 bus->qbus.qdev_allocated = 1;
289 pci_bus_new_inplace(bus, parent, name, devfn_min);
290 return bus;
293 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
294 void *irq_opaque, int nirq)
296 bus->set_irq = set_irq;
297 bus->map_irq = map_irq;
298 bus->irq_opaque = irq_opaque;
299 bus->nirq = nirq;
300 bus->irq_count = qemu_mallocz(nirq * sizeof(bus->irq_count[0]));
303 void pci_bus_hotplug(PCIBus *bus, pci_hotplug_fn hotplug, DeviceState *qdev)
305 bus->qbus.allow_hotplug = 1;
306 bus->hotplug = hotplug;
307 bus->hotplug_qdev = qdev;
310 void pci_bus_set_mem_base(PCIBus *bus, target_phys_addr_t base)
312 bus->mem_base = base;
315 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
316 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
317 void *irq_opaque, uint8_t devfn_min, int nirq)
319 PCIBus *bus;
321 bus = pci_bus_new(parent, name, devfn_min);
322 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
323 return bus;
326 int pci_bus_num(PCIBus *s)
328 if (!s->parent_dev)
329 return 0; /* pci host bridge */
330 return s->parent_dev->config[PCI_SECONDARY_BUS];
333 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
335 PCIDevice *s = container_of(pv, PCIDevice, config);
336 uint8_t *config;
337 int i;
339 assert(size == pci_config_size(s));
340 config = qemu_malloc(size);
342 qemu_get_buffer(f, config, size);
343 for (i = 0; i < size; ++i) {
344 if ((config[i] ^ s->config[i]) &
345 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
346 qemu_free(config);
347 return -EINVAL;
350 memcpy(s->config, config, size);
352 pci_update_mappings(s);
353 msi_post_load(s);
355 qemu_free(config);
356 return 0;
359 /* just put buffer */
360 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
362 const uint8_t **v = pv;
363 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
364 qemu_put_buffer(f, *v, size);
367 static VMStateInfo vmstate_info_pci_config = {
368 .name = "pci config",
369 .get = get_pci_config_device,
370 .put = put_pci_config_device,
373 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
375 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
376 uint32_t irq_state[PCI_NUM_PINS];
377 int i;
378 for (i = 0; i < PCI_NUM_PINS; ++i) {
379 irq_state[i] = qemu_get_be32(f);
380 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
381 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
382 irq_state[i]);
383 return -EINVAL;
387 for (i = 0; i < PCI_NUM_PINS; ++i) {
388 pci_set_irq_state(s, i, irq_state[i]);
391 return 0;
394 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
396 int i;
397 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
399 for (i = 0; i < PCI_NUM_PINS; ++i) {
400 qemu_put_be32(f, pci_irq_state(s, i));
404 static VMStateInfo vmstate_info_pci_irq_state = {
405 .name = "pci irq state",
406 .get = get_pci_irq_state,
407 .put = put_pci_irq_state,
410 const VMStateDescription vmstate_pci_device = {
411 .name = "PCIDevice",
412 .version_id = 2,
413 .minimum_version_id = 1,
414 .minimum_version_id_old = 1,
415 .fields = (VMStateField []) {
416 VMSTATE_INT32_LE(version_id, PCIDevice),
417 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
418 vmstate_info_pci_config,
419 PCI_CONFIG_SPACE_SIZE),
420 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
421 vmstate_info_pci_irq_state,
422 PCI_NUM_PINS * sizeof(int32_t)),
423 VMSTATE_END_OF_LIST()
427 const VMStateDescription vmstate_pcie_device = {
428 .name = "PCIDevice",
429 .version_id = 2,
430 .minimum_version_id = 1,
431 .minimum_version_id_old = 1,
432 .fields = (VMStateField []) {
433 VMSTATE_INT32_LE(version_id, PCIDevice),
434 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
435 vmstate_info_pci_config,
436 PCIE_CONFIG_SPACE_SIZE),
437 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
438 vmstate_info_pci_irq_state,
439 PCI_NUM_PINS * sizeof(int32_t)),
440 VMSTATE_END_OF_LIST()
444 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
446 return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
449 void pci_device_save(PCIDevice *s, QEMUFile *f)
451 /* Clear interrupt status bit: it is implicit
452 * in irq_state which we are saving.
453 * This makes us compatible with old devices
454 * which never set or clear this bit. */
455 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
456 vmstate_save_state(f, pci_get_vmstate(s), s);
457 /* Restore the interrupt status bit. */
458 pci_update_irq_status(s);
461 int pci_device_load(PCIDevice *s, QEMUFile *f)
463 int ret;
464 ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
465 /* Restore the interrupt status bit. */
466 pci_update_irq_status(s);
467 return ret;
470 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
472 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
473 pci_default_sub_vendor_id);
474 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
475 pci_default_sub_device_id);
479 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
480 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
482 int pci_parse_devaddr(const char *addr, int *domp, int *busp,
483 unsigned int *slotp, unsigned int *funcp)
485 const char *p;
486 char *e;
487 unsigned long val;
488 unsigned long dom = 0, bus = 0;
489 unsigned int slot = 0;
490 unsigned int func = 0;
492 p = addr;
493 val = strtoul(p, &e, 16);
494 if (e == p)
495 return -1;
496 if (*e == ':') {
497 bus = val;
498 p = e + 1;
499 val = strtoul(p, &e, 16);
500 if (e == p)
501 return -1;
502 if (*e == ':') {
503 dom = bus;
504 bus = val;
505 p = e + 1;
506 val = strtoul(p, &e, 16);
507 if (e == p)
508 return -1;
512 slot = val;
514 if (funcp != NULL) {
515 if (*e != '.')
516 return -1;
518 p = e + 1;
519 val = strtoul(p, &e, 16);
520 if (e == p)
521 return -1;
523 func = val;
526 /* if funcp == NULL func is 0 */
527 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
528 return -1;
530 if (*e)
531 return -1;
533 /* Note: QEMU doesn't implement domains other than 0 */
534 if (!pci_find_bus(pci_find_root_bus(dom), bus))
535 return -1;
537 *domp = dom;
538 *busp = bus;
539 *slotp = slot;
540 if (funcp != NULL)
541 *funcp = func;
542 return 0;
546 * Parse device seg and bdf in device assignment command:
548 * -pcidevice host=[seg:]bus:dev.func
550 * Parse [seg:]<bus>:<slot>.<func> return -1 on error
552 int pci_parse_host_devaddr(const char *addr, int *segp, int *busp,
553 int *slotp, int *funcp)
555 const char *p;
556 char *e;
557 int val;
558 int seg = 0, bus = 0, slot = 0, func = 0;
560 /* parse optional seg */
561 p = addr;
562 val = 0;
563 while (1) {
564 p = strchr(p, ':');
565 if (p) {
566 val++;
567 p++;
568 } else
569 break;
571 if (val <= 0 || val > 2)
572 return -1;
574 p = addr;
575 if (val == 2) {
576 val = strtoul(p, &e, 16);
577 if (e == p)
578 return -1;
579 if (*e == ':') {
580 seg = val;
581 p = e + 1;
583 } else
584 seg = 0;
587 /* parse bdf */
588 val = strtoul(p, &e, 16);
589 if (e == p)
590 return -1;
591 if (*e == ':') {
592 bus = val;
593 p = e + 1;
594 val = strtoul(p, &e, 16);
595 if (e == p)
596 return -1;
597 if (*e == '.') {
598 slot = val;
599 p = e + 1;
600 val = strtoul(p, &e, 16);
601 if (e == p)
602 return -1;
603 func = val;
604 } else
605 return -1;
606 } else
607 return -1;
609 if (seg > 0xffff || bus > 0xff || slot > 0x1f || func > 0x7)
610 return -1;
612 if (*e)
613 return -1;
615 *segp = seg;
616 *busp = bus;
617 *slotp = slot;
618 *funcp = func;
619 return 0;
622 int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
623 unsigned *slotp)
625 /* strip legacy tag */
626 if (!strncmp(addr, "pci_addr=", 9)) {
627 addr += 9;
629 if (pci_parse_devaddr(addr, domp, busp, slotp, NULL)) {
630 monitor_printf(mon, "Invalid pci address\n");
631 return -1;
633 return 0;
636 PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
638 int dom, bus;
639 unsigned slot;
641 if (!devaddr) {
642 *devfnp = -1;
643 return pci_find_bus(pci_find_root_bus(0), 0);
646 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
647 return NULL;
650 *devfnp = PCI_DEVFN(slot, 0);
651 return pci_find_bus(pci_find_root_bus(dom), bus);
654 static void pci_init_cmask(PCIDevice *dev)
656 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
657 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
658 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
659 dev->cmask[PCI_REVISION_ID] = 0xff;
660 dev->cmask[PCI_CLASS_PROG] = 0xff;
661 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
662 dev->cmask[PCI_HEADER_TYPE] = 0xff;
663 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
666 static void pci_init_wmask(PCIDevice *dev)
668 int config_size = pci_config_size(dev);
670 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
671 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
672 pci_set_word(dev->wmask + PCI_COMMAND,
673 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
674 PCI_COMMAND_INTX_DISABLE);
675 if (dev->cap_present & QEMU_PCI_CAP_SERR) {
676 pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
679 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
680 config_size - PCI_CONFIG_HEADER_SIZE);
683 static void pci_init_w1cmask(PCIDevice *dev)
686 * Note: It's okay to set w1cmask even for readonly bits as
687 * long as their value is hardwired to 0.
689 pci_set_word(dev->w1cmask + PCI_STATUS,
690 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
691 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
692 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
695 static void pci_init_wmask_bridge(PCIDevice *d)
697 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
698 PCI_SEC_LETENCY_TIMER */
699 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
701 /* base and limit */
702 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
703 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
704 pci_set_word(d->wmask + PCI_MEMORY_BASE,
705 PCI_MEMORY_RANGE_MASK & 0xffff);
706 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
707 PCI_MEMORY_RANGE_MASK & 0xffff);
708 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
709 PCI_PREF_RANGE_MASK & 0xffff);
710 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
711 PCI_PREF_RANGE_MASK & 0xffff);
713 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
714 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
716 /* TODO: add this define to pci_regs.h in linux and then in qemu. */
717 #define PCI_BRIDGE_CTL_VGA_16BIT 0x10 /* VGA 16-bit decode */
718 #define PCI_BRIDGE_CTL_DISCARD 0x100 /* Primary discard timer */
719 #define PCI_BRIDGE_CTL_SEC_DISCARD 0x200 /* Secondary discard timer */
720 #define PCI_BRIDGE_CTL_DISCARD_STATUS 0x400 /* Discard timer status */
721 #define PCI_BRIDGE_CTL_DISCARD_SERR 0x800 /* Discard timer SERR# enable */
722 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
723 PCI_BRIDGE_CTL_PARITY |
724 PCI_BRIDGE_CTL_SERR |
725 PCI_BRIDGE_CTL_ISA |
726 PCI_BRIDGE_CTL_VGA |
727 PCI_BRIDGE_CTL_VGA_16BIT |
728 PCI_BRIDGE_CTL_MASTER_ABORT |
729 PCI_BRIDGE_CTL_BUS_RESET |
730 PCI_BRIDGE_CTL_FAST_BACK |
731 PCI_BRIDGE_CTL_DISCARD |
732 PCI_BRIDGE_CTL_SEC_DISCARD |
733 PCI_BRIDGE_CTL_DISCARD_SERR);
734 /* Below does not do anything as we never set this bit, put here for
735 * completeness. */
736 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
737 PCI_BRIDGE_CTL_DISCARD_STATUS);
740 static int pci_init_multifunction(PCIBus *bus, PCIDevice *dev)
742 uint8_t slot = PCI_SLOT(dev->devfn);
743 uint8_t func;
745 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
746 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
750 * multifunction bit is interpreted in two ways as follows.
751 * - all functions must set the bit to 1.
752 * Example: Intel X53
753 * - function 0 must set the bit, but the rest function (> 0)
754 * is allowed to leave the bit to 0.
755 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
757 * So OS (at least Linux) checks the bit of only function 0,
758 * and doesn't see the bit of function > 0.
760 * The below check allows both interpretation.
762 if (PCI_FUNC(dev->devfn)) {
763 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
764 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
765 /* function 0 should set multifunction bit */
766 error_report("PCI: single function device can't be populated "
767 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
768 return -1;
770 return 0;
773 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
774 return 0;
776 /* function 0 indicates single function, so function > 0 must be NULL */
777 for (func = 1; func < PCI_FUNC_MAX; ++func) {
778 if (bus->devices[PCI_DEVFN(slot, func)]) {
779 error_report("PCI: %x.0 indicates single function, "
780 "but %x.%x is already populated.",
781 slot, slot, func);
782 return -1;
785 return 0;
788 static void pci_config_alloc(PCIDevice *pci_dev)
790 int config_size = pci_config_size(pci_dev);
792 pci_dev->config = qemu_mallocz(config_size);
793 pci_dev->cmask = qemu_mallocz(config_size);
794 pci_dev->wmask = qemu_mallocz(config_size);
795 pci_dev->w1cmask = qemu_mallocz(config_size);
796 pci_dev->config_map = qemu_mallocz(config_size);
799 static void pci_config_free(PCIDevice *pci_dev)
801 qemu_free(pci_dev->config);
802 qemu_free(pci_dev->cmask);
803 qemu_free(pci_dev->wmask);
804 qemu_free(pci_dev->w1cmask);
805 qemu_free(pci_dev->config_map);
808 /* -1 for devfn means auto assign */
809 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
810 const char *name, int devfn,
811 const PCIDeviceInfo *info)
813 PCIConfigReadFunc *config_read = info->config_read;
814 PCIConfigWriteFunc *config_write = info->config_write;
816 if (devfn < 0) {
817 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
818 devfn += PCI_FUNC_MAX) {
819 if (!bus->devices[devfn])
820 goto found;
822 error_report("PCI: no slot/function available for %s, all in use", name);
823 return NULL;
824 found: ;
825 } else if (bus->devices[devfn]) {
826 error_report("PCI: slot %d function %d not available for %s, in use by %s",
827 PCI_SLOT(devfn), PCI_FUNC(devfn), name, bus->devices[devfn]->name);
828 return NULL;
830 pci_dev->bus = bus;
831 pci_dev->devfn = devfn;
832 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
833 pci_dev->irq_state = 0;
834 pci_config_alloc(pci_dev);
836 memset(pci_dev->config_map, 0xff, PCI_CONFIG_HEADER_SIZE);
838 pci_config_set_vendor_id(pci_dev->config, info->vendor_id);
839 pci_config_set_device_id(pci_dev->config, info->device_id);
840 pci_config_set_revision(pci_dev->config, info->revision);
841 pci_config_set_class(pci_dev->config, info->class_id);
843 if (!info->is_bridge) {
844 if (info->subsystem_vendor_id || info->subsystem_id) {
845 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
846 info->subsystem_vendor_id);
847 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
848 info->subsystem_id);
849 } else {
850 pci_set_default_subsystem_id(pci_dev);
852 } else {
853 /* subsystem_vendor_id/subsystem_id are only for header type 0 */
854 assert(!info->subsystem_vendor_id);
855 assert(!info->subsystem_id);
857 pci_init_cmask(pci_dev);
858 pci_init_wmask(pci_dev);
859 pci_init_w1cmask(pci_dev);
860 if (info->is_bridge) {
861 pci_init_wmask_bridge(pci_dev);
863 if (pci_init_multifunction(bus, pci_dev)) {
864 pci_config_free(pci_dev);
865 return NULL;
868 if (!config_read)
869 config_read = pci_default_read_config;
870 if (!config_write)
871 config_write = pci_default_write_config;
872 pci_dev->config_read = config_read;
873 pci_dev->config_write = config_write;
874 bus->devices[devfn] = pci_dev;
875 pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
876 pci_dev->version_id = 2; /* Current pci device vmstate version */
877 return pci_dev;
880 static void do_pci_unregister_device(PCIDevice *pci_dev)
882 qemu_free_irqs(pci_dev->irq);
883 pci_dev->bus->devices[pci_dev->devfn] = NULL;
884 pci_config_free(pci_dev);
887 /* TODO: obsolete. eliminate this once all pci devices are qdevifed. */
888 PCIDevice *pci_register_device(PCIBus *bus, const char *name,
889 int instance_size, int devfn,
890 PCIConfigReadFunc *config_read,
891 PCIConfigWriteFunc *config_write)
893 PCIDevice *pci_dev;
894 PCIDeviceInfo info = {
895 .config_read = config_read,
896 .config_write = config_write,
899 pci_dev = qemu_mallocz(instance_size);
900 pci_dev = do_pci_register_device(pci_dev, bus, name, devfn, &info);
901 if (pci_dev == NULL) {
902 hw_error("PCI: can't register device\n");
904 return pci_dev;
907 static target_phys_addr_t pci_to_cpu_addr(PCIBus *bus,
908 target_phys_addr_t addr)
910 return addr + bus->mem_base;
913 static void pci_unregister_io_regions(PCIDevice *pci_dev)
915 PCIIORegion *r;
916 int i;
918 for(i = 0; i < PCI_NUM_REGIONS; i++) {
919 r = &pci_dev->io_regions[i];
920 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
921 continue;
922 if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
923 isa_unassign_ioport(r->addr, r->filtered_size);
924 } else {
925 cpu_register_physical_memory(pci_to_cpu_addr(pci_dev->bus,
926 r->addr),
927 r->filtered_size,
928 IO_MEM_UNASSIGNED);
933 static int pci_unregister_device(DeviceState *dev)
935 PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
936 PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
937 int ret = 0;
939 if (info->exit)
940 ret = info->exit(pci_dev);
941 if (ret)
942 return ret;
944 pci_unregister_io_regions(pci_dev);
945 pci_del_option_rom(pci_dev);
946 qemu_free(pci_dev->romfile);
947 do_pci_unregister_device(pci_dev);
948 return 0;
951 void pci_register_bar(PCIDevice *pci_dev, int region_num,
952 pcibus_t size, uint8_t type,
953 PCIMapIORegionFunc *map_func)
955 PCIIORegion *r;
956 uint32_t addr;
957 uint64_t wmask;
959 assert(region_num >= 0);
960 assert(region_num < PCI_NUM_REGIONS);
961 if (size & (size-1)) {
962 fprintf(stderr, "ERROR: PCI region size must be pow2 "
963 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
964 exit(1);
967 r = &pci_dev->io_regions[region_num];
968 r->addr = PCI_BAR_UNMAPPED;
969 r->size = size;
970 r->filtered_size = size;
971 r->type = type;
972 r->map_func = map_func;
973 r->ram_addr = IO_MEM_UNASSIGNED;
975 wmask = ~(size - 1);
976 addr = pci_bar(pci_dev, region_num);
977 if (region_num == PCI_ROM_SLOT) {
978 /* ROM enable bit is writable */
979 wmask |= PCI_ROM_ADDRESS_ENABLE;
981 pci_set_long(pci_dev->config + addr, type);
982 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
983 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
984 pci_set_quad(pci_dev->wmask + addr, wmask);
985 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
986 } else {
987 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
988 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
992 static void pci_simple_bar_mapfunc(PCIDevice *pci_dev, int region_num,
993 pcibus_t addr, pcibus_t size, int type)
995 cpu_register_physical_memory(addr, size,
996 pci_dev->io_regions[region_num].ram_addr);
999 void pci_register_bar_simple(PCIDevice *pci_dev, int region_num,
1000 pcibus_t size, uint8_t attr, ram_addr_t ram_addr)
1002 pci_register_bar(pci_dev, region_num, size,
1003 PCI_BASE_ADDRESS_SPACE_MEMORY | attr,
1004 pci_simple_bar_mapfunc);
1005 pci_dev->io_regions[region_num].ram_addr = ram_addr;
1008 static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
1009 uint8_t type)
1011 pcibus_t base = *addr;
1012 pcibus_t limit = *addr + *size - 1;
1013 PCIDevice *br;
1015 for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
1016 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1018 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1019 if (!(cmd & PCI_COMMAND_IO)) {
1020 goto no_map;
1022 } else {
1023 if (!(cmd & PCI_COMMAND_MEMORY)) {
1024 goto no_map;
1028 base = MAX(base, pci_bridge_get_base(br, type));
1029 limit = MIN(limit, pci_bridge_get_limit(br, type));
1032 if (base > limit) {
1033 goto no_map;
1035 *addr = base;
1036 *size = limit - base + 1;
1037 return;
1038 no_map:
1039 *addr = PCI_BAR_UNMAPPED;
1040 *size = 0;
1043 static pcibus_t pci_bar_address(PCIDevice *d,
1044 int reg, uint8_t type, pcibus_t size)
1046 pcibus_t new_addr, last_addr;
1047 int bar = pci_bar(d, reg);
1048 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1050 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1051 if (!(cmd & PCI_COMMAND_IO)) {
1052 return PCI_BAR_UNMAPPED;
1054 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
1055 last_addr = new_addr + size - 1;
1056 /* NOTE: we have only 64K ioports on PC */
1057 if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
1058 return PCI_BAR_UNMAPPED;
1060 return new_addr;
1063 if (!(cmd & PCI_COMMAND_MEMORY)) {
1064 return PCI_BAR_UNMAPPED;
1066 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1067 new_addr = pci_get_quad(d->config + bar);
1068 } else {
1069 new_addr = pci_get_long(d->config + bar);
1071 /* the ROM slot has a specific enable bit */
1072 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1073 return PCI_BAR_UNMAPPED;
1075 new_addr &= ~(size - 1);
1076 last_addr = new_addr + size - 1;
1077 /* NOTE: we do not support wrapping */
1078 /* XXX: as we cannot support really dynamic
1079 mappings, we handle specific values as invalid
1080 mappings. */
1081 if (last_addr <= new_addr || new_addr == 0 ||
1082 last_addr == PCI_BAR_UNMAPPED) {
1083 return PCI_BAR_UNMAPPED;
1086 /* Now pcibus_t is 64bit.
1087 * Check if 32 bit BAR wraps around explicitly.
1088 * Without this, PC ide doesn't work well.
1089 * TODO: remove this work around.
1091 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1092 return PCI_BAR_UNMAPPED;
1096 * OS is allowed to set BAR beyond its addressable
1097 * bits. For example, 32 bit OS can set 64bit bar
1098 * to >4G. Check it. TODO: we might need to support
1099 * it in the future for e.g. PAE.
1101 if (last_addr >= TARGET_PHYS_ADDR_MAX) {
1102 return PCI_BAR_UNMAPPED;
1105 return new_addr;
1108 static void pci_update_mappings(PCIDevice *d)
1110 PCIIORegion *r;
1111 int i;
1112 pcibus_t new_addr, filtered_size;
1114 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1115 r = &d->io_regions[i];
1117 /* this region isn't registered */
1118 if (!r->size)
1119 continue;
1121 new_addr = pci_bar_address(d, i, r->type, r->size);
1123 /* bridge filtering */
1124 filtered_size = r->size;
1125 if (new_addr != PCI_BAR_UNMAPPED) {
1126 pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
1129 /* This bar isn't changed */
1130 if (new_addr == r->addr && filtered_size == r->filtered_size)
1131 continue;
1133 /* now do the real mapping */
1134 if (r->addr != PCI_BAR_UNMAPPED) {
1135 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1136 int class;
1137 /* NOTE: specific hack for IDE in PC case:
1138 only one byte must be mapped. */
1139 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1140 if (class == 0x0101 && r->size == 4) {
1141 isa_unassign_ioport(r->addr + 2, 1);
1142 } else {
1143 isa_unassign_ioport(r->addr, r->filtered_size);
1145 } else {
1146 cpu_register_physical_memory(pci_to_cpu_addr(d->bus, r->addr),
1147 r->filtered_size,
1148 IO_MEM_UNASSIGNED);
1149 qemu_unregister_coalesced_mmio(r->addr, r->filtered_size);
1152 r->addr = new_addr;
1153 r->filtered_size = filtered_size;
1154 if (r->addr != PCI_BAR_UNMAPPED) {
1156 * TODO: currently almost all the map funcions assumes
1157 * filtered_size == size and addr & ~(size - 1) == addr.
1158 * However with bridge filtering, they aren't always true.
1159 * Teach them such cases, such that filtered_size < size and
1160 * addr & (size - 1) != 0.
1162 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1163 r->map_func(d, i, r->addr, r->filtered_size, r->type);
1164 } else {
1165 r->map_func(d, i, pci_to_cpu_addr(d->bus, r->addr),
1166 r->filtered_size, r->type);
1172 static inline int pci_irq_disabled(PCIDevice *d)
1174 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1177 /* Called after interrupt disabled field update in config space,
1178 * assert/deassert interrupts if necessary.
1179 * Gets original interrupt disable bit value (before update). */
1180 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1182 int i, disabled = pci_irq_disabled(d);
1183 if (disabled == was_irq_disabled)
1184 return;
1185 for (i = 0; i < PCI_NUM_PINS; ++i) {
1186 int state = pci_irq_state(d, i);
1187 pci_change_irq_level(d, i, disabled ? -state : state);
1191 uint32_t pci_default_read_config(PCIDevice *d,
1192 uint32_t address, int len)
1194 uint32_t val = 0;
1195 assert(len == 1 || len == 2 || len == 4);
1196 len = MIN(len, pci_config_size(d) - address);
1197 memcpy(&val, d->config + address, len);
1198 return le32_to_cpu(val);
1201 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
1203 int i, was_irq_disabled = pci_irq_disabled(d);
1204 uint32_t config_size = pci_config_size(d);
1206 for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
1207 uint8_t wmask = d->wmask[addr + i];
1208 uint8_t w1cmask = d->w1cmask[addr + i];
1209 assert(!(wmask & w1cmask));
1210 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1211 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1214 #ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
1215 if (kvm_enabled() && kvm_irqchip_in_kernel() &&
1216 addr >= PIIX_CONFIG_IRQ_ROUTE &&
1217 addr < PIIX_CONFIG_IRQ_ROUTE + 4)
1218 assigned_dev_update_irqs();
1219 #endif /* CONFIG_KVM_DEVICE_ASSIGNMENT */
1221 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1222 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1223 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1224 range_covers_byte(addr, l, PCI_COMMAND))
1225 pci_update_mappings(d);
1227 if (range_covers_byte(addr, l, PCI_COMMAND))
1228 pci_update_irq_disabled(d, was_irq_disabled);
1231 /***********************************************************/
1232 /* generic PCI irq support */
1234 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1235 static void pci_set_irq(void *opaque, int irq_num, int level)
1237 PCIDevice *pci_dev = opaque;
1238 int change;
1240 change = level - pci_irq_state(pci_dev, irq_num);
1241 if (!change)
1242 return;
1244 #if defined(TARGET_IA64)
1245 ioapic_set_irq(pci_dev, irq_num, level);
1246 #endif
1248 pci_set_irq_state(pci_dev, irq_num, level);
1249 pci_update_irq_status(pci_dev);
1250 if (pci_irq_disabled(pci_dev))
1251 return;
1252 pci_change_irq_level(pci_dev, irq_num, change);
1255 int pci_map_irq(PCIDevice *pci_dev, int pin)
1257 return pci_dev->bus->map_irq(pci_dev, pin);
1260 /***********************************************************/
1261 /* monitor info on PCI */
1263 typedef struct {
1264 uint16_t class;
1265 const char *desc;
1266 const char *fw_name;
1267 uint16_t fw_ign_bits;
1268 } pci_class_desc;
1270 static const pci_class_desc pci_class_descriptions[] =
1272 { 0x0001, "VGA controller", "display"},
1273 { 0x0100, "SCSI controller", "scsi"},
1274 { 0x0101, "IDE controller", "ide"},
1275 { 0x0102, "Floppy controller", "fdc"},
1276 { 0x0103, "IPI controller", "ipi"},
1277 { 0x0104, "RAID controller", "raid"},
1278 { 0x0106, "SATA controller"},
1279 { 0x0107, "SAS controller"},
1280 { 0x0180, "Storage controller"},
1281 { 0x0200, "Ethernet controller", "ethernet"},
1282 { 0x0201, "Token Ring controller", "token-ring"},
1283 { 0x0202, "FDDI controller", "fddi"},
1284 { 0x0203, "ATM controller", "atm"},
1285 { 0x0280, "Network controller"},
1286 { 0x0300, "VGA controller", "display", 0x00ff},
1287 { 0x0301, "XGA controller"},
1288 { 0x0302, "3D controller"},
1289 { 0x0380, "Display controller"},
1290 { 0x0400, "Video controller", "video"},
1291 { 0x0401, "Audio controller", "sound"},
1292 { 0x0402, "Phone"},
1293 { 0x0403, "Audio controller", "sound"},
1294 { 0x0480, "Multimedia controller"},
1295 { 0x0500, "RAM controller", "memory"},
1296 { 0x0501, "Flash controller", "flash"},
1297 { 0x0580, "Memory controller"},
1298 { 0x0600, "Host bridge", "host"},
1299 { 0x0601, "ISA bridge", "isa"},
1300 { 0x0602, "EISA bridge", "eisa"},
1301 { 0x0603, "MC bridge", "mca"},
1302 { 0x0604, "PCI bridge", "pci"},
1303 { 0x0605, "PCMCIA bridge", "pcmcia"},
1304 { 0x0606, "NUBUS bridge", "nubus"},
1305 { 0x0607, "CARDBUS bridge", "cardbus"},
1306 { 0x0608, "RACEWAY bridge"},
1307 { 0x0680, "Bridge"},
1308 { 0x0700, "Serial port", "serial"},
1309 { 0x0701, "Parallel port", "parallel"},
1310 { 0x0800, "Interrupt controller", "interrupt-controller"},
1311 { 0x0801, "DMA controller", "dma-controller"},
1312 { 0x0802, "Timer", "timer"},
1313 { 0x0803, "RTC", "rtc"},
1314 { 0x0900, "Keyboard", "keyboard"},
1315 { 0x0901, "Pen", "pen"},
1316 { 0x0902, "Mouse", "mouse"},
1317 { 0x0A00, "Dock station", "dock", 0x00ff},
1318 { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1319 { 0x0c00, "Fireware contorller", "fireware"},
1320 { 0x0c01, "Access bus controller", "access-bus"},
1321 { 0x0c02, "SSA controller", "ssa"},
1322 { 0x0c03, "USB controller", "usb"},
1323 { 0x0c04, "Fibre channel controller", "fibre-channel"},
1324 { 0, NULL}
1327 static void pci_for_each_device_under_bus(PCIBus *bus,
1328 void (*fn)(PCIBus *b, PCIDevice *d))
1330 PCIDevice *d;
1331 int devfn;
1333 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1334 d = bus->devices[devfn];
1335 if (d) {
1336 fn(bus, d);
1341 void pci_for_each_device(PCIBus *bus, int bus_num,
1342 void (*fn)(PCIBus *b, PCIDevice *d))
1344 bus = pci_find_bus(bus, bus_num);
1346 if (bus) {
1347 pci_for_each_device_under_bus(bus, fn);
1351 static void pci_device_print(Monitor *mon, QDict *device)
1353 QDict *qdict;
1354 QListEntry *entry;
1355 uint64_t addr, size;
1357 monitor_printf(mon, " Bus %2" PRId64 ", ", qdict_get_int(device, "bus"));
1358 monitor_printf(mon, "device %3" PRId64 ", function %" PRId64 ":\n",
1359 qdict_get_int(device, "slot"),
1360 qdict_get_int(device, "function"));
1361 monitor_printf(mon, " ");
1363 qdict = qdict_get_qdict(device, "class_info");
1364 if (qdict_haskey(qdict, "desc")) {
1365 monitor_printf(mon, "%s", qdict_get_str(qdict, "desc"));
1366 } else {
1367 monitor_printf(mon, "Class %04" PRId64, qdict_get_int(qdict, "class"));
1370 qdict = qdict_get_qdict(device, "id");
1371 monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
1372 qdict_get_int(qdict, "device"),
1373 qdict_get_int(qdict, "vendor"));
1375 if (qdict_haskey(device, "irq")) {
1376 monitor_printf(mon, " IRQ %" PRId64 ".\n",
1377 qdict_get_int(device, "irq"));
1380 if (qdict_haskey(device, "pci_bridge")) {
1381 QDict *info;
1383 qdict = qdict_get_qdict(device, "pci_bridge");
1385 info = qdict_get_qdict(qdict, "bus");
1386 monitor_printf(mon, " BUS %" PRId64 ".\n",
1387 qdict_get_int(info, "number"));
1388 monitor_printf(mon, " secondary bus %" PRId64 ".\n",
1389 qdict_get_int(info, "secondary"));
1390 monitor_printf(mon, " subordinate bus %" PRId64 ".\n",
1391 qdict_get_int(info, "subordinate"));
1393 info = qdict_get_qdict(qdict, "io_range");
1394 monitor_printf(mon, " IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1395 qdict_get_int(info, "base"),
1396 qdict_get_int(info, "limit"));
1398 info = qdict_get_qdict(qdict, "memory_range");
1399 monitor_printf(mon,
1400 " memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1401 qdict_get_int(info, "base"),
1402 qdict_get_int(info, "limit"));
1404 info = qdict_get_qdict(qdict, "prefetchable_range");
1405 monitor_printf(mon, " prefetchable memory range "
1406 "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
1407 qdict_get_int(info, "base"),
1408 qdict_get_int(info, "limit"));
1411 QLIST_FOREACH_ENTRY(qdict_get_qlist(device, "regions"), entry) {
1412 qdict = qobject_to_qdict(qlist_entry_obj(entry));
1413 monitor_printf(mon, " BAR%d: ", (int) qdict_get_int(qdict, "bar"));
1415 addr = qdict_get_int(qdict, "address");
1416 size = qdict_get_int(qdict, "size");
1418 if (!strcmp(qdict_get_str(qdict, "type"), "io")) {
1419 monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1420 " [0x%04"FMT_PCIBUS"].\n",
1421 addr, addr + size - 1);
1422 } else {
1423 monitor_printf(mon, "%d bit%s memory at 0x%08"FMT_PCIBUS
1424 " [0x%08"FMT_PCIBUS"].\n",
1425 qdict_get_bool(qdict, "mem_type_64") ? 64 : 32,
1426 qdict_get_bool(qdict, "prefetch") ?
1427 " prefetchable" : "", addr, addr + size - 1);
1431 monitor_printf(mon, " id \"%s\"\n", qdict_get_str(device, "qdev_id"));
1433 if (qdict_haskey(device, "pci_bridge")) {
1434 qdict = qdict_get_qdict(device, "pci_bridge");
1435 if (qdict_haskey(qdict, "devices")) {
1436 QListEntry *dev;
1437 QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1438 pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1444 void do_pci_info_print(Monitor *mon, const QObject *data)
1446 QListEntry *bus, *dev;
1448 QLIST_FOREACH_ENTRY(qobject_to_qlist(data), bus) {
1449 QDict *qdict = qobject_to_qdict(qlist_entry_obj(bus));
1450 QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1451 pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1456 static QObject *pci_get_dev_class(const PCIDevice *dev)
1458 int class;
1459 const pci_class_desc *desc;
1461 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1462 desc = pci_class_descriptions;
1463 while (desc->desc && class != desc->class)
1464 desc++;
1466 if (desc->desc) {
1467 return qobject_from_jsonf("{ 'desc': %s, 'class': %d }",
1468 desc->desc, class);
1469 } else {
1470 return qobject_from_jsonf("{ 'class': %d }", class);
1474 static QObject *pci_get_dev_id(const PCIDevice *dev)
1476 return qobject_from_jsonf("{ 'device': %d, 'vendor': %d }",
1477 pci_get_word(dev->config + PCI_VENDOR_ID),
1478 pci_get_word(dev->config + PCI_DEVICE_ID));
1481 static QObject *pci_get_regions_list(const PCIDevice *dev)
1483 int i;
1484 QList *regions_list;
1486 regions_list = qlist_new();
1488 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1489 QObject *obj;
1490 const PCIIORegion *r = &dev->io_regions[i];
1492 if (!r->size) {
1493 continue;
1496 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1497 obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'io', "
1498 "'address': %" PRId64 ", "
1499 "'size': %" PRId64 " }",
1500 i, r->addr, r->size);
1501 } else {
1502 int mem_type_64 = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64;
1504 obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'memory', "
1505 "'mem_type_64': %i, 'prefetch': %i, "
1506 "'address': %" PRId64 ", "
1507 "'size': %" PRId64 " }",
1508 i, mem_type_64,
1509 r->type & PCI_BASE_ADDRESS_MEM_PREFETCH,
1510 r->addr, r->size);
1513 qlist_append_obj(regions_list, obj);
1516 return QOBJECT(regions_list);
1519 static QObject *pci_get_devices_list(PCIBus *bus, int bus_num);
1521 static QObject *pci_get_dev_dict(PCIDevice *dev, PCIBus *bus, int bus_num)
1523 uint8_t type;
1524 QObject *obj;
1526 obj = qobject_from_jsonf("{ 'bus': %d, 'slot': %d, 'function': %d," "'class_info': %p, 'id': %p, 'regions': %p,"
1527 " 'qdev_id': %s }",
1528 bus_num,
1529 PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
1530 pci_get_dev_class(dev), pci_get_dev_id(dev),
1531 pci_get_regions_list(dev),
1532 dev->qdev.id ? dev->qdev.id : "");
1534 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1535 QDict *qdict = qobject_to_qdict(obj);
1536 qdict_put(qdict, "irq", qint_from_int(dev->config[PCI_INTERRUPT_LINE]));
1539 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1540 if (type == PCI_HEADER_TYPE_BRIDGE) {
1541 QDict *qdict;
1542 QObject *pci_bridge;
1544 pci_bridge = qobject_from_jsonf("{ 'bus': "
1545 "{ 'number': %d, 'secondary': %d, 'subordinate': %d }, "
1546 "'io_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1547 "'memory_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1548 "'prefetchable_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "} }",
1549 dev->config[PCI_PRIMARY_BUS], dev->config[PCI_SECONDARY_BUS],
1550 dev->config[PCI_SUBORDINATE_BUS],
1551 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO),
1552 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO),
1553 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1554 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1555 pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1556 PCI_BASE_ADDRESS_MEM_PREFETCH),
1557 pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1558 PCI_BASE_ADDRESS_MEM_PREFETCH));
1560 if (dev->config[PCI_SECONDARY_BUS] != 0) {
1561 PCIBus *child_bus = pci_find_bus(bus, dev->config[PCI_SECONDARY_BUS]);
1563 if (child_bus) {
1564 qdict = qobject_to_qdict(pci_bridge);
1565 qdict_put_obj(qdict, "devices",
1566 pci_get_devices_list(child_bus,
1567 dev->config[PCI_SECONDARY_BUS]));
1570 qdict = qobject_to_qdict(obj);
1571 qdict_put_obj(qdict, "pci_bridge", pci_bridge);
1574 return obj;
1577 static QObject *pci_get_devices_list(PCIBus *bus, int bus_num)
1579 int devfn;
1580 PCIDevice *dev;
1581 QList *dev_list;
1583 dev_list = qlist_new();
1585 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1586 dev = bus->devices[devfn];
1587 if (dev) {
1588 qlist_append_obj(dev_list, pci_get_dev_dict(dev, bus, bus_num));
1592 return QOBJECT(dev_list);
1595 static QObject *pci_get_bus_dict(PCIBus *bus, int bus_num)
1597 bus = pci_find_bus(bus, bus_num);
1598 if (bus) {
1599 return qobject_from_jsonf("{ 'bus': %d, 'devices': %p }",
1600 bus_num, pci_get_devices_list(bus, bus_num));
1603 return NULL;
1606 void do_pci_info(Monitor *mon, QObject **ret_data)
1608 QList *bus_list;
1609 struct PCIHostBus *host;
1611 bus_list = qlist_new();
1613 QLIST_FOREACH(host, &host_buses, next) {
1614 QObject *obj = pci_get_bus_dict(host->bus, 0);
1615 if (obj) {
1616 qlist_append_obj(bus_list, obj);
1620 *ret_data = QOBJECT(bus_list);
1623 static const char * const pci_nic_models[] = {
1624 "ne2k_pci",
1625 "i82551",
1626 "i82557b",
1627 "i82559er",
1628 "rtl8139",
1629 "e1000",
1630 "pcnet",
1631 "virtio",
1632 NULL
1635 static const char * const pci_nic_names[] = {
1636 "ne2k_pci",
1637 "i82551",
1638 "i82557b",
1639 "i82559er",
1640 "rtl8139",
1641 "e1000",
1642 "pcnet",
1643 "virtio-net-pci",
1644 NULL
1647 /* Initialize a PCI NIC. */
1648 /* FIXME callers should check for failure, but don't */
1649 PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1650 const char *default_devaddr)
1652 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1653 PCIBus *bus;
1654 int devfn;
1655 PCIDevice *pci_dev;
1656 DeviceState *dev;
1657 int i;
1659 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1660 if (i < 0)
1661 return NULL;
1663 bus = pci_get_bus_devfn(&devfn, devaddr);
1664 if (!bus) {
1665 error_report("Invalid PCI device address %s for device %s",
1666 devaddr, pci_nic_names[i]);
1667 return NULL;
1670 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1671 dev = &pci_dev->qdev;
1672 qdev_set_nic_properties(dev, nd);
1673 if (qdev_init(dev) < 0)
1674 return NULL;
1675 return pci_dev;
1678 PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1679 const char *default_devaddr)
1681 PCIDevice *res;
1683 if (qemu_show_nic_models(nd->model, pci_nic_models))
1684 exit(0);
1686 res = pci_nic_init(nd, default_model, default_devaddr);
1687 if (!res)
1688 exit(1);
1689 return res;
1692 static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1694 pci_update_mappings(d);
1697 void pci_bridge_update_mappings(PCIBus *b)
1699 PCIBus *child;
1701 pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1703 QLIST_FOREACH(child, &b->child, sibling) {
1704 pci_bridge_update_mappings(child);
1708 /* Whether a given bus number is in range of the secondary
1709 * bus of the given bridge device. */
1710 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1712 return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1713 PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1714 dev->config[PCI_SECONDARY_BUS] < bus_num &&
1715 bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1718 PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1720 PCIBus *sec;
1722 if (!bus) {
1723 return NULL;
1726 if (pci_bus_num(bus) == bus_num) {
1727 return bus;
1730 /* Consider all bus numbers in range for the host pci bridge. */
1731 if (bus->parent_dev &&
1732 !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1733 return NULL;
1736 /* try child bus */
1737 for (; bus; bus = sec) {
1738 QLIST_FOREACH(sec, &bus->child, sibling) {
1739 assert(sec->parent_dev);
1740 if (sec->parent_dev->config[PCI_SECONDARY_BUS] == bus_num) {
1741 return sec;
1743 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1744 break;
1749 return NULL;
1752 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1754 bus = pci_find_bus(bus, bus_num);
1756 if (!bus)
1757 return NULL;
1759 return bus->devices[devfn];
1762 static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1764 PCIDevice *pci_dev = (PCIDevice *)qdev;
1765 PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1766 PCIBus *bus;
1767 int rc;
1768 bool is_default_rom;
1770 /* initialize cap_present for pci_is_express() and pci_config_size() */
1771 if (info->is_express) {
1772 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1775 bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1776 pci_dev = do_pci_register_device(pci_dev, bus, base->name,
1777 pci_dev->devfn, info);
1778 if (pci_dev == NULL)
1779 return -1;
1780 if (qdev->hotplugged && info->no_hotplug) {
1781 qerror_report(QERR_DEVICE_NO_HOTPLUG, info->qdev.name);
1782 do_pci_unregister_device(pci_dev);
1783 return -1;
1785 if (info->init) {
1786 rc = info->init(pci_dev);
1787 if (rc != 0) {
1788 do_pci_unregister_device(pci_dev);
1789 return rc;
1793 /* rom loading */
1794 is_default_rom = false;
1795 if (pci_dev->romfile == NULL && info->romfile != NULL) {
1796 pci_dev->romfile = qemu_strdup(info->romfile);
1797 is_default_rom = true;
1799 pci_add_option_rom(pci_dev, is_default_rom);
1801 if (bus->hotplug) {
1802 /* Let buses differentiate between hotplug and when device is
1803 * enabled during qemu machine creation. */
1804 rc = bus->hotplug(bus->hotplug_qdev, pci_dev,
1805 qdev->hotplugged ? PCI_HOTPLUG_ENABLED:
1806 PCI_COLDPLUG_ENABLED);
1807 if (rc != 0) {
1808 int r = pci_unregister_device(&pci_dev->qdev);
1809 assert(!r);
1810 return rc;
1813 return 0;
1816 static int pci_unplug_device(DeviceState *qdev)
1818 PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1819 PCIDeviceInfo *info = container_of(qdev->info, PCIDeviceInfo, qdev);
1821 if (info->no_hotplug) {
1822 qerror_report(QERR_DEVICE_NO_HOTPLUG, info->qdev.name);
1823 return -1;
1825 return dev->bus->hotplug(dev->bus->hotplug_qdev, dev,
1826 PCI_HOTPLUG_DISABLED);
1829 void pci_qdev_register(PCIDeviceInfo *info)
1831 info->qdev.init = pci_qdev_init;
1832 info->qdev.unplug = pci_unplug_device;
1833 info->qdev.exit = pci_unregister_device;
1834 info->qdev.bus_info = &pci_bus_info;
1835 qdev_register(&info->qdev);
1838 void pci_qdev_register_many(PCIDeviceInfo *info)
1840 while (info->qdev.name) {
1841 pci_qdev_register(info);
1842 info++;
1846 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1847 const char *name)
1849 DeviceState *dev;
1851 dev = qdev_create(&bus->qbus, name);
1852 qdev_prop_set_uint32(dev, "addr", devfn);
1853 qdev_prop_set_bit(dev, "multifunction", multifunction);
1854 return DO_UPCAST(PCIDevice, qdev, dev);
1857 PCIDevice *pci_try_create_multifunction(PCIBus *bus, int devfn,
1858 bool multifunction,
1859 const char *name)
1861 DeviceState *dev;
1863 dev = qdev_try_create(&bus->qbus, name);
1864 if (!dev) {
1865 return NULL;
1867 qdev_prop_set_uint32(dev, "addr", devfn);
1868 qdev_prop_set_bit(dev, "multifunction", multifunction);
1869 return DO_UPCAST(PCIDevice, qdev, dev);
1872 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1873 bool multifunction,
1874 const char *name)
1876 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1877 qdev_init_nofail(&dev->qdev);
1878 return dev;
1881 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1883 return pci_create_multifunction(bus, devfn, false, name);
1886 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1888 return pci_create_simple_multifunction(bus, devfn, false, name);
1891 PCIDevice *pci_try_create(PCIBus *bus, int devfn, const char *name)
1893 return pci_try_create_multifunction(bus, devfn, false, name);
1896 static int pci_find_space(PCIDevice *pdev, uint8_t size)
1898 int config_size = pci_config_size(pdev);
1899 int offset = PCI_CONFIG_HEADER_SIZE;
1900 int i;
1901 for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1902 if (pdev->config_map[i])
1903 offset = i + 1;
1904 else if (i - offset + 1 == size)
1905 return offset;
1906 return 0;
1909 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1910 uint8_t *prev_p)
1912 uint8_t next, prev;
1914 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1915 return 0;
1917 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1918 prev = next + PCI_CAP_LIST_NEXT)
1919 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1920 break;
1922 if (prev_p)
1923 *prev_p = prev;
1924 return next;
1927 void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1929 cpu_register_physical_memory(addr, size, pdev->rom_offset);
1932 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
1933 This is needed for an option rom which is used for more than one device. */
1934 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
1936 uint16_t vendor_id;
1937 uint16_t device_id;
1938 uint16_t rom_vendor_id;
1939 uint16_t rom_device_id;
1940 uint16_t rom_magic;
1941 uint16_t pcir_offset;
1942 uint8_t checksum;
1944 /* Words in rom data are little endian (like in PCI configuration),
1945 so they can be read / written with pci_get_word / pci_set_word. */
1947 /* Only a valid rom will be patched. */
1948 rom_magic = pci_get_word(ptr);
1949 if (rom_magic != 0xaa55) {
1950 PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
1951 return;
1953 pcir_offset = pci_get_word(ptr + 0x18);
1954 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
1955 PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
1956 return;
1959 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
1960 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
1961 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
1962 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
1964 PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
1965 vendor_id, device_id, rom_vendor_id, rom_device_id);
1967 checksum = ptr[6];
1969 if (vendor_id != rom_vendor_id) {
1970 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
1971 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
1972 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
1973 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1974 ptr[6] = checksum;
1975 pci_set_word(ptr + pcir_offset + 4, vendor_id);
1978 if (device_id != rom_device_id) {
1979 /* Patch device id and checksum (at offset 6 for etherboot roms). */
1980 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
1981 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
1982 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1983 ptr[6] = checksum;
1984 pci_set_word(ptr + pcir_offset + 6, device_id);
1988 /* Add an option rom for the device */
1989 static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom)
1991 int size;
1992 char *path;
1993 void *ptr;
1994 char name[32];
1996 if (!pdev->romfile)
1997 return 0;
1998 if (strlen(pdev->romfile) == 0)
1999 return 0;
2001 if (!pdev->rom_bar) {
2003 * Load rom via fw_cfg instead of creating a rom bar,
2004 * for 0.11 compatibility.
2006 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2007 if (class == 0x0300) {
2008 rom_add_vga(pdev->romfile);
2009 } else {
2010 rom_add_option(pdev->romfile, -1);
2012 return 0;
2015 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2016 if (path == NULL) {
2017 path = qemu_strdup(pdev->romfile);
2020 size = get_image_size(path);
2021 if (size < 0) {
2022 error_report("%s: failed to find romfile \"%s\"",
2023 __FUNCTION__, pdev->romfile);
2024 qemu_free(path);
2025 return -1;
2027 if (size & (size - 1)) {
2028 size = 1 << qemu_fls(size);
2031 if (pdev->qdev.info->vmsd)
2032 snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);
2033 else
2034 snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);
2035 pdev->rom_offset = qemu_ram_alloc(&pdev->qdev, name, size);
2037 ptr = qemu_get_ram_ptr(pdev->rom_offset);
2038 load_image(path, ptr);
2039 qemu_free(path);
2041 if (is_default_rom) {
2042 /* Only the default rom images will be patched (if needed). */
2043 pci_patch_ids(pdev, ptr, size);
2046 qemu_put_ram_ptr(ptr);
2048 pci_register_bar(pdev, PCI_ROM_SLOT, size,
2049 0, pci_map_option_rom);
2051 return 0;
2054 static void pci_del_option_rom(PCIDevice *pdev)
2056 if (!pdev->rom_offset)
2057 return;
2059 qemu_ram_free(pdev->rom_offset);
2060 pdev->rom_offset = 0;
2064 * if !offset
2065 * Reserve space and add capability to the linked list in pci config space
2067 * if offset = 0,
2068 * Find and reserve space and add capability to the linked list
2069 * in pci config space */
2070 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2071 uint8_t offset, uint8_t size)
2073 uint8_t *config;
2074 if (!offset) {
2075 offset = pci_find_space(pdev, size);
2076 if (!offset) {
2077 return -ENOSPC;
2079 } else {
2080 int i;
2082 for (i = offset; i < offset + size; i++) {
2083 if (pdev->config_map[i]) {
2084 fprintf(stderr, "ERROR: %04x:%02x:%02x.%x "
2085 "Attempt to add PCI capability %x at offset "
2086 "%x overlaps existing capability %x at offset %x\n",
2087 pci_find_domain(pdev->bus), pci_bus_num(pdev->bus),
2088 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2089 cap_id, offset, pdev->config_map[i], i);
2090 return -EINVAL;
2095 config = pdev->config + offset;
2096 config[PCI_CAP_LIST_ID] = cap_id;
2097 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2098 pdev->config[PCI_CAPABILITY_LIST] = offset;
2099 memset(pdev->config_map + offset, cap_id, size);
2100 /* Make capability read-only by default */
2101 memset(pdev->wmask + offset, 0, size);
2102 /* Check capability by default */
2103 memset(pdev->cmask + offset, 0xFF, size);
2105 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2107 return offset;
2110 /* Unlink capability from the pci config space. */
2111 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2113 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2114 if (!offset)
2115 return;
2116 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2117 /* Make capability writable again */
2118 memset(pdev->wmask + offset, 0xff, size);
2119 memset(pdev->w1cmask + offset, 0, size);
2120 /* Clear cmask as device-specific registers can't be checked */
2121 memset(pdev->cmask + offset, 0, size);
2122 memset(pdev->config_map + offset, 0, size);
2124 if (!pdev->config[PCI_CAPABILITY_LIST]) {
2125 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2129 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2131 return pci_find_capability_list(pdev, cap_id, NULL);
2134 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2136 PCIDevice *d = (PCIDevice *)dev;
2137 const pci_class_desc *desc;
2138 char ctxt[64];
2139 PCIIORegion *r;
2140 int i, class;
2142 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2143 desc = pci_class_descriptions;
2144 while (desc->desc && class != desc->class)
2145 desc++;
2146 if (desc->desc) {
2147 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2148 } else {
2149 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2152 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2153 "pci id %04x:%04x (sub %04x:%04x)\n",
2154 indent, "", ctxt, pci_bus_num(d->bus),
2155 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2156 pci_get_word(d->config + PCI_VENDOR_ID),
2157 pci_get_word(d->config + PCI_DEVICE_ID),
2158 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2159 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2160 for (i = 0; i < PCI_NUM_REGIONS; i++) {
2161 r = &d->io_regions[i];
2162 if (!r->size)
2163 continue;
2164 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2165 " [0x%"FMT_PCIBUS"]\n",
2166 indent, "",
2167 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2168 r->addr, r->addr + r->size - 1);
2172 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2174 PCIDevice *d = (PCIDevice *)dev;
2175 const char *name = NULL;
2176 const pci_class_desc *desc = pci_class_descriptions;
2177 int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2179 while (desc->desc &&
2180 (class & ~desc->fw_ign_bits) !=
2181 (desc->class & ~desc->fw_ign_bits)) {
2182 desc++;
2185 if (desc->desc) {
2186 name = desc->fw_name;
2189 if (name) {
2190 pstrcpy(buf, len, name);
2191 } else {
2192 snprintf(buf, len, "pci%04x,%04x",
2193 pci_get_word(d->config + PCI_VENDOR_ID),
2194 pci_get_word(d->config + PCI_DEVICE_ID));
2197 return buf;
2200 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2202 PCIDevice *d = (PCIDevice *)dev;
2203 char path[50], name[33];
2204 int off;
2206 off = snprintf(path, sizeof(path), "%s@%x",
2207 pci_dev_fw_name(dev, name, sizeof name),
2208 PCI_SLOT(d->devfn));
2209 if (PCI_FUNC(d->devfn))
2210 snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2211 return strdup(path);
2214 static char *pcibus_get_dev_path(DeviceState *dev)
2216 PCIDevice *d = container_of(dev, PCIDevice, qdev);
2217 PCIDevice *t;
2218 int slot_depth;
2219 /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2220 * 00 is added here to make this format compatible with
2221 * domain:Bus:Slot.Func for systems without nested PCI bridges.
2222 * Slot.Function list specifies the slot and function numbers for all
2223 * devices on the path from root to the specific device. */
2224 char domain[] = "DDDD:00";
2225 char slot[] = ":SS.F";
2226 int domain_len = sizeof domain - 1 /* For '\0' */;
2227 int slot_len = sizeof slot - 1 /* For '\0' */;
2228 int path_len;
2229 char *path, *p;
2230 int s;
2232 /* Calculate # of slots on path between device and root. */;
2233 slot_depth = 0;
2234 for (t = d; t; t = t->bus->parent_dev) {
2235 ++slot_depth;
2238 path_len = domain_len + slot_len * slot_depth;
2240 /* Allocate memory, fill in the terminating null byte. */
2241 path = qemu_malloc(path_len + 1 /* For '\0' */);
2242 path[path_len] = '\0';
2244 /* First field is the domain. */
2245 s = snprintf(domain, sizeof domain, "%04x:00", pci_find_domain(d->bus));
2246 assert(s == domain_len);
2247 memcpy(path, domain, domain_len);
2249 /* Fill in slot numbers. We walk up from device to root, so need to print
2250 * them in the reverse order, last to first. */
2251 p = path + path_len;
2252 for (t = d; t; t = t->bus->parent_dev) {
2253 p -= slot_len;
2254 s = snprintf(slot, sizeof slot, ":%02x.%x",
2255 PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2256 assert(s == slot_len);
2257 memcpy(p, slot, slot_len);
2260 return path;
2263 static int pci_qdev_find_recursive(PCIBus *bus,
2264 const char *id, PCIDevice **pdev)
2266 DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2267 if (!qdev) {
2268 return -ENODEV;
2271 /* roughly check if given qdev is pci device */
2272 if (qdev->info->init == &pci_qdev_init &&
2273 qdev->parent_bus->info == &pci_bus_info) {
2274 *pdev = DO_UPCAST(PCIDevice, qdev, qdev);
2275 return 0;
2277 return -EINVAL;
2280 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2282 struct PCIHostBus *host;
2283 int rc = -ENODEV;
2285 QLIST_FOREACH(host, &host_buses, next) {
2286 int tmp = pci_qdev_find_recursive(host->bus, id, pdev);
2287 if (!tmp) {
2288 rc = 0;
2289 break;
2291 if (tmp != -ENODEV) {
2292 rc = tmp;
2296 return rc;