]> git.proxmox.com Git - mirror_qemu.git/blame - hw/pci/pci.c
Merge remote-tracking branch 'remotes/dgibson/tags/ppc-for-2.7-20160729' into staging
[mirror_qemu.git] / hw / pci / pci.c
CommitLineData
69b91039
FB
1/*
2 * QEMU PCI bus manager
3 *
4 * Copyright (c) 2004 Fabrice Bellard
5fafdf24 5 *
69b91039
FB
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
97d5408f 24#include "qemu/osdep.h"
c759b24f
MT
25#include "hw/hw.h"
26#include "hw/pci/pci.h"
27#include "hw/pci/pci_bridge.h"
06aac7bd 28#include "hw/pci/pci_bus.h"
568f0690 29#include "hw/pci/pci_host.h"
83c9089e 30#include "monitor/monitor.h"
1422e32d 31#include "net/net.h"
9c17d615 32#include "sysemu/sysemu.h"
c759b24f 33#include "hw/loader.h"
d49b6836 34#include "qemu/error-report.h"
1de7afc9 35#include "qemu/range.h"
79627472 36#include "qmp-commands.h"
7828d750 37#include "trace.h"
c759b24f
MT
38#include "hw/pci/msi.h"
39#include "hw/pci/msix.h"
022c62cb 40#include "exec/address-spaces.h"
5e954943 41#include "hw/hotplug.h"
e4024630 42#include "hw/boards.h"
f348b6d1 43#include "qemu/cutils.h"
69b91039
FB
44
45//#define DEBUG_PCI
d8d2e079 46#ifdef DEBUG_PCI
2e49d64a 47# define PCI_DPRINTF(format, ...) printf(format, ## __VA_ARGS__)
d8d2e079
IY
48#else
49# define PCI_DPRINTF(format, ...) do { } while (0)
50#endif
69b91039 51
10c4c98a 52static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
4f43c1ff 53static char *pcibus_get_dev_path(DeviceState *dev);
5e0259e7 54static char *pcibus_get_fw_dev_path(DeviceState *dev);
dcc20931 55static void pcibus_reset(BusState *qbus);
10c4c98a 56
3cb75a7c
PB
57static Property pci_props[] = {
58 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
59 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
60 DEFINE_PROP_UINT32("rombar", PCIDevice, rom_bar, 1),
61 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
62 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
63 DEFINE_PROP_BIT("command_serr_enable", PCIDevice, cap_present,
64 QEMU_PCI_CAP_SERR_BITNR, true),
6b449540
MT
65 DEFINE_PROP_BIT("x-pcie-lnksta-dllla", PCIDevice, cap_present,
66 QEMU_PCIE_LNKSTA_DLLLA_BITNR, true),
3cb75a7c
PB
67 DEFINE_PROP_END_OF_LIST()
68};
69
d2f69df7
BD
70static const VMStateDescription vmstate_pcibus = {
71 .name = "PCIBUS",
72 .version_id = 1,
73 .minimum_version_id = 1,
d49805ae 74 .fields = (VMStateField[]) {
d2f69df7
BD
75 VMSTATE_INT32_EQUAL(nirq, PCIBus),
76 VMSTATE_VARRAY_INT32(irq_count, PCIBus,
77 nirq, 0, vmstate_info_int32,
78 int32_t),
79 VMSTATE_END_OF_LIST()
80 }
81};
82
b86eacb8
MA
83static void pci_init_bus_master(PCIDevice *pci_dev)
84{
85 AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);
86
87 memory_region_init_alias(&pci_dev->bus_master_enable_region,
88 OBJECT(pci_dev), "bus master",
89 dma_as->root, 0, memory_region_size(dma_as->root));
90 memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
91 address_space_init(&pci_dev->bus_master_as,
92 &pci_dev->bus_master_enable_region, pci_dev->name);
93}
94
95static void pcibus_machine_done(Notifier *notifier, void *data)
96{
97 PCIBus *bus = container_of(notifier, PCIBus, machine_done);
98 int i;
99
100 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
101 if (bus->devices[i]) {
102 pci_init_bus_master(bus->devices[i]);
103 }
104 }
105}
106
d2f69df7
BD
107static void pci_bus_realize(BusState *qbus, Error **errp)
108{
109 PCIBus *bus = PCI_BUS(qbus);
110
b86eacb8
MA
111 bus->machine_done.notify = pcibus_machine_done;
112 qemu_add_machine_init_done_notifier(&bus->machine_done);
113
d2f69df7
BD
114 vmstate_register(NULL, -1, &vmstate_pcibus, bus);
115}
116
117static void pci_bus_unrealize(BusState *qbus, Error **errp)
118{
119 PCIBus *bus = PCI_BUS(qbus);
120
b86eacb8
MA
121 qemu_remove_machine_init_done_notifier(&bus->machine_done);
122
d2f69df7
BD
123 vmstate_unregister(NULL, &vmstate_pcibus, bus);
124}
125
ce6a28ee
MA
126static bool pcibus_is_root(PCIBus *bus)
127{
128 return !bus->parent_dev;
129}
130
602141d9
MA
131static int pcibus_num(PCIBus *bus)
132{
133 if (pcibus_is_root(bus)) {
134 return 0; /* pci host bridge */
135 }
136 return bus->parent_dev->config[PCI_SECONDARY_BUS];
137}
138
6a3042b2
MA
139static uint16_t pcibus_numa_node(PCIBus *bus)
140{
141 return NUMA_NODE_UNASSIGNED;
142}
143
0d936928
AL
144static void pci_bus_class_init(ObjectClass *klass, void *data)
145{
146 BusClass *k = BUS_CLASS(klass);
ce6a28ee 147 PCIBusClass *pbc = PCI_BUS_CLASS(klass);
0d936928
AL
148
149 k->print_dev = pcibus_dev_print;
150 k->get_dev_path = pcibus_get_dev_path;
151 k->get_fw_dev_path = pcibus_get_fw_dev_path;
d2f69df7
BD
152 k->realize = pci_bus_realize;
153 k->unrealize = pci_bus_unrealize;
0d936928 154 k->reset = pcibus_reset;
ce6a28ee
MA
155
156 pbc->is_root = pcibus_is_root;
602141d9 157 pbc->bus_num = pcibus_num;
6a3042b2 158 pbc->numa_node = pcibus_numa_node;
0d936928
AL
159}
160
161static const TypeInfo pci_bus_info = {
162 .name = TYPE_PCI_BUS,
163 .parent = TYPE_BUS,
164 .instance_size = sizeof(PCIBus),
ce6a28ee 165 .class_size = sizeof(PCIBusClass),
0d936928 166 .class_init = pci_bus_class_init,
30468f78 167};
69b91039 168
3a861c46
AW
169static const TypeInfo pcie_bus_info = {
170 .name = TYPE_PCIE_BUS,
171 .parent = TYPE_PCI_BUS,
172};
173
d662210a 174static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num);
1941d19c 175static void pci_update_mappings(PCIDevice *d);
d98f08f5 176static void pci_irq_handler(void *opaque, int irq_num, int level);
133e9b22 177static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
230741dc 178static void pci_del_option_rom(PCIDevice *pdev);
1941d19c 179
d350d97d
AL
180static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
181static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
e822a52a 182
7588e2b0 183static QLIST_HEAD(, PCIHostState) pci_host_bridges;
30468f78 184
cf8c704d 185int pci_bar(PCIDevice *d, int reg)
5330de09 186{
b3b11697
IY
187 uint8_t type;
188
189 if (reg != PCI_ROM_SLOT)
190 return PCI_BASE_ADDRESS_0 + reg * 4;
191
192 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
193 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
5330de09
MT
194}
195
d036bb21
MT
196static inline int pci_irq_state(PCIDevice *d, int irq_num)
197{
198 return (d->irq_state >> irq_num) & 0x1;
199}
200
201static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
202{
203 d->irq_state &= ~(0x1 << irq_num);
204 d->irq_state |= level << irq_num;
205}
206
207static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
208{
209 PCIBus *bus;
210 for (;;) {
211 bus = pci_dev->bus;
212 irq_num = bus->map_irq(pci_dev, irq_num);
213 if (bus->set_irq)
214 break;
215 pci_dev = bus->parent_dev;
216 }
217 bus->irq_count[irq_num] += change;
218 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
219}
220
9ddf8437
IY
221int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
222{
223 assert(irq_num >= 0);
224 assert(irq_num < bus->nirq);
225 return !!bus->irq_count[irq_num];
226}
227
f9bf77dd
MT
228/* Update interrupt status bit in config space on interrupt
229 * state change. */
230static void pci_update_irq_status(PCIDevice *dev)
231{
232 if (dev->irq_state) {
233 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
234 } else {
235 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
236 }
237}
238
4c92325b
IY
239void pci_device_deassert_intx(PCIDevice *dev)
240{
241 int i;
242 for (i = 0; i < PCI_NUM_PINS; ++i) {
d98f08f5 243 pci_irq_handler(dev, i, 0);
4c92325b
IY
244 }
245}
246
dcc20931 247static void pci_do_device_reset(PCIDevice *dev)
5330de09 248{
c0b1905b 249 int r;
6fc4925b 250
4c92325b 251 pci_device_deassert_intx(dev);
58b59014
CR
252 assert(dev->irq_state == 0);
253
ebabb67a 254 /* Clear all writable bits */
99443c21 255 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
f9aebe2e
MT
256 pci_get_word(dev->wmask + PCI_COMMAND) |
257 pci_get_word(dev->w1cmask + PCI_COMMAND));
89d437df
IY
258 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
259 pci_get_word(dev->wmask + PCI_STATUS) |
260 pci_get_word(dev->w1cmask + PCI_STATUS));
c0b1905b
MT
261 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
262 dev->config[PCI_INTERRUPT_LINE] = 0x0;
263 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
71ebd6dc
IY
264 PCIIORegion *region = &dev->io_regions[r];
265 if (!region->size) {
c0b1905b
MT
266 continue;
267 }
71ebd6dc
IY
268
269 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
270 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
271 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
272 } else {
273 pci_set_long(dev->config + pci_bar(dev, r), region->type);
274 }
c0b1905b
MT
275 }
276 pci_update_mappings(dev);
cbd2d434
JK
277
278 msi_reset(dev);
279 msix_reset(dev);
5330de09
MT
280}
281
dcc20931
PB
282/*
283 * This function is called on #RST and FLR.
284 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
285 */
286void pci_device_reset(PCIDevice *dev)
287{
288 qdev_reset_all(&dev->qdev);
289 pci_do_device_reset(dev);
290}
291
9bb33586
IY
292/*
293 * Trigger pci bus reset under a given bus.
dcc20931
PB
294 * Called via qbus_reset_all on RST# assert, after the devices
295 * have been reset qdev_reset_all-ed already.
9bb33586 296 */
dcc20931 297static void pcibus_reset(BusState *qbus)
6eaa6847 298{
81e3e75b 299 PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
6eaa6847
GN
300 int i;
301
5330de09
MT
302 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
303 if (bus->devices[i]) {
dcc20931 304 pci_do_device_reset(bus->devices[i]);
5330de09 305 }
6eaa6847 306 }
9bb33586 307
9bdbbfc3
PB
308 for (i = 0; i < bus->nirq; i++) {
309 assert(bus->irq_count[i] == 0);
310 }
9bb33586
IY
311}
312
3dbc01ae 313static void pci_host_bus_register(DeviceState *host)
e822a52a 314{
3dbc01ae 315 PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
7588e2b0
DG
316
317 QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
e822a52a
IY
318}
319
1ef7a2a2 320PCIBus *pci_find_primary_bus(void)
e822a52a 321{
9bc47305 322 PCIBus *primary_bus = NULL;
7588e2b0 323 PCIHostState *host;
e822a52a 324
7588e2b0 325 QLIST_FOREACH(host, &pci_host_bridges, next) {
9bc47305
DG
326 if (primary_bus) {
327 /* We have multiple root buses, refuse to select a primary */
328 return NULL;
e822a52a 329 }
9bc47305 330 primary_bus = host->bus;
e822a52a
IY
331 }
332
9bc47305 333 return primary_bus;
e822a52a
IY
334}
335
c473d18d 336PCIBus *pci_device_root_bus(const PCIDevice *d)
e075e788 337{
c473d18d 338 PCIBus *bus = d->bus;
e075e788 339
ce6a28ee
MA
340 while (!pci_bus_is_root(bus)) {
341 d = bus->parent_dev;
342 assert(d != NULL);
343
e075e788
IY
344 bus = d->bus;
345 }
346
c473d18d
DG
347 return bus;
348}
349
568f0690 350const char *pci_root_bus_path(PCIDevice *dev)
c473d18d 351{
568f0690
DG
352 PCIBus *rootbus = pci_device_root_bus(dev);
353 PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
354 PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
c473d18d 355
568f0690
DG
356 assert(host_bridge->bus == rootbus);
357
358 if (hc->root_bus_path) {
359 return (*hc->root_bus_path)(host_bridge, rootbus);
e075e788
IY
360 }
361
568f0690 362 return rootbus->qbus.name;
e075e788
IY
363}
364
4fec6404 365static void pci_bus_init(PCIBus *bus, DeviceState *parent,
aee97b84
AK
366 MemoryRegion *address_space_mem,
367 MemoryRegion *address_space_io,
1e39101c 368 uint8_t devfn_min)
30468f78 369{
6fa84913 370 assert(PCI_FUNC(devfn_min) == 0);
502a5395 371 bus->devfn_min = devfn_min;
5968eca3
AK
372 bus->address_space_mem = address_space_mem;
373 bus->address_space_io = address_space_io;
e822a52a
IY
374
375 /* host bridge */
376 QLIST_INIT(&bus->child);
2b8cc89a 377
3dbc01ae 378 pci_host_bus_register(parent);
21eea4b3
GH
379}
380
8c0bf9e2
AW
381bool pci_bus_is_express(PCIBus *bus)
382{
383 return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
384}
385
0889464a
AW
386bool pci_bus_is_root(PCIBus *bus)
387{
ce6a28ee 388 return PCI_BUS_GET_CLASS(bus)->is_root(bus);
0889464a
AW
389}
390
dd301ca6 391void pci_bus_new_inplace(PCIBus *bus, size_t bus_size, DeviceState *parent,
4fec6404
PB
392 const char *name,
393 MemoryRegion *address_space_mem,
394 MemoryRegion *address_space_io,
60a0e443 395 uint8_t devfn_min, const char *typename)
4fec6404 396{
fb17dfe0 397 qbus_create_inplace(bus, bus_size, typename, parent, name);
9ae91bc4 398 pci_bus_init(bus, parent, address_space_mem, address_space_io, devfn_min);
4fec6404
PB
399}
400
1e39101c 401PCIBus *pci_bus_new(DeviceState *parent, const char *name,
aee97b84
AK
402 MemoryRegion *address_space_mem,
403 MemoryRegion *address_space_io,
60a0e443 404 uint8_t devfn_min, const char *typename)
21eea4b3
GH
405{
406 PCIBus *bus;
407
60a0e443 408 bus = PCI_BUS(qbus_create(typename, parent, name));
9ae91bc4 409 pci_bus_init(bus, parent, address_space_mem, address_space_io, devfn_min);
21eea4b3
GH
410 return bus;
411}
412
413void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
414 void *irq_opaque, int nirq)
415{
416 bus->set_irq = set_irq;
417 bus->map_irq = map_irq;
418 bus->irq_opaque = irq_opaque;
419 bus->nirq = nirq;
7267c094 420 bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
21eea4b3
GH
421}
422
423PCIBus *pci_register_bus(DeviceState *parent, const char *name,
424 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
1e39101c 425 void *irq_opaque,
aee97b84
AK
426 MemoryRegion *address_space_mem,
427 MemoryRegion *address_space_io,
60a0e443 428 uint8_t devfn_min, int nirq, const char *typename)
21eea4b3
GH
429{
430 PCIBus *bus;
431
aee97b84 432 bus = pci_bus_new(parent, name, address_space_mem,
60a0e443 433 address_space_io, devfn_min, typename);
21eea4b3 434 pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
30468f78
FB
435 return bus;
436}
69b91039 437
502a5395
PB
438int pci_bus_num(PCIBus *s)
439{
602141d9 440 return PCI_BUS_GET_CLASS(s)->bus_num(s);
502a5395
PB
441}
442
6a3042b2
MA
443int pci_bus_numa_node(PCIBus *bus)
444{
445 return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
502a5395
PB
446}
447
73534f2f 448static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
30ca2aab 449{
73534f2f 450 PCIDevice *s = container_of(pv, PCIDevice, config);
e78e9ae4 451 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(s);
a9f49946 452 uint8_t *config;
52fc1d83
AZ
453 int i;
454
a9f49946 455 assert(size == pci_config_size(s));
7267c094 456 config = g_malloc(size);
a9f49946
IY
457
458 qemu_get_buffer(f, config, size);
459 for (i = 0; i < size; ++i) {
f9aebe2e
MT
460 if ((config[i] ^ s->config[i]) &
461 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
7c59364d
DDAG
462 error_report("%s: Bad config data: i=0x%x read: %x device: %x "
463 "cmask: %x wmask: %x w1cmask:%x", __func__,
464 i, config[i], s->config[i],
465 s->cmask[i], s->wmask[i], s->w1cmask[i]);
7267c094 466 g_free(config);
bd4b65ee 467 return -EINVAL;
a9f49946
IY
468 }
469 }
470 memcpy(s->config, config, size);
bd4b65ee 471
1941d19c 472 pci_update_mappings(s);
e78e9ae4 473 if (pc->is_bridge) {
f055e96b 474 PCIBridge *b = PCI_BRIDGE(s);
e78e9ae4
DK
475 pci_bridge_update_mappings(b);
476 }
52fc1d83 477
4ea375bf
GH
478 memory_region_set_enabled(&s->bus_master_enable_region,
479 pci_get_word(s->config + PCI_COMMAND)
480 & PCI_COMMAND_MASTER);
481
7267c094 482 g_free(config);
30ca2aab
FB
483 return 0;
484}
485
73534f2f 486/* just put buffer */
84e2e3eb 487static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
73534f2f 488{
dbe73d7f 489 const uint8_t **v = pv;
a9f49946 490 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
dbe73d7f 491 qemu_put_buffer(f, *v, size);
73534f2f
JQ
492}
493
494static VMStateInfo vmstate_info_pci_config = {
495 .name = "pci config",
496 .get = get_pci_config_device,
497 .put = put_pci_config_device,
498};
499
d036bb21
MT
500static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
501{
c3f8f611 502 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
d036bb21
MT
503 uint32_t irq_state[PCI_NUM_PINS];
504 int i;
505 for (i = 0; i < PCI_NUM_PINS; ++i) {
506 irq_state[i] = qemu_get_be32(f);
507 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
508 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
509 irq_state[i]);
510 return -EINVAL;
511 }
512 }
513
514 for (i = 0; i < PCI_NUM_PINS; ++i) {
515 pci_set_irq_state(s, i, irq_state[i]);
516 }
517
518 return 0;
519}
520
521static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
522{
523 int i;
c3f8f611 524 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
d036bb21
MT
525
526 for (i = 0; i < PCI_NUM_PINS; ++i) {
527 qemu_put_be32(f, pci_irq_state(s, i));
528 }
529}
530
531static VMStateInfo vmstate_info_pci_irq_state = {
532 .name = "pci irq state",
533 .get = get_pci_irq_state,
534 .put = put_pci_irq_state,
535};
536
73534f2f
JQ
537const VMStateDescription vmstate_pci_device = {
538 .name = "PCIDevice",
539 .version_id = 2,
540 .minimum_version_id = 1,
d49805ae 541 .fields = (VMStateField[]) {
3476436a 542 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
a9f49946
IY
543 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
544 vmstate_info_pci_config,
545 PCI_CONFIG_SPACE_SIZE),
d036bb21
MT
546 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
547 vmstate_info_pci_irq_state,
548 PCI_NUM_PINS * sizeof(int32_t)),
a9f49946
IY
549 VMSTATE_END_OF_LIST()
550 }
551};
552
553const VMStateDescription vmstate_pcie_device = {
1de53459 554 .name = "PCIEDevice",
a9f49946
IY
555 .version_id = 2,
556 .minimum_version_id = 1,
d49805ae 557 .fields = (VMStateField[]) {
3476436a 558 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
a9f49946
IY
559 VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
560 vmstate_info_pci_config,
561 PCIE_CONFIG_SPACE_SIZE),
d036bb21
MT
562 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
563 vmstate_info_pci_irq_state,
564 PCI_NUM_PINS * sizeof(int32_t)),
73534f2f
JQ
565 VMSTATE_END_OF_LIST()
566 }
567};
568
a9f49946
IY
569static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
570{
571 return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
572}
573
73534f2f
JQ
574void pci_device_save(PCIDevice *s, QEMUFile *f)
575{
f9bf77dd
MT
576 /* Clear interrupt status bit: it is implicit
577 * in irq_state which we are saving.
578 * This makes us compatible with old devices
579 * which never set or clear this bit. */
580 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
8118f095 581 vmstate_save_state(f, pci_get_vmstate(s), s, NULL);
f9bf77dd
MT
582 /* Restore the interrupt status bit. */
583 pci_update_irq_status(s);
73534f2f
JQ
584}
585
586int pci_device_load(PCIDevice *s, QEMUFile *f)
587{
f9bf77dd
MT
588 int ret;
589 ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
590 /* Restore the interrupt status bit. */
591 pci_update_irq_status(s);
592 return ret;
73534f2f
JQ
593}
594
5e434f4e 595static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
d350d97d 596{
5e434f4e
IY
597 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
598 pci_default_sub_vendor_id);
599 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
600 pci_default_sub_device_id);
d350d97d
AL
601}
602
880345c4 603/*
43c945f1
IY
604 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
605 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
880345c4 606 */
6dbcb819
MA
607static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
608 unsigned int *slotp, unsigned int *funcp)
880345c4
AL
609{
610 const char *p;
611 char *e;
612 unsigned long val;
613 unsigned long dom = 0, bus = 0;
43c945f1
IY
614 unsigned int slot = 0;
615 unsigned int func = 0;
880345c4
AL
616
617 p = addr;
618 val = strtoul(p, &e, 16);
619 if (e == p)
620 return -1;
621 if (*e == ':') {
622 bus = val;
623 p = e + 1;
624 val = strtoul(p, &e, 16);
625 if (e == p)
626 return -1;
627 if (*e == ':') {
628 dom = bus;
629 bus = val;
630 p = e + 1;
631 val = strtoul(p, &e, 16);
632 if (e == p)
633 return -1;
634 }
635 }
636
880345c4
AL
637 slot = val;
638
43c945f1
IY
639 if (funcp != NULL) {
640 if (*e != '.')
641 return -1;
642
643 p = e + 1;
644 val = strtoul(p, &e, 16);
645 if (e == p)
646 return -1;
647
648 func = val;
649 }
650
651 /* if funcp == NULL func is 0 */
652 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
653 return -1;
654
880345c4
AL
655 if (*e)
656 return -1;
657
880345c4
AL
658 *domp = dom;
659 *busp = bus;
660 *slotp = slot;
43c945f1
IY
661 if (funcp != NULL)
662 *funcp = func;
880345c4
AL
663 return 0;
664}
665
6dbcb819
MA
666static PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root,
667 const char *devaddr)
5607c388
MA
668{
669 int dom, bus;
670 unsigned slot;
671
1ef7a2a2
DG
672 if (!root) {
673 fprintf(stderr, "No primary PCI bus\n");
674 return NULL;
675 }
676
b645000e
S
677 assert(!root->parent_dev);
678
5607c388
MA
679 if (!devaddr) {
680 *devfnp = -1;
1ef7a2a2 681 return pci_find_bus_nr(root, 0);
5607c388
MA
682 }
683
43c945f1 684 if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
5607c388
MA
685 return NULL;
686 }
687
1ef7a2a2
DG
688 if (dom != 0) {
689 fprintf(stderr, "No support for non-zero PCI domains\n");
690 return NULL;
691 }
692
6ff534b6 693 *devfnp = PCI_DEVFN(slot, 0);
1ef7a2a2 694 return pci_find_bus_nr(root, bus);
5607c388
MA
695}
696
bd4b65ee
MT
697static void pci_init_cmask(PCIDevice *dev)
698{
699 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
700 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
701 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
702 dev->cmask[PCI_REVISION_ID] = 0xff;
703 dev->cmask[PCI_CLASS_PROG] = 0xff;
704 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
705 dev->cmask[PCI_HEADER_TYPE] = 0xff;
706 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
707}
708
b7ee1603
MT
709static void pci_init_wmask(PCIDevice *dev)
710{
a9f49946
IY
711 int config_size = pci_config_size(dev);
712
b7ee1603
MT
713 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
714 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
67a51b48 715 pci_set_word(dev->wmask + PCI_COMMAND,
a7b15a5c
MT
716 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
717 PCI_COMMAND_INTX_DISABLE);
b1aeb926
IY
718 if (dev->cap_present & QEMU_PCI_CAP_SERR) {
719 pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
720 }
3e21ffc9
IY
721
722 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
723 config_size - PCI_CONFIG_HEADER_SIZE);
b7ee1603
MT
724}
725
89d437df
IY
726static void pci_init_w1cmask(PCIDevice *dev)
727{
728 /*
f6bdfcc9 729 * Note: It's okay to set w1cmask even for readonly bits as
89d437df
IY
730 * long as their value is hardwired to 0.
731 */
732 pci_set_word(dev->w1cmask + PCI_STATUS,
733 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
734 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
735 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
736}
737
d5f27e88 738static void pci_init_mask_bridge(PCIDevice *d)
fb231628
IY
739{
740 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
741 PCI_SEC_LETENCY_TIMER */
742 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
743
744 /* base and limit */
745 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
746 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
747 pci_set_word(d->wmask + PCI_MEMORY_BASE,
748 PCI_MEMORY_RANGE_MASK & 0xffff);
749 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
750 PCI_MEMORY_RANGE_MASK & 0xffff);
751 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
752 PCI_PREF_RANGE_MASK & 0xffff);
753 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
754 PCI_PREF_RANGE_MASK & 0xffff);
755
756 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
757 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
758
d5f27e88 759 /* Supported memory and i/o types */
68917102
MT
760 d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
761 d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
d5f27e88
MT
762 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
763 PCI_PREF_RANGE_TYPE_64);
764 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
765 PCI_PREF_RANGE_TYPE_64);
766
45eb768c
MT
767 /*
768 * TODO: Bridges default to 10-bit VGA decoding but we currently only
769 * implement 16-bit decoding (no alias support).
770 */
f6bdfcc9
MT
771 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
772 PCI_BRIDGE_CTL_PARITY |
773 PCI_BRIDGE_CTL_SERR |
774 PCI_BRIDGE_CTL_ISA |
775 PCI_BRIDGE_CTL_VGA |
776 PCI_BRIDGE_CTL_VGA_16BIT |
777 PCI_BRIDGE_CTL_MASTER_ABORT |
778 PCI_BRIDGE_CTL_BUS_RESET |
779 PCI_BRIDGE_CTL_FAST_BACK |
780 PCI_BRIDGE_CTL_DISCARD |
781 PCI_BRIDGE_CTL_SEC_DISCARD |
f6bdfcc9
MT
782 PCI_BRIDGE_CTL_DISCARD_SERR);
783 /* Below does not do anything as we never set this bit, put here for
784 * completeness. */
785 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
786 PCI_BRIDGE_CTL_DISCARD_STATUS);
d5f27e88 787 d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
15ab7a75 788 d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
d5f27e88
MT
789 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
790 PCI_PREF_RANGE_TYPE_MASK);
15ab7a75
MT
791 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
792 PCI_PREF_RANGE_TYPE_MASK);
fb231628
IY
793}
794
133e9b22 795static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
6eab3de1
IY
796{
797 uint8_t slot = PCI_SLOT(dev->devfn);
798 uint8_t func;
799
800 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
801 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
802 }
803
804 /*
b0cd712c 805 * multifunction bit is interpreted in two ways as follows.
6eab3de1
IY
806 * - all functions must set the bit to 1.
807 * Example: Intel X53
808 * - function 0 must set the bit, but the rest function (> 0)
809 * is allowed to leave the bit to 0.
810 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
811 *
812 * So OS (at least Linux) checks the bit of only function 0,
813 * and doesn't see the bit of function > 0.
814 *
815 * The below check allows both interpretation.
816 */
817 if (PCI_FUNC(dev->devfn)) {
818 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
819 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
820 /* function 0 should set multifunction bit */
133e9b22
MA
821 error_setg(errp, "PCI: single function device can't be populated "
822 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
823 return;
6eab3de1 824 }
133e9b22 825 return;
6eab3de1
IY
826 }
827
828 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
133e9b22 829 return;
6eab3de1
IY
830 }
831 /* function 0 indicates single function, so function > 0 must be NULL */
832 for (func = 1; func < PCI_FUNC_MAX; ++func) {
833 if (bus->devices[PCI_DEVFN(slot, func)]) {
133e9b22
MA
834 error_setg(errp, "PCI: %x.0 indicates single function, "
835 "but %x.%x is already populated.",
836 slot, slot, func);
837 return;
6eab3de1
IY
838 }
839 }
6eab3de1
IY
840}
841
a9f49946
IY
842static void pci_config_alloc(PCIDevice *pci_dev)
843{
844 int config_size = pci_config_size(pci_dev);
845
7267c094
AL
846 pci_dev->config = g_malloc0(config_size);
847 pci_dev->cmask = g_malloc0(config_size);
848 pci_dev->wmask = g_malloc0(config_size);
849 pci_dev->w1cmask = g_malloc0(config_size);
850 pci_dev->used = g_malloc0(config_size);
a9f49946
IY
851}
852
853static void pci_config_free(PCIDevice *pci_dev)
854{
7267c094
AL
855 g_free(pci_dev->config);
856 g_free(pci_dev->cmask);
857 g_free(pci_dev->wmask);
858 g_free(pci_dev->w1cmask);
859 g_free(pci_dev->used);
a9f49946
IY
860}
861
30607764
MA
862static void do_pci_unregister_device(PCIDevice *pci_dev)
863{
864 pci_dev->bus->devices[pci_dev->devfn] = NULL;
865 pci_config_free(pci_dev);
866
867 address_space_destroy(&pci_dev->bus_master_as);
30607764
MA
868}
869
4a94b3aa
PX
870/* Extract PCIReqIDCache into BDF format */
871static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
872{
873 uint8_t bus_n;
874 uint16_t result;
875
876 switch (cache->type) {
877 case PCI_REQ_ID_BDF:
878 result = pci_get_bdf(cache->dev);
879 break;
880 case PCI_REQ_ID_SECONDARY_BUS:
881 bus_n = pci_bus_num(cache->dev->bus);
882 result = PCI_BUILD_BDF(bus_n, 0);
883 break;
884 default:
885 error_printf("Invalid PCI requester ID cache type: %d\n",
886 cache->type);
887 exit(1);
888 break;
889 }
890
891 return result;
892}
893
894/* Parse bridges up to the root complex and return requester ID
895 * cache for specific device. For full PCIe topology, the cache
896 * result would be exactly the same as getting BDF of the device.
897 * However, several tricks are required when system mixed up with
898 * legacy PCI devices and PCIe-to-PCI bridges.
899 *
900 * Here we cache the proxy device (and type) not requester ID since
901 * bus number might change from time to time.
902 */
903static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
904{
905 PCIDevice *parent;
906 PCIReqIDCache cache = {
907 .dev = dev,
908 .type = PCI_REQ_ID_BDF,
909 };
910
911 while (!pci_bus_is_root(dev->bus)) {
912 /* We are under PCI/PCIe bridges */
913 parent = dev->bus->parent_dev;
914 if (pci_is_express(parent)) {
915 if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
916 /* When we pass through PCIe-to-PCI/PCIX bridges, we
917 * override the requester ID using secondary bus
918 * number of parent bridge with zeroed devfn
919 * (pcie-to-pci bridge spec chap 2.3). */
920 cache.type = PCI_REQ_ID_SECONDARY_BUS;
921 cache.dev = dev;
922 }
923 } else {
924 /* Legacy PCI, override requester ID with the bridge's
925 * BDF upstream. When the root complex connects to
926 * legacy PCI devices (including buses), it can only
927 * obtain requester ID info from directly attached
928 * devices. If devices are attached under bridges, only
929 * the requester ID of the bridge that is directly
930 * attached to the root complex can be recognized. */
931 cache.type = PCI_REQ_ID_BDF;
932 cache.dev = parent;
933 }
934 dev = parent;
935 }
936
937 return cache;
938}
939
940uint16_t pci_requester_id(PCIDevice *dev)
941{
942 return pci_req_id_cache_extract(&dev->requester_id_cache);
943}
944
69b91039 945/* -1 for devfn means auto assign */
6b1b92d3 946static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
133e9b22
MA
947 const char *name, int devfn,
948 Error **errp)
69b91039 949{
40021f08
AL
950 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
951 PCIConfigReadFunc *config_read = pc->config_read;
952 PCIConfigWriteFunc *config_write = pc->config_write;
133e9b22 953 Error *local_err = NULL;
3f1e1478
C
954 DeviceState *dev = DEVICE(pci_dev);
955
956 pci_dev->bus = bus;
0144f6f1
MA
957 /* Only pci bridges can be attached to extra PCI root buses */
958 if (pci_bus_is_root(bus) && bus->parent_dev && !pc->is_bridge) {
959 error_setg(errp,
960 "PCI: Only PCI/PCIe bridges can be plugged into %s",
961 bus->parent_dev->name);
962 return NULL;
963 }
113f89df 964
69b91039 965 if (devfn < 0) {
b47b0706 966 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
6fa84913 967 devfn += PCI_FUNC_MAX) {
30468f78 968 if (!bus->devices[devfn])
69b91039
FB
969 goto found;
970 }
133e9b22
MA
971 error_setg(errp, "PCI: no slot/function available for %s, all in use",
972 name);
09e3acc6 973 return NULL;
69b91039 974 found: ;
07b7d053 975 } else if (bus->devices[devfn]) {
133e9b22
MA
976 error_setg(errp, "PCI: slot %d function %d not available for %s,"
977 " in use by %s",
978 PCI_SLOT(devfn), PCI_FUNC(devfn), name,
979 bus->devices[devfn]->name);
09e3acc6 980 return NULL;
3f1e1478
C
981 } else if (dev->hotplugged &&
982 pci_get_function_0(pci_dev)) {
983 error_setg(errp, "PCI: slot %d function 0 already ocuppied by %s,"
984 " new func %s cannot be exposed to guest.",
985 PCI_SLOT(devfn),
986 bus->devices[PCI_DEVFN(PCI_SLOT(devfn), 0)]->name,
987 name);
988
989 return NULL;
69b91039 990 }
e00387d5 991
efc8188e 992 pci_dev->devfn = devfn;
4a94b3aa 993 pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
e00387d5 994
b86eacb8
MA
995 if (qdev_hotplug) {
996 pci_init_bus_master(pci_dev);
997 }
69b91039 998 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
d036bb21 999 pci_dev->irq_state = 0;
a9f49946 1000 pci_config_alloc(pci_dev);
fb231628 1001
40021f08
AL
1002 pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
1003 pci_config_set_device_id(pci_dev->config, pc->device_id);
1004 pci_config_set_revision(pci_dev->config, pc->revision);
1005 pci_config_set_class(pci_dev->config, pc->class_id);
113f89df 1006
40021f08
AL
1007 if (!pc->is_bridge) {
1008 if (pc->subsystem_vendor_id || pc->subsystem_id) {
113f89df 1009 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
40021f08 1010 pc->subsystem_vendor_id);
113f89df 1011 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
40021f08 1012 pc->subsystem_id);
113f89df
IY
1013 } else {
1014 pci_set_default_subsystem_id(pci_dev);
1015 }
1016 } else {
1017 /* subsystem_vendor_id/subsystem_id are only for header type 0 */
40021f08
AL
1018 assert(!pc->subsystem_vendor_id);
1019 assert(!pc->subsystem_id);
fb231628 1020 }
bd4b65ee 1021 pci_init_cmask(pci_dev);
b7ee1603 1022 pci_init_wmask(pci_dev);
89d437df 1023 pci_init_w1cmask(pci_dev);
40021f08 1024 if (pc->is_bridge) {
d5f27e88 1025 pci_init_mask_bridge(pci_dev);
fb231628 1026 }
133e9b22
MA
1027 pci_init_multifunction(bus, pci_dev, &local_err);
1028 if (local_err) {
1029 error_propagate(errp, local_err);
30607764 1030 do_pci_unregister_device(pci_dev);
6eab3de1
IY
1031 return NULL;
1032 }
0ac32c83
FB
1033
1034 if (!config_read)
1035 config_read = pci_default_read_config;
1036 if (!config_write)
1037 config_write = pci_default_write_config;
69b91039
FB
1038 pci_dev->config_read = config_read;
1039 pci_dev->config_write = config_write;
30468f78 1040 bus->devices[devfn] = pci_dev;
f16c4abf 1041 pci_dev->version_id = 2; /* Current pci device vmstate version */
69b91039
FB
1042 return pci_dev;
1043}
1044
5851e08c
AL
1045static void pci_unregister_io_regions(PCIDevice *pci_dev)
1046{
1047 PCIIORegion *r;
1048 int i;
1049
1050 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1051 r = &pci_dev->io_regions[i];
182f9c8a 1052 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
5851e08c 1053 continue;
03952339 1054 memory_region_del_subregion(r->address_space, r->memory);
5851e08c 1055 }
e01fd687
AW
1056
1057 pci_unregister_vga(pci_dev);
5851e08c
AL
1058}
1059
133e9b22 1060static void pci_qdev_unrealize(DeviceState *dev, Error **errp)
5851e08c 1061{
40021f08
AL
1062 PCIDevice *pci_dev = PCI_DEVICE(dev);
1063 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
5851e08c
AL
1064
1065 pci_unregister_io_regions(pci_dev);
230741dc 1066 pci_del_option_rom(pci_dev);
7cf1b0fd 1067
f90c2bcd
AW
1068 if (pc->exit) {
1069 pc->exit(pci_dev);
1070 }
5851e08c 1071
925fe64a 1072 do_pci_unregister_device(pci_dev);
5851e08c
AL
1073}
1074
e824b2cc
AK
1075void pci_register_bar(PCIDevice *pci_dev, int region_num,
1076 uint8_t type, MemoryRegion *memory)
69b91039
FB
1077{
1078 PCIIORegion *r;
5178ecd8 1079 uint32_t addr; /* offset in pci config space */
5a9ff381 1080 uint64_t wmask;
cfc0be25 1081 pcibus_t size = memory_region_size(memory);
a4c20c6a 1082
2bbb9c2f
IY
1083 assert(region_num >= 0);
1084 assert(region_num < PCI_NUM_REGIONS);
a4c20c6a
AL
1085 if (size & (size-1)) {
1086 fprintf(stderr, "ERROR: PCI region size must be pow2 "
89e8b13c 1087 "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
a4c20c6a
AL
1088 exit(1);
1089 }
1090
69b91039 1091 r = &pci_dev->io_regions[region_num];
182f9c8a 1092 r->addr = PCI_BAR_UNMAPPED;
69b91039
FB
1093 r->size = size;
1094 r->type = type;
5178ecd8
C
1095 r->memory = memory;
1096 r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO
1097 ? pci_dev->bus->address_space_io
1098 : pci_dev->bus->address_space_mem;
b7ee1603
MT
1099
1100 wmask = ~(size - 1);
d7ce493a 1101 if (region_num == PCI_ROM_SLOT) {
ebabb67a 1102 /* ROM enable bit is writable */
5330de09 1103 wmask |= PCI_ROM_ADDRESS_ENABLE;
d7ce493a 1104 }
5178ecd8
C
1105
1106 addr = pci_bar(pci_dev, region_num);
b0ff8eb2 1107 pci_set_long(pci_dev->config + addr, type);
5178ecd8 1108
14421258
IY
1109 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1110 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1111 pci_set_quad(pci_dev->wmask + addr, wmask);
1112 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1113 } else {
1114 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1115 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1116 }
79ff8cb0
AK
1117}
1118
e01fd687
AW
1119static void pci_update_vga(PCIDevice *pci_dev)
1120{
1121 uint16_t cmd;
1122
1123 if (!pci_dev->has_vga) {
1124 return;
1125 }
1126
1127 cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1128
1129 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1130 cmd & PCI_COMMAND_MEMORY);
1131 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1132 cmd & PCI_COMMAND_IO);
1133 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1134 cmd & PCI_COMMAND_IO);
1135}
1136
1137void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1138 MemoryRegion *io_lo, MemoryRegion *io_hi)
1139{
1140 assert(!pci_dev->has_vga);
1141
1142 assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1143 pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1144 memory_region_add_subregion_overlap(pci_dev->bus->address_space_mem,
1145 QEMU_PCI_VGA_MEM_BASE, mem, 1);
1146
1147 assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1148 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1149 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1150 QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1151
1152 assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1153 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1154 memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1155 QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1156 pci_dev->has_vga = true;
1157
1158 pci_update_vga(pci_dev);
1159}
1160
1161void pci_unregister_vga(PCIDevice *pci_dev)
1162{
1163 if (!pci_dev->has_vga) {
1164 return;
1165 }
1166
1167 memory_region_del_subregion(pci_dev->bus->address_space_mem,
1168 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1169 memory_region_del_subregion(pci_dev->bus->address_space_io,
1170 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1171 memory_region_del_subregion(pci_dev->bus->address_space_io,
1172 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1173 pci_dev->has_vga = false;
1174}
1175
16a96f28
AK
1176pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1177{
1178 return pci_dev->io_regions[region_num].addr;
1179}
1180
876a350d
MT
1181static pcibus_t pci_bar_address(PCIDevice *d,
1182 int reg, uint8_t type, pcibus_t size)
1183{
1184 pcibus_t new_addr, last_addr;
1185 int bar = pci_bar(d, reg);
1186 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
e4024630
LV
1187 Object *machine = qdev_get_machine();
1188 ObjectClass *oc = object_get_class(machine);
1189 MachineClass *mc = MACHINE_CLASS(oc);
1190 bool allow_0_address = mc->pci_allow_0_address;
876a350d
MT
1191
1192 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1193 if (!(cmd & PCI_COMMAND_IO)) {
1194 return PCI_BAR_UNMAPPED;
1195 }
1196 new_addr = pci_get_long(d->config + bar) & ~(size - 1);
1197 last_addr = new_addr + size - 1;
9f1a029a
HP
1198 /* Check if 32 bit BAR wraps around explicitly.
1199 * TODO: make priorities correct and remove this work around.
1200 */
e4024630
LV
1201 if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1202 (!allow_0_address && new_addr == 0)) {
876a350d
MT
1203 return PCI_BAR_UNMAPPED;
1204 }
1205 return new_addr;
1206 }
1207
1208 if (!(cmd & PCI_COMMAND_MEMORY)) {
1209 return PCI_BAR_UNMAPPED;
1210 }
1211 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1212 new_addr = pci_get_quad(d->config + bar);
1213 } else {
1214 new_addr = pci_get_long(d->config + bar);
1215 }
1216 /* the ROM slot has a specific enable bit */
1217 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1218 return PCI_BAR_UNMAPPED;
1219 }
1220 new_addr &= ~(size - 1);
1221 last_addr = new_addr + size - 1;
1222 /* NOTE: we do not support wrapping */
1223 /* XXX: as we cannot support really dynamic
1224 mappings, we handle specific values as invalid
1225 mappings. */
e4024630
LV
1226 if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1227 (!allow_0_address && new_addr == 0)) {
876a350d
MT
1228 return PCI_BAR_UNMAPPED;
1229 }
1230
1231 /* Now pcibus_t is 64bit.
1232 * Check if 32 bit BAR wraps around explicitly.
1233 * Without this, PC ide doesn't work well.
1234 * TODO: remove this work around.
1235 */
1236 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1237 return PCI_BAR_UNMAPPED;
1238 }
1239
1240 /*
1241 * OS is allowed to set BAR beyond its addressable
1242 * bits. For example, 32 bit OS can set 64bit bar
1243 * to >4G. Check it. TODO: we might need to support
1244 * it in the future for e.g. PAE.
1245 */
a8170e5e 1246 if (last_addr >= HWADDR_MAX) {
876a350d
MT
1247 return PCI_BAR_UNMAPPED;
1248 }
1249
1250 return new_addr;
1251}
1252
0ac32c83
FB
1253static void pci_update_mappings(PCIDevice *d)
1254{
1255 PCIIORegion *r;
876a350d 1256 int i;
7df32ca0 1257 pcibus_t new_addr;
3b46e624 1258
8a8696a3 1259 for(i = 0; i < PCI_NUM_REGIONS; i++) {
0ac32c83 1260 r = &d->io_regions[i];
a9688570
IY
1261
1262 /* this region isn't registered */
ec503442 1263 if (!r->size)
a9688570
IY
1264 continue;
1265
876a350d 1266 new_addr = pci_bar_address(d, i, r->type, r->size);
a9688570
IY
1267
1268 /* This bar isn't changed */
7df32ca0 1269 if (new_addr == r->addr)
a9688570
IY
1270 continue;
1271
1272 /* now do the real mapping */
1273 if (r->addr != PCI_BAR_UNMAPPED) {
7828d750 1274 trace_pci_update_mappings_del(d, pci_bus_num(d->bus),
7828d750 1275 PCI_SLOT(d->devfn),
0f288f85 1276 PCI_FUNC(d->devfn),
7828d750 1277 i, r->addr, r->size);
03952339 1278 memory_region_del_subregion(r->address_space, r->memory);
0ac32c83 1279 }
a9688570
IY
1280 r->addr = new_addr;
1281 if (r->addr != PCI_BAR_UNMAPPED) {
7828d750 1282 trace_pci_update_mappings_add(d, pci_bus_num(d->bus),
7828d750 1283 PCI_SLOT(d->devfn),
0f288f85 1284 PCI_FUNC(d->devfn),
7828d750 1285 i, r->addr, r->size);
8b881e77
AK
1286 memory_region_add_subregion_overlap(r->address_space,
1287 r->addr, r->memory, 1);
a9688570 1288 }
0ac32c83 1289 }
e01fd687
AW
1290
1291 pci_update_vga(d);
0ac32c83
FB
1292}
1293
a7b15a5c
MT
1294static inline int pci_irq_disabled(PCIDevice *d)
1295{
1296 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1297}
1298
1299/* Called after interrupt disabled field update in config space,
1300 * assert/deassert interrupts if necessary.
1301 * Gets original interrupt disable bit value (before update). */
1302static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1303{
1304 int i, disabled = pci_irq_disabled(d);
1305 if (disabled == was_irq_disabled)
1306 return;
1307 for (i = 0; i < PCI_NUM_PINS; ++i) {
1308 int state = pci_irq_state(d, i);
1309 pci_change_irq_level(d, i, disabled ? -state : state);
1310 }
1311}
1312
5fafdf24 1313uint32_t pci_default_read_config(PCIDevice *d,
0ac32c83 1314 uint32_t address, int len)
69b91039 1315{
5029fe12 1316 uint32_t val = 0;
42e4126b 1317
5029fe12
IY
1318 memcpy(&val, d->config + address, len);
1319 return le32_to_cpu(val);
0ac32c83
FB
1320}
1321
d7efb7e0 1322void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
0ac32c83 1323{
a7b15a5c 1324 int i, was_irq_disabled = pci_irq_disabled(d);
d7efb7e0 1325 uint32_t val = val_in;
0ac32c83 1326
42e4126b 1327 for (i = 0; i < l; val >>= 8, ++i) {
91011d4f 1328 uint8_t wmask = d->wmask[addr + i];
92ba5f51
IY
1329 uint8_t w1cmask = d->w1cmask[addr + i];
1330 assert(!(wmask & w1cmask));
91011d4f 1331 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
92ba5f51 1332 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
0ac32c83 1333 }
260c0cd3 1334 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
edb00035
IY
1335 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1336 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
260c0cd3 1337 range_covers_byte(addr, l, PCI_COMMAND))
0ac32c83 1338 pci_update_mappings(d);
a7b15a5c 1339
1c380f94 1340 if (range_covers_byte(addr, l, PCI_COMMAND)) {
a7b15a5c 1341 pci_update_irq_disabled(d, was_irq_disabled);
1c380f94
AK
1342 memory_region_set_enabled(&d->bus_master_enable_region,
1343 pci_get_word(d->config + PCI_COMMAND)
1344 & PCI_COMMAND_MASTER);
1345 }
95d65800 1346
d7efb7e0
KO
1347 msi_write_config(d, addr, val_in, l);
1348 msix_write_config(d, addr, val_in, l);
69b91039
FB
1349}
1350
502a5395
PB
1351/***********************************************************/
1352/* generic PCI irq support */
30468f78 1353
502a5395 1354/* 0 <= irq_num <= 3. level must be 0 or 1 */
d98f08f5 1355static void pci_irq_handler(void *opaque, int irq_num, int level)
69b91039 1356{
a60380a5 1357 PCIDevice *pci_dev = opaque;
80b3ada7 1358 int change;
3b46e624 1359
d036bb21 1360 change = level - pci_irq_state(pci_dev, irq_num);
80b3ada7
PB
1361 if (!change)
1362 return;
d2b59317 1363
d036bb21 1364 pci_set_irq_state(pci_dev, irq_num, level);
f9bf77dd 1365 pci_update_irq_status(pci_dev);
a7b15a5c
MT
1366 if (pci_irq_disabled(pci_dev))
1367 return;
d036bb21 1368 pci_change_irq_level(pci_dev, irq_num, change);
69b91039
FB
1369}
1370
d98f08f5
MA
1371static inline int pci_intx(PCIDevice *pci_dev)
1372{
1373 return pci_get_byte(pci_dev->config + PCI_INTERRUPT_PIN) - 1;
1374}
1375
1376qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1377{
1378 int intx = pci_intx(pci_dev);
1379
1380 return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1381}
1382
1383void pci_set_irq(PCIDevice *pci_dev, int level)
1384{
1385 int intx = pci_intx(pci_dev);
1386 pci_irq_handler(pci_dev, intx, level);
1387}
1388
3afa9bb4
MT
1389/* Special hooks used by device assignment */
1390void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1391{
0889464a 1392 assert(pci_bus_is_root(bus));
3afa9bb4
MT
1393 bus->route_intx_to_irq = route_intx_to_irq;
1394}
1395
1396PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1397{
1398 PCIBus *bus;
1399
1400 do {
1401 bus = dev->bus;
1402 pin = bus->map_irq(dev, pin);
1403 dev = bus->parent_dev;
1404 } while (dev);
05c0621e
AW
1405
1406 if (!bus->route_intx_to_irq) {
312fd5f2 1407 error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
05c0621e
AW
1408 object_get_typename(OBJECT(bus->qbus.parent)));
1409 return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1410 }
1411
3afa9bb4 1412 return bus->route_intx_to_irq(bus->irq_opaque, pin);
0ae16251
JK
1413}
1414
d6e65d54
AW
1415bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1416{
1417 return old->mode != new->mode || old->irq != new->irq;
1418}
1419
0ae16251
JK
1420void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1421{
1422 PCIDevice *dev;
1423 PCIBus *sec;
1424 int i;
1425
1426 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1427 dev = bus->devices[i];
1428 if (dev && dev->intx_routing_notifier) {
1429 dev->intx_routing_notifier(dev);
1430 }
e5368f0d
AW
1431 }
1432
1433 QLIST_FOREACH(sec, &bus->child, sibling) {
1434 pci_bus_fire_intx_routing_notifier(sec);
0ae16251
JK
1435 }
1436}
1437
1438void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1439 PCIINTxRoutingNotifier notifier)
1440{
1441 dev->intx_routing_notifier = notifier;
69b91039
FB
1442}
1443
91e56159
IY
1444/*
1445 * PCI-to-PCI bridge specification
1446 * 9.1: Interrupt routing. Table 9-1
1447 *
1448 * the PCI Express Base Specification, Revision 2.1
1449 * 2.2.8.1: INTx interrutp signaling - Rules
1450 * the Implementation Note
1451 * Table 2-20
1452 */
1453/*
1454 * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1455 * 0-origin unlike PCI interrupt pin register.
1456 */
1457int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1458{
1459 return (pin + PCI_SLOT(pci_dev->devfn)) % PCI_NUM_PINS;
1460}
1461
502a5395
PB
1462/***********************************************************/
1463/* monitor info on PCI */
0ac32c83 1464
6650ee6d
PB
1465typedef struct {
1466 uint16_t class;
1467 const char *desc;
5e0259e7
GN
1468 const char *fw_name;
1469 uint16_t fw_ign_bits;
6650ee6d
PB
1470} pci_class_desc;
1471
09bc878a 1472static const pci_class_desc pci_class_descriptions[] =
6650ee6d 1473{
5e0259e7
GN
1474 { 0x0001, "VGA controller", "display"},
1475 { 0x0100, "SCSI controller", "scsi"},
1476 { 0x0101, "IDE controller", "ide"},
1477 { 0x0102, "Floppy controller", "fdc"},
1478 { 0x0103, "IPI controller", "ipi"},
1479 { 0x0104, "RAID controller", "raid"},
dcb5b19a
TS
1480 { 0x0106, "SATA controller"},
1481 { 0x0107, "SAS controller"},
1482 { 0x0180, "Storage controller"},
5e0259e7
GN
1483 { 0x0200, "Ethernet controller", "ethernet"},
1484 { 0x0201, "Token Ring controller", "token-ring"},
1485 { 0x0202, "FDDI controller", "fddi"},
1486 { 0x0203, "ATM controller", "atm"},
dcb5b19a 1487 { 0x0280, "Network controller"},
5e0259e7 1488 { 0x0300, "VGA controller", "display", 0x00ff},
dcb5b19a
TS
1489 { 0x0301, "XGA controller"},
1490 { 0x0302, "3D controller"},
1491 { 0x0380, "Display controller"},
5e0259e7
GN
1492 { 0x0400, "Video controller", "video"},
1493 { 0x0401, "Audio controller", "sound"},
dcb5b19a 1494 { 0x0402, "Phone"},
602ef4d9 1495 { 0x0403, "Audio controller", "sound"},
dcb5b19a 1496 { 0x0480, "Multimedia controller"},
5e0259e7
GN
1497 { 0x0500, "RAM controller", "memory"},
1498 { 0x0501, "Flash controller", "flash"},
dcb5b19a 1499 { 0x0580, "Memory controller"},
5e0259e7
GN
1500 { 0x0600, "Host bridge", "host"},
1501 { 0x0601, "ISA bridge", "isa"},
1502 { 0x0602, "EISA bridge", "eisa"},
1503 { 0x0603, "MC bridge", "mca"},
4c41425d 1504 { 0x0604, "PCI bridge", "pci-bridge"},
5e0259e7
GN
1505 { 0x0605, "PCMCIA bridge", "pcmcia"},
1506 { 0x0606, "NUBUS bridge", "nubus"},
1507 { 0x0607, "CARDBUS bridge", "cardbus"},
dcb5b19a
TS
1508 { 0x0608, "RACEWAY bridge"},
1509 { 0x0680, "Bridge"},
5e0259e7
GN
1510 { 0x0700, "Serial port", "serial"},
1511 { 0x0701, "Parallel port", "parallel"},
1512 { 0x0800, "Interrupt controller", "interrupt-controller"},
1513 { 0x0801, "DMA controller", "dma-controller"},
1514 { 0x0802, "Timer", "timer"},
1515 { 0x0803, "RTC", "rtc"},
1516 { 0x0900, "Keyboard", "keyboard"},
1517 { 0x0901, "Pen", "pen"},
1518 { 0x0902, "Mouse", "mouse"},
1519 { 0x0A00, "Dock station", "dock", 0x00ff},
1520 { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1521 { 0x0c00, "Fireware contorller", "fireware"},
1522 { 0x0c01, "Access bus controller", "access-bus"},
1523 { 0x0c02, "SSA controller", "ssa"},
1524 { 0x0c03, "USB controller", "usb"},
1525 { 0x0c04, "Fibre channel controller", "fibre-channel"},
f7748569 1526 { 0x0c05, "SMBus"},
6650ee6d
PB
1527 { 0, NULL}
1528};
1529
163c8a59 1530static void pci_for_each_device_under_bus(PCIBus *bus,
7aa8cbb9
AP
1531 void (*fn)(PCIBus *b, PCIDevice *d,
1532 void *opaque),
1533 void *opaque)
30468f78 1534{
163c8a59
LC
1535 PCIDevice *d;
1536 int devfn;
30468f78 1537
163c8a59
LC
1538 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1539 d = bus->devices[devfn];
1540 if (d) {
7aa8cbb9 1541 fn(bus, d, opaque);
163c8a59
LC
1542 }
1543 }
1544}
1545
1546void pci_for_each_device(PCIBus *bus, int bus_num,
7aa8cbb9
AP
1547 void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
1548 void *opaque)
163c8a59 1549{
d662210a 1550 bus = pci_find_bus_nr(bus, bus_num);
163c8a59
LC
1551
1552 if (bus) {
7aa8cbb9 1553 pci_for_each_device_under_bus(bus, fn, opaque);
163c8a59
LC
1554 }
1555}
1556
79627472 1557static const pci_class_desc *get_class_desc(int class)
163c8a59 1558{
79627472 1559 const pci_class_desc *desc;
163c8a59 1560
79627472
LC
1561 desc = pci_class_descriptions;
1562 while (desc->desc && class != desc->class) {
1563 desc++;
30468f78 1564 }
b4dccd8d 1565
79627472
LC
1566 return desc;
1567}
14421258 1568
79627472 1569static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num);
163c8a59 1570
79627472
LC
1571static PciMemoryRegionList *qmp_query_pci_regions(const PCIDevice *dev)
1572{
1573 PciMemoryRegionList *head = NULL, *cur_item = NULL;
1574 int i;
163c8a59 1575
79627472
LC
1576 for (i = 0; i < PCI_NUM_REGIONS; i++) {
1577 const PCIIORegion *r = &dev->io_regions[i];
1578 PciMemoryRegionList *region;
1579
1580 if (!r->size) {
1581 continue;
502a5395 1582 }
163c8a59 1583
79627472
LC
1584 region = g_malloc0(sizeof(*region));
1585 region->value = g_malloc0(sizeof(*region->value));
163c8a59 1586
79627472
LC
1587 if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1588 region->value->type = g_strdup("io");
1589 } else {
1590 region->value->type = g_strdup("memory");
1591 region->value->has_prefetch = true;
1592 region->value->prefetch = !!(r->type & PCI_BASE_ADDRESS_MEM_PREFETCH);
1593 region->value->has_mem_type_64 = true;
1594 region->value->mem_type_64 = !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
d5e4acf7 1595 }
163c8a59 1596
79627472
LC
1597 region->value->bar = i;
1598 region->value->address = r->addr;
1599 region->value->size = r->size;
163c8a59 1600
79627472
LC
1601 /* XXX: waiting for the qapi to support GSList */
1602 if (!cur_item) {
1603 head = cur_item = region;
1604 } else {
1605 cur_item->next = region;
1606 cur_item = region;
163c8a59 1607 }
80b3ada7 1608 }
384d8876 1609
79627472 1610 return head;
163c8a59
LC
1611}
1612
79627472
LC
1613static PciBridgeInfo *qmp_query_pci_bridge(PCIDevice *dev, PCIBus *bus,
1614 int bus_num)
163c8a59 1615{
79627472 1616 PciBridgeInfo *info;
9fa02cd1 1617 PciMemoryRange *range;
163c8a59 1618
9fa02cd1 1619 info = g_new0(PciBridgeInfo, 1);
163c8a59 1620
9fa02cd1
EB
1621 info->bus = g_new0(PciBusInfo, 1);
1622 info->bus->number = dev->config[PCI_PRIMARY_BUS];
1623 info->bus->secondary = dev->config[PCI_SECONDARY_BUS];
1624 info->bus->subordinate = dev->config[PCI_SUBORDINATE_BUS];
163c8a59 1625
9fa02cd1
EB
1626 range = info->bus->io_range = g_new0(PciMemoryRange, 1);
1627 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
1628 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
163c8a59 1629
9fa02cd1
EB
1630 range = info->bus->memory_range = g_new0(PciMemoryRange, 1);
1631 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1632 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
163c8a59 1633
9fa02cd1
EB
1634 range = info->bus->prefetchable_range = g_new0(PciMemoryRange, 1);
1635 range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1636 range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
163c8a59 1637
79627472 1638 if (dev->config[PCI_SECONDARY_BUS] != 0) {
d662210a 1639 PCIBus *child_bus = pci_find_bus_nr(bus, dev->config[PCI_SECONDARY_BUS]);
79627472
LC
1640 if (child_bus) {
1641 info->has_devices = true;
1642 info->devices = qmp_query_pci_devices(child_bus, dev->config[PCI_SECONDARY_BUS]);
1643 }
163c8a59
LC
1644 }
1645
79627472 1646 return info;
163c8a59
LC
1647}
1648
79627472
LC
1649static PciDeviceInfo *qmp_query_pci_device(PCIDevice *dev, PCIBus *bus,
1650 int bus_num)
163c8a59 1651{
79627472
LC
1652 const pci_class_desc *desc;
1653 PciDeviceInfo *info;
b5937f29 1654 uint8_t type;
79627472 1655 int class;
163c8a59 1656
9fa02cd1 1657 info = g_new0(PciDeviceInfo, 1);
79627472
LC
1658 info->bus = bus_num;
1659 info->slot = PCI_SLOT(dev->devfn);
1660 info->function = PCI_FUNC(dev->devfn);
1661
9fa02cd1 1662 info->class_info = g_new0(PciDeviceClass, 1);
79627472 1663 class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
9fa02cd1 1664 info->class_info->q_class = class;
79627472
LC
1665 desc = get_class_desc(class);
1666 if (desc->desc) {
9fa02cd1
EB
1667 info->class_info->has_desc = true;
1668 info->class_info->desc = g_strdup(desc->desc);
79627472
LC
1669 }
1670
9fa02cd1
EB
1671 info->id = g_new0(PciDeviceId, 1);
1672 info->id->vendor = pci_get_word(dev->config + PCI_VENDOR_ID);
1673 info->id->device = pci_get_word(dev->config + PCI_DEVICE_ID);
79627472
LC
1674 info->regions = qmp_query_pci_regions(dev);
1675 info->qdev_id = g_strdup(dev->qdev.id ? dev->qdev.id : "");
163c8a59
LC
1676
1677 if (dev->config[PCI_INTERRUPT_PIN] != 0) {
79627472
LC
1678 info->has_irq = true;
1679 info->irq = dev->config[PCI_INTERRUPT_LINE];
163c8a59
LC
1680 }
1681
b5937f29
IY
1682 type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1683 if (type == PCI_HEADER_TYPE_BRIDGE) {
79627472
LC
1684 info->has_pci_bridge = true;
1685 info->pci_bridge = qmp_query_pci_bridge(dev, bus, bus_num);
163c8a59
LC
1686 }
1687
79627472 1688 return info;
163c8a59
LC
1689}
1690
79627472 1691static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num)
384d8876 1692{
79627472 1693 PciDeviceInfoList *info, *head = NULL, *cur_item = NULL;
163c8a59 1694 PCIDevice *dev;
79627472 1695 int devfn;
163c8a59
LC
1696
1697 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1698 dev = bus->devices[devfn];
1699 if (dev) {
79627472
LC
1700 info = g_malloc0(sizeof(*info));
1701 info->value = qmp_query_pci_device(dev, bus, bus_num);
1702
1703 /* XXX: waiting for the qapi to support GSList */
1704 if (!cur_item) {
1705 head = cur_item = info;
1706 } else {
1707 cur_item->next = info;
1708 cur_item = info;
1709 }
163c8a59 1710 }
1074df4f 1711 }
163c8a59 1712
79627472 1713 return head;
1074df4f
IY
1714}
1715
79627472 1716static PciInfo *qmp_query_pci_bus(PCIBus *bus, int bus_num)
1074df4f 1717{
79627472
LC
1718 PciInfo *info = NULL;
1719
d662210a 1720 bus = pci_find_bus_nr(bus, bus_num);
502a5395 1721 if (bus) {
79627472
LC
1722 info = g_malloc0(sizeof(*info));
1723 info->bus = bus_num;
1724 info->devices = qmp_query_pci_devices(bus, bus_num);
f2aa58c6 1725 }
163c8a59 1726
79627472 1727 return info;
f2aa58c6
FB
1728}
1729
79627472 1730PciInfoList *qmp_query_pci(Error **errp)
f2aa58c6 1731{
79627472 1732 PciInfoList *info, *head = NULL, *cur_item = NULL;
7588e2b0 1733 PCIHostState *host_bridge;
163c8a59 1734
7588e2b0 1735 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
79627472 1736 info = g_malloc0(sizeof(*info));
cb2ed8b3
MA
1737 info->value = qmp_query_pci_bus(host_bridge->bus,
1738 pci_bus_num(host_bridge->bus));
79627472
LC
1739
1740 /* XXX: waiting for the qapi to support GSList */
1741 if (!cur_item) {
1742 head = cur_item = info;
1743 } else {
1744 cur_item->next = info;
1745 cur_item = info;
163c8a59 1746 }
e822a52a 1747 }
163c8a59 1748
79627472 1749 return head;
77d4bc34 1750}
a41b2ff2 1751
cb457d76
AL
1752static const char * const pci_nic_models[] = {
1753 "ne2k_pci",
1754 "i82551",
1755 "i82557b",
1756 "i82559er",
1757 "rtl8139",
1758 "e1000",
1759 "pcnet",
1760 "virtio",
1761 NULL
1762};
1763
9d07d757
PB
1764static const char * const pci_nic_names[] = {
1765 "ne2k_pci",
1766 "i82551",
1767 "i82557b",
1768 "i82559er",
1769 "rtl8139",
1770 "e1000",
1771 "pcnet",
53c25cea 1772 "virtio-net-pci",
cb457d76
AL
1773 NULL
1774};
1775
a41b2ff2 1776/* Initialize a PCI NIC. */
51f7cb97 1777PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
6dbcb819 1778 const char *default_model,
51f7cb97 1779 const char *default_devaddr)
a41b2ff2 1780{
5607c388 1781 const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
558ecef2 1782 Error *err = NULL;
07caea31 1783 PCIBus *bus;
5607c388 1784 PCIDevice *pci_dev;
9d07d757 1785 DeviceState *dev;
51f7cb97 1786 int devfn;
cb457d76
AL
1787 int i;
1788
51f7cb97
TH
1789 if (qemu_show_nic_models(nd->model, pci_nic_models)) {
1790 exit(0);
1791 }
1792
07caea31 1793 i = qemu_find_nic_model(nd, pci_nic_models, default_model);
51f7cb97
TH
1794 if (i < 0) {
1795 exit(1);
1796 }
07caea31 1797
29b358f9 1798 bus = pci_get_bus_devfn(&devfn, rootbus, devaddr);
07caea31 1799 if (!bus) {
1ecda02b
MA
1800 error_report("Invalid PCI device address %s for device %s",
1801 devaddr, pci_nic_names[i]);
51f7cb97 1802 exit(1);
07caea31
MA
1803 }
1804
499cf102 1805 pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
9ee05825 1806 dev = &pci_dev->qdev;
1cc33683 1807 qdev_set_nic_properties(dev, nd);
558ecef2
MA
1808
1809 object_property_set_bool(OBJECT(dev), true, "realized", &err);
1810 if (err) {
51f7cb97 1811 error_report_err(err);
558ecef2 1812 object_unparent(OBJECT(dev));
07caea31 1813 exit(1);
558ecef2 1814 }
51f7cb97
TH
1815
1816 return pci_dev;
07caea31
MA
1817}
1818
129d42fb
AJ
1819PCIDevice *pci_vga_init(PCIBus *bus)
1820{
1821 switch (vga_interface_type) {
1822 case VGA_CIRRUS:
1823 return pci_create_simple(bus, -1, "cirrus-vga");
1824 case VGA_QXL:
1825 return pci_create_simple(bus, -1, "qxl-vga");
1826 case VGA_STD:
1827 return pci_create_simple(bus, -1, "VGA");
1828 case VGA_VMWARE:
1829 return pci_create_simple(bus, -1, "vmware-svga");
a94f0c5c
GH
1830 case VGA_VIRTIO:
1831 return pci_create_simple(bus, -1, "virtio-vga");
129d42fb
AJ
1832 case VGA_NONE:
1833 default: /* Other non-PCI types. Checking for unsupported types is already
1834 done in vl.c. */
1835 return NULL;
1836 }
1837}
1838
929176c3
MT
1839/* Whether a given bus number is in range of the secondary
1840 * bus of the given bridge device. */
1841static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1842{
1843 return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1844 PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
09e5b819 1845 dev->config[PCI_SECONDARY_BUS] <= bus_num &&
929176c3
MT
1846 bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1847}
1848
09e5b819
MA
1849/* Whether a given bus number is in a range of a root bus */
1850static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1851{
1852 int i;
1853
1854 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1855 PCIDevice *dev = bus->devices[i];
1856
1857 if (dev && PCI_DEVICE_GET_CLASS(dev)->is_bridge) {
1858 if (pci_secondary_bus_in_range(dev, bus_num)) {
1859 return true;
1860 }
1861 }
1862 }
1863
1864 return false;
1865}
1866
d662210a 1867static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
3ae80618 1868{
470e6363 1869 PCIBus *sec;
3ae80618 1870
470e6363 1871 if (!bus) {
e822a52a 1872 return NULL;
470e6363 1873 }
3ae80618 1874
e822a52a
IY
1875 if (pci_bus_num(bus) == bus_num) {
1876 return bus;
1877 }
1878
929176c3 1879 /* Consider all bus numbers in range for the host pci bridge. */
0889464a 1880 if (!pci_bus_is_root(bus) &&
929176c3
MT
1881 !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1882 return NULL;
1883 }
1884
e822a52a 1885 /* try child bus */
929176c3
MT
1886 for (; bus; bus = sec) {
1887 QLIST_FOREACH(sec, &bus->child, sibling) {
09e5b819 1888 if (pci_bus_num(sec) == bus_num) {
929176c3
MT
1889 return sec;
1890 }
09e5b819
MA
1891 /* PXB buses assumed to be children of bus 0 */
1892 if (pci_bus_is_root(sec)) {
1893 if (pci_root_bus_in_range(sec, bus_num)) {
1894 break;
1895 }
1896 } else {
1897 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1898 break;
1899 }
c021f8e6 1900 }
e822a52a
IY
1901 }
1902 }
1903
1904 return NULL;
3ae80618
AL
1905}
1906
eb0acfdd
MT
1907void pci_for_each_bus_depth_first(PCIBus *bus,
1908 void *(*begin)(PCIBus *bus, void *parent_state),
1909 void (*end)(PCIBus *bus, void *state),
1910 void *parent_state)
1911{
1912 PCIBus *sec;
1913 void *state;
1914
1915 if (!bus) {
1916 return;
1917 }
1918
1919 if (begin) {
1920 state = begin(bus, parent_state);
1921 } else {
1922 state = parent_state;
1923 }
1924
1925 QLIST_FOREACH(sec, &bus->child, sibling) {
1926 pci_for_each_bus_depth_first(sec, begin, end, state);
1927 }
1928
1929 if (end) {
1930 end(bus, state);
1931 }
1932}
1933
1934
5256d8bf 1935PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
3ae80618 1936{
d662210a 1937 bus = pci_find_bus_nr(bus, bus_num);
3ae80618
AL
1938
1939 if (!bus)
1940 return NULL;
1941
5256d8bf 1942 return bus->devices[devfn];
3ae80618
AL
1943}
1944
133e9b22 1945static void pci_qdev_realize(DeviceState *qdev, Error **errp)
6b1b92d3
PB
1946{
1947 PCIDevice *pci_dev = (PCIDevice *)qdev;
40021f08 1948 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
133e9b22 1949 Error *local_err = NULL;
6b1b92d3 1950 PCIBus *bus;
ab85ceb1 1951 bool is_default_rom;
6b1b92d3 1952
a9f49946 1953 /* initialize cap_present for pci_is_express() and pci_config_size() */
40021f08 1954 if (pc->is_express) {
a9f49946
IY
1955 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1956 }
1957
fef7fbc9 1958 bus = PCI_BUS(qdev_get_parent_bus(qdev));
6e008585
AL
1959 pci_dev = do_pci_register_device(pci_dev, bus,
1960 object_get_typename(OBJECT(qdev)),
133e9b22 1961 pci_dev->devfn, errp);
09e3acc6 1962 if (pci_dev == NULL)
133e9b22 1963 return;
2897ae02 1964
7ee6c1e1
MA
1965 if (pc->realize) {
1966 pc->realize(pci_dev, &local_err);
1967 if (local_err) {
1968 error_propagate(errp, local_err);
c2afc922 1969 do_pci_unregister_device(pci_dev);
133e9b22 1970 return;
c2afc922 1971 }
925fe64a 1972 }
8c52c8f3
GH
1973
1974 /* rom loading */
ab85ceb1 1975 is_default_rom = false;
40021f08
AL
1976 if (pci_dev->romfile == NULL && pc->romfile != NULL) {
1977 pci_dev->romfile = g_strdup(pc->romfile);
ab85ceb1
SW
1978 is_default_rom = true;
1979 }
178e785f 1980
133e9b22
MA
1981 pci_add_option_rom(pci_dev, is_default_rom, &local_err);
1982 if (local_err) {
1983 error_propagate(errp, local_err);
1984 pci_qdev_unrealize(DEVICE(pci_dev), NULL);
1985 return;
178e785f 1986 }
ee995ffb
GH
1987}
1988
7ee6c1e1
MA
1989static void pci_default_realize(PCIDevice *dev, Error **errp)
1990{
1991 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
1992
1993 if (pc->init) {
1994 if (pc->init(dev) < 0) {
1995 error_setg(errp, "Device initialization failed");
1996 return;
1997 }
1998 }
1999}
2000
49823868
IY
2001PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
2002 const char *name)
6b1b92d3
PB
2003{
2004 DeviceState *dev;
2005
02e2da45 2006 dev = qdev_create(&bus->qbus, name);
09f1bbcd 2007 qdev_prop_set_int32(dev, "addr", devfn);
49823868 2008 qdev_prop_set_bit(dev, "multifunction", multifunction);
40021f08 2009 return PCI_DEVICE(dev);
71077c1c 2010}
6b1b92d3 2011
49823868
IY
2012PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2013 bool multifunction,
2014 const char *name)
71077c1c 2015{
49823868 2016 PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
e23a1b33 2017 qdev_init_nofail(&dev->qdev);
71077c1c 2018 return dev;
6b1b92d3 2019}
6f4cbd39 2020
49823868
IY
2021PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
2022{
2023 return pci_create_multifunction(bus, devfn, false, name);
2024}
2025
2026PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2027{
2028 return pci_create_simple_multifunction(bus, devfn, false, name);
2029}
2030
b56d701f 2031static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
6f4cbd39
MT
2032{
2033 int offset = PCI_CONFIG_HEADER_SIZE;
2034 int i;
b56d701f 2035 for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
6f4cbd39
MT
2036 if (pdev->used[i])
2037 offset = i + 1;
2038 else if (i - offset + 1 == size)
2039 return offset;
b56d701f 2040 }
6f4cbd39
MT
2041 return 0;
2042}
2043
2044static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2045 uint8_t *prev_p)
2046{
2047 uint8_t next, prev;
2048
2049 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2050 return 0;
2051
2052 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2053 prev = next + PCI_CAP_LIST_NEXT)
2054 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2055 break;
2056
2057 if (prev_p)
2058 *prev_p = prev;
2059 return next;
2060}
2061
c9abe111
JK
2062static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2063{
2064 uint8_t next, prev, found = 0;
2065
2066 if (!(pdev->used[offset])) {
2067 return 0;
2068 }
2069
2070 assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2071
2072 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2073 prev = next + PCI_CAP_LIST_NEXT) {
2074 if (next <= offset && next > found) {
2075 found = next;
2076 }
2077 }
2078 return found;
2079}
2080
ab85ceb1
SW
2081/* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2082 This is needed for an option rom which is used for more than one device. */
2083static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
2084{
2085 uint16_t vendor_id;
2086 uint16_t device_id;
2087 uint16_t rom_vendor_id;
2088 uint16_t rom_device_id;
2089 uint16_t rom_magic;
2090 uint16_t pcir_offset;
2091 uint8_t checksum;
2092
2093 /* Words in rom data are little endian (like in PCI configuration),
2094 so they can be read / written with pci_get_word / pci_set_word. */
2095
2096 /* Only a valid rom will be patched. */
2097 rom_magic = pci_get_word(ptr);
2098 if (rom_magic != 0xaa55) {
2099 PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2100 return;
2101 }
2102 pcir_offset = pci_get_word(ptr + 0x18);
2103 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2104 PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2105 return;
2106 }
2107
2108 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2109 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2110 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2111 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2112
2113 PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2114 vendor_id, device_id, rom_vendor_id, rom_device_id);
2115
2116 checksum = ptr[6];
2117
2118 if (vendor_id != rom_vendor_id) {
2119 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2120 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2121 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2122 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2123 ptr[6] = checksum;
2124 pci_set_word(ptr + pcir_offset + 4, vendor_id);
2125 }
2126
2127 if (device_id != rom_device_id) {
2128 /* Patch device id and checksum (at offset 6 for etherboot roms). */
2129 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2130 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2131 PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2132 ptr[6] = checksum;
2133 pci_set_word(ptr + pcir_offset + 6, device_id);
2134 }
2135}
2136
c2039bd0 2137/* Add an option rom for the device */
133e9b22
MA
2138static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2139 Error **errp)
c2039bd0
AL
2140{
2141 int size;
2142 char *path;
2143 void *ptr;
1724f049 2144 char name[32];
4be9f0d1 2145 const VMStateDescription *vmsd;
c2039bd0 2146
8c52c8f3 2147 if (!pdev->romfile)
133e9b22 2148 return;
8c52c8f3 2149 if (strlen(pdev->romfile) == 0)
133e9b22 2150 return;
8c52c8f3 2151
88169ddf
GH
2152 if (!pdev->rom_bar) {
2153 /*
2154 * Load rom via fw_cfg instead of creating a rom bar,
2155 * for 0.11 compatibility.
2156 */
2157 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
db80c7b9
MA
2158
2159 /*
2160 * Hot-plugged devices can't use the option ROM
2161 * if the rom bar is disabled.
2162 */
2163 if (DEVICE(pdev)->hotplugged) {
133e9b22
MA
2164 error_setg(errp, "Hot-plugged device without ROM bar"
2165 " can't have an option ROM");
2166 return;
db80c7b9
MA
2167 }
2168
88169ddf
GH
2169 if (class == 0x0300) {
2170 rom_add_vga(pdev->romfile);
2171 } else {
2e55e842 2172 rom_add_option(pdev->romfile, -1);
88169ddf 2173 }
133e9b22 2174 return;
88169ddf
GH
2175 }
2176
8c52c8f3 2177 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
c2039bd0 2178 if (path == NULL) {
7267c094 2179 path = g_strdup(pdev->romfile);
c2039bd0
AL
2180 }
2181
2182 size = get_image_size(path);
8c52c8f3 2183 if (size < 0) {
133e9b22 2184 error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
8c7f3dd0 2185 g_free(path);
133e9b22 2186 return;
8c7f3dd0 2187 } else if (size == 0) {
133e9b22 2188 error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
7267c094 2189 g_free(path);
133e9b22 2190 return;
8c52c8f3 2191 }
9bff5d81 2192 size = pow2ceil(size);
c2039bd0 2193
4be9f0d1
AL
2194 vmsd = qdev_get_vmsd(DEVICE(pdev));
2195
2196 if (vmsd) {
2197 snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2198 } else {
f79f2bfc 2199 snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
4be9f0d1 2200 }
14caaf7f 2201 pdev->has_rom = true;
f8ed85ac 2202 memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_fatal);
c5705a77 2203 vmstate_register_ram(&pdev->rom, &pdev->qdev);
14caaf7f 2204 ptr = memory_region_get_ram_ptr(&pdev->rom);
c2039bd0 2205 load_image(path, ptr);
7267c094 2206 g_free(path);
c2039bd0 2207
ab85ceb1
SW
2208 if (is_default_rom) {
2209 /* Only the default rom images will be patched (if needed). */
2210 pci_patch_ids(pdev, ptr, size);
2211 }
2212
e824b2cc 2213 pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
c2039bd0
AL
2214}
2215
230741dc
AW
2216static void pci_del_option_rom(PCIDevice *pdev)
2217{
14caaf7f 2218 if (!pdev->has_rom)
230741dc
AW
2219 return;
2220
c5705a77 2221 vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
14caaf7f 2222 pdev->has_rom = false;
230741dc
AW
2223}
2224
ca77089d 2225/*
ca77089d
IY
2226 * if offset = 0,
2227 * Find and reserve space and add capability to the linked list
9a2a6623
CH
2228 * in pci config space
2229 */
ca77089d
IY
2230int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2231 uint8_t offset, uint8_t size)
cd9aa33e
LE
2232{
2233 int ret;
2234 Error *local_err = NULL;
2235
2236 ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err);
2237 if (local_err) {
2238 assert(ret < 0);
565f65d2 2239 error_report_err(local_err);
cd9aa33e
LE
2240 } else {
2241 /* success implies a positive offset in config space */
2242 assert(ret > 0);
2243 }
2244 return ret;
2245}
2246
2247int pci_add_capability2(PCIDevice *pdev, uint8_t cap_id,
2248 uint8_t offset, uint8_t size,
2249 Error **errp)
6f4cbd39 2250{
ca77089d 2251 uint8_t *config;
c9abe111
JK
2252 int i, overlapping_cap;
2253
ca77089d
IY
2254 if (!offset) {
2255 offset = pci_find_space(pdev, size);
97fe42f1
C
2256 /* out of PCI config space is programming error */
2257 assert(offset);
c9abe111
JK
2258 } else {
2259 /* Verify that capabilities don't overlap. Note: device assignment
2260 * depends on this check to verify that the device is not broken.
2261 * Should never trigger for emulated devices, but it's helpful
2262 * for debugging these. */
2263 for (i = offset; i < offset + size; i++) {
2264 overlapping_cap = pci_find_capability_at_offset(pdev, i);
2265 if (overlapping_cap) {
cd9aa33e
LE
2266 error_setg(errp, "%s:%02x:%02x.%x "
2267 "Attempt to add PCI capability %x at offset "
2268 "%x overlaps existing capability %x at offset %x",
2269 pci_root_bus_path(pdev), pci_bus_num(pdev->bus),
2270 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2271 cap_id, offset, overlapping_cap, i);
c9abe111
JK
2272 return -EINVAL;
2273 }
2274 }
ca77089d
IY
2275 }
2276
2277 config = pdev->config + offset;
6f4cbd39
MT
2278 config[PCI_CAP_LIST_ID] = cap_id;
2279 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2280 pdev->config[PCI_CAPABILITY_LIST] = offset;
2281 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
e26631b7 2282 memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
6f4cbd39
MT
2283 /* Make capability read-only by default */
2284 memset(pdev->wmask + offset, 0, size);
bd4b65ee
MT
2285 /* Check capability by default */
2286 memset(pdev->cmask + offset, 0xFF, size);
6f4cbd39
MT
2287 return offset;
2288}
2289
2290/* Unlink capability from the pci config space. */
2291void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2292{
2293 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2294 if (!offset)
2295 return;
2296 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
ebabb67a 2297 /* Make capability writable again */
6f4cbd39 2298 memset(pdev->wmask + offset, 0xff, size);
1a4f5971 2299 memset(pdev->w1cmask + offset, 0, size);
bd4b65ee
MT
2300 /* Clear cmask as device-specific registers can't be checked */
2301 memset(pdev->cmask + offset, 0, size);
e26631b7 2302 memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
6f4cbd39
MT
2303
2304 if (!pdev->config[PCI_CAPABILITY_LIST])
2305 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2306}
2307
6f4cbd39
MT
2308uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2309{
2310 return pci_find_capability_list(pdev, cap_id, NULL);
2311}
10c4c98a
GH
2312
2313static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2314{
2315 PCIDevice *d = (PCIDevice *)dev;
2316 const pci_class_desc *desc;
2317 char ctxt[64];
2318 PCIIORegion *r;
2319 int i, class;
2320
b0ff8eb2 2321 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
10c4c98a
GH
2322 desc = pci_class_descriptions;
2323 while (desc->desc && class != desc->class)
2324 desc++;
2325 if (desc->desc) {
2326 snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2327 } else {
2328 snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2329 }
2330
2331 monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2332 "pci id %04x:%04x (sub %04x:%04x)\n",
7f5feab4 2333 indent, "", ctxt, pci_bus_num(d->bus),
e822a52a 2334 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
b0ff8eb2
IY
2335 pci_get_word(d->config + PCI_VENDOR_ID),
2336 pci_get_word(d->config + PCI_DEVICE_ID),
2337 pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2338 pci_get_word(d->config + PCI_SUBSYSTEM_ID));
10c4c98a
GH
2339 for (i = 0; i < PCI_NUM_REGIONS; i++) {
2340 r = &d->io_regions[i];
2341 if (!r->size)
2342 continue;
89e8b13c
IY
2343 monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2344 " [0x%"FMT_PCIBUS"]\n",
2345 indent, "",
0392a017 2346 i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
10c4c98a
GH
2347 r->addr, r->addr + r->size - 1);
2348 }
2349}
03587182 2350
5e0259e7
GN
2351static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2352{
2353 PCIDevice *d = (PCIDevice *)dev;
2354 const char *name = NULL;
2355 const pci_class_desc *desc = pci_class_descriptions;
2356 int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2357
2358 while (desc->desc &&
2359 (class & ~desc->fw_ign_bits) !=
2360 (desc->class & ~desc->fw_ign_bits)) {
2361 desc++;
2362 }
2363
2364 if (desc->desc) {
2365 name = desc->fw_name;
2366 }
2367
2368 if (name) {
2369 pstrcpy(buf, len, name);
2370 } else {
2371 snprintf(buf, len, "pci%04x,%04x",
2372 pci_get_word(d->config + PCI_VENDOR_ID),
2373 pci_get_word(d->config + PCI_DEVICE_ID));
2374 }
2375
2376 return buf;
2377}
2378
2379static char *pcibus_get_fw_dev_path(DeviceState *dev)
2380{
2381 PCIDevice *d = (PCIDevice *)dev;
2382 char path[50], name[33];
2383 int off;
2384
2385 off = snprintf(path, sizeof(path), "%s@%x",
2386 pci_dev_fw_name(dev, name, sizeof name),
2387 PCI_SLOT(d->devfn));
2388 if (PCI_FUNC(d->devfn))
2389 snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
a5cf8262 2390 return g_strdup(path);
5e0259e7
GN
2391}
2392
4f43c1ff
AW
2393static char *pcibus_get_dev_path(DeviceState *dev)
2394{
a6a7005d
MT
2395 PCIDevice *d = container_of(dev, PCIDevice, qdev);
2396 PCIDevice *t;
2397 int slot_depth;
2398 /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2399 * 00 is added here to make this format compatible with
2400 * domain:Bus:Slot.Func for systems without nested PCI bridges.
2401 * Slot.Function list specifies the slot and function numbers for all
2402 * devices on the path from root to the specific device. */
568f0690
DG
2403 const char *root_bus_path;
2404 int root_bus_len;
2991181a 2405 char slot[] = ":SS.F";
2991181a 2406 int slot_len = sizeof slot - 1 /* For '\0' */;
a6a7005d
MT
2407 int path_len;
2408 char *path, *p;
2991181a 2409 int s;
a6a7005d 2410
568f0690
DG
2411 root_bus_path = pci_root_bus_path(d);
2412 root_bus_len = strlen(root_bus_path);
2413
a6a7005d
MT
2414 /* Calculate # of slots on path between device and root. */;
2415 slot_depth = 0;
2416 for (t = d; t; t = t->bus->parent_dev) {
2417 ++slot_depth;
2418 }
2419
568f0690 2420 path_len = root_bus_len + slot_len * slot_depth;
a6a7005d
MT
2421
2422 /* Allocate memory, fill in the terminating null byte. */
7267c094 2423 path = g_malloc(path_len + 1 /* For '\0' */);
a6a7005d
MT
2424 path[path_len] = '\0';
2425
568f0690 2426 memcpy(path, root_bus_path, root_bus_len);
a6a7005d
MT
2427
2428 /* Fill in slot numbers. We walk up from device to root, so need to print
2429 * them in the reverse order, last to first. */
2430 p = path + path_len;
2431 for (t = d; t; t = t->bus->parent_dev) {
2432 p -= slot_len;
2991181a 2433 s = snprintf(slot, sizeof slot, ":%02x.%x",
4c900518 2434 PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2991181a
MT
2435 assert(s == slot_len);
2436 memcpy(p, slot, slot_len);
a6a7005d
MT
2437 }
2438
2439 return path;
4f43c1ff
AW
2440}
2441
f3006dd1
IY
2442static int pci_qdev_find_recursive(PCIBus *bus,
2443 const char *id, PCIDevice **pdev)
2444{
2445 DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2446 if (!qdev) {
2447 return -ENODEV;
2448 }
2449
2450 /* roughly check if given qdev is pci device */
4be9f0d1 2451 if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
40021f08 2452 *pdev = PCI_DEVICE(qdev);
f3006dd1
IY
2453 return 0;
2454 }
2455 return -EINVAL;
2456}
2457
2458int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2459{
7588e2b0 2460 PCIHostState *host_bridge;
f3006dd1
IY
2461 int rc = -ENODEV;
2462
7588e2b0
DG
2463 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2464 int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
f3006dd1
IY
2465 if (!tmp) {
2466 rc = 0;
2467 break;
2468 }
2469 if (tmp != -ENODEV) {
2470 rc = tmp;
2471 }
2472 }
2473
2474 return rc;
2475}
f5e6fed8
AK
2476
2477MemoryRegion *pci_address_space(PCIDevice *dev)
2478{
2479 return dev->bus->address_space_mem;
2480}
e11d6439
RH
2481
2482MemoryRegion *pci_address_space_io(PCIDevice *dev)
2483{
2484 return dev->bus->address_space_io;
2485}
40021f08 2486
39bffca2
AL
2487static void pci_device_class_init(ObjectClass *klass, void *data)
2488{
2489 DeviceClass *k = DEVICE_CLASS(klass);
7ee6c1e1
MA
2490 PCIDeviceClass *pc = PCI_DEVICE_CLASS(klass);
2491
133e9b22
MA
2492 k->realize = pci_qdev_realize;
2493 k->unrealize = pci_qdev_unrealize;
0d936928 2494 k->bus_type = TYPE_PCI_BUS;
bce54474 2495 k->props = pci_props;
7ee6c1e1 2496 pc->realize = pci_default_realize;
39bffca2
AL
2497}
2498
9eda7d37
AK
2499AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2500{
2501 PCIBus *bus = PCI_BUS(dev->bus);
5af2ae23 2502 PCIBus *iommu_bus = bus;
9eda7d37 2503
5af2ae23
BH
2504 while(iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2505 iommu_bus = PCI_BUS(iommu_bus->parent_dev->bus);
9eda7d37 2506 }
5af2ae23
BH
2507 if (iommu_bus && iommu_bus->iommu_fn) {
2508 return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, dev->devfn);
9eda7d37 2509 }
9eda7d37
AK
2510 return &address_space_memory;
2511}
2512
e00387d5 2513void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
5fa45de5 2514{
e00387d5
AK
2515 bus->iommu_fn = fn;
2516 bus->iommu_opaque = opaque;
5fa45de5
DG
2517}
2518
43864069
MT
2519static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2520{
2521 Range *range = opaque;
2522 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2523 uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
77d6f4ea 2524 int i;
43864069
MT
2525
2526 if (!(cmd & PCI_COMMAND_MEMORY)) {
2527 return;
2528 }
2529
2530 if (pc->is_bridge) {
2531 pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2532 pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2533
2534 base = MAX(base, 0x1ULL << 32);
2535
2536 if (limit >= base) {
2537 Range pref_range;
a0efbf16 2538 range_set_bounds(&pref_range, base, limit);
43864069
MT
2539 range_extend(range, &pref_range);
2540 }
2541 }
77d6f4ea
MT
2542 for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2543 PCIIORegion *r = &dev->io_regions[i];
a0efbf16 2544 pcibus_t lob, upb;
43864069
MT
2545 Range region_range;
2546
77d6f4ea
MT
2547 if (!r->size ||
2548 (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2549 !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2550 continue;
2551 }
77d6f4ea 2552
a0efbf16
MA
2553 lob = pci_bar_address(dev, i, r->type, r->size);
2554 upb = lob + r->size - 1;
2555 if (lob == PCI_BAR_UNMAPPED) {
43864069
MT
2556 continue;
2557 }
43864069 2558
a0efbf16 2559 lob = MAX(lob, 0x1ULL << 32);
43864069 2560
a0efbf16
MA
2561 if (upb >= lob) {
2562 range_set_bounds(&region_range, lob, upb);
43864069
MT
2563 range_extend(range, &region_range);
2564 }
2565 }
2566}
2567
2568void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2569{
a0efbf16 2570 range_make_empty(range);
43864069
MT
2571 pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2572}
2573
3f1e1478
C
2574static bool pcie_has_upstream_port(PCIDevice *dev)
2575{
2576 PCIDevice *parent_dev = pci_bridge_get_device(dev->bus);
2577
2578 /* Device associated with an upstream port.
2579 * As there are several types of these, it's easier to check the
2580 * parent device: upstream ports are always connected to
2581 * root or downstream ports.
2582 */
2583 return parent_dev &&
2584 pci_is_express(parent_dev) &&
2585 parent_dev->exp.exp_cap &&
2586 (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2587 pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2588}
2589
2590PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2591{
2592 if(pcie_has_upstream_port(pci_dev)) {
2593 /* With an upstream PCIe port, we only support 1 device at slot 0 */
2594 return pci_dev->bus->devices[0];
2595 } else {
2596 /* Other bus types might support multiple devices at slots 0-31 */
2597 return pci_dev->bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2598 }
2599}
2600
e1d4fb2d
PX
2601MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2602{
2603 MSIMessage msg;
2604 if (msix_enabled(dev)) {
2605 msg = msix_get_message(dev, vector);
2606 } else if (msi_enabled(dev)) {
2607 msg = msi_get_message(dev, vector);
2608 } else {
2609 /* Should never happen */
2610 error_report("%s: unknown interrupt type", __func__);
2611 abort();
2612 }
2613 return msg;
2614}
2615
8c43a6f0 2616static const TypeInfo pci_device_type_info = {
40021f08
AL
2617 .name = TYPE_PCI_DEVICE,
2618 .parent = TYPE_DEVICE,
2619 .instance_size = sizeof(PCIDevice),
2620 .abstract = true,
2621 .class_size = sizeof(PCIDeviceClass),
39bffca2 2622 .class_init = pci_device_class_init,
40021f08
AL
2623};
2624
83f7d43a 2625static void pci_register_types(void)
40021f08 2626{
0d936928 2627 type_register_static(&pci_bus_info);
3a861c46 2628 type_register_static(&pcie_bus_info);
40021f08
AL
2629 type_register_static(&pci_device_type_info);
2630}
2631
83f7d43a 2632type_init(pci_register_types)