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