master
c 3,487 lines 106 KB
Raw
1 /*
2 * QEMU PCI bus manager
3 *
4 * Copyright (c) 2004 Fabrice Bellard
5 *
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 */
24
25 #include "qemu/osdep.h"
26 #include "qemu/datadir.h"
27 #include "qemu/units.h"
28 #include "hw/acpi/pcihp.h"
29 #include "hw/core/irq.h"
30 #include "hw/pci/pci.h"
31 #include "hw/pci/pci_bridge.h"
32 #include "hw/pci/pci_bus.h"
33 #include "hw/pci/pci_host.h"
34 #include "hw/core/qdev-properties.h"
35 #include "hw/core/qdev-properties-system.h"
36 #include "migration/cpr.h"
37 #include "migration/qemu-file-types.h"
38 #include "migration/vmstate.h"
39 #include "net/net.h"
40 #include "qemu/base-arch-defs.h"
41 #include "system/numa.h"
42 #include "system/runstate.h"
43 #include "system/system.h"
44 #include "hw/core/loader.h"
45 #include "qemu/error-report.h"
46 #include "qemu/range.h"
47 #include "trace.h"
48 #include "hw/pci/msi.h"
49 #include "hw/pci/msix.h"
50 #include "hw/core/hotplug.h"
51 #include "hw/core/boards.h"
52 #include "hw/nvram/fw_cfg.h"
53 #include "qapi/error.h"
54 #include "qemu/cutils.h"
55 #include "pci-internal.h"
56
57 #include "hw/xen/xen.h"
58 #include "hw/i386/kvm/xen_evtchn.h"
59
60 bool pci_available = true;
61
62 static char *pcibus_get_dev_path(DeviceState *dev);
63 static char *pcibus_get_fw_dev_path(DeviceState *dev);
64 static void pcibus_reset_hold(Object *obj, ResetType type);
65 static bool pcie_has_upstream_port(PCIDevice *dev);
66
67 static void prop_pci_busnr_get(Object *obj, Visitor *v, const char *name,
68 void *opaque, Error **errp)
69 {
70 PCIDevice *dev = PCI_DEVICE(obj);
71 PCIBus *bus = pci_get_bus(dev);
72 uint8_t busnr;
73
74 if (!bus) {
75 error_setg(errp, "device not attached to a PCI bus");
76 return;
77 }
78 busnr = pci_bus_num(bus);
79 visit_type_uint8(v, name, &busnr, errp);
80 }
81
82 static const PropertyInfo prop_pci_busnr = {
83 .type = "busnr",
84 .get = prop_pci_busnr_get,
85 };
86
87 static const Property pci_props[] = {
88 DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
89 DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
90 DEFINE_PROP_UINT32("romsize", PCIDevice, romsize, UINT32_MAX),
91 DEFINE_PROP_INT32("rombar", PCIDevice, rom_bar, -1),
92 DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
93 QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
94 DEFINE_PROP_BIT("x-pcie-lnksta-dllla", PCIDevice, cap_present,
95 QEMU_PCIE_LNKSTA_DLLLA_BITNR, true),
96 DEFINE_PROP_STRING("failover_pair_id", PCIDevice,
97 failover_pair_id),
98 DEFINE_PROP_UINT32("acpi-index", PCIDevice, acpi_index, 0),
99 DEFINE_PROP_BIT("x-pcie-err-unc-mask", PCIDevice, cap_present,
100 QEMU_PCIE_ERR_UNC_MASK_BITNR, true),
101 DEFINE_PROP_BIT("x-pcie-ari-nextfn-1", PCIDevice, cap_present,
102 QEMU_PCIE_ARI_NEXTFN_1_BITNR, false),
103 DEFINE_PROP_SIZE32("x-max-bounce-buffer-size", PCIDevice,
104 max_bounce_buffer_size, DEFAULT_MAX_BOUNCE_BUFFER_SIZE),
105 DEFINE_PROP_STRING("sriov-pf", PCIDevice, sriov_pf),
106 DEFINE_PROP_BIT("x-pcie-ext-tag", PCIDevice, cap_present,
107 QEMU_PCIE_EXT_TAG_BITNR, true),
108 { .name = "busnr", .info = &prop_pci_busnr },
109 };
110
111 static const VMStateDescription vmstate_pcibus = {
112 .name = "PCIBUS",
113 .version_id = 1,
114 .minimum_version_id = 1,
115 .fields = (const VMStateField[]) {
116 VMSTATE_INT32_EQUAL(nirq, PCIBus),
117 VMSTATE_VARRAY_INT32(irq_count, PCIBus,
118 nirq, 0, vmstate_info_int32,
119 int32_t),
120 VMSTATE_END_OF_LIST()
121 }
122 };
123
124 static gint g_cmp_uint32(gconstpointer a, gconstpointer b, gpointer user_data)
125 {
126 return a - b;
127 }
128
129 static GSequence *pci_acpi_index_list(void)
130 {
131 static GSequence *used_acpi_index_list;
132
133 if (!used_acpi_index_list) {
134 used_acpi_index_list = g_sequence_new(NULL);
135 }
136 return used_acpi_index_list;
137 }
138
139 static void pci_set_master(PCIDevice *d, bool enable)
140 {
141 memory_region_set_enabled(&d->bus_master_enable_region, enable);
142 d->is_master = enable; /* cache the status */
143 }
144
145 static bool
146 pci_device_supports_iommu_address_space(PCIDevice *dev, Error **errp)
147 {
148 PCIBus *bus;
149 PCIBus *iommu_bus;
150 int devfn;
151
152 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
153 if (iommu_bus && iommu_bus->iommu_ops->supports_address_space) {
154 return iommu_bus->iommu_ops->supports_address_space(bus,
155 iommu_bus->iommu_opaque, devfn, errp);
156 }
157 return true;
158 }
159
160 static void pci_init_bus_master(PCIDevice *pci_dev)
161 {
162 AddressSpace *dma_as = pci_device_iommu_address_space(pci_dev);
163
164 memory_region_init_alias(&pci_dev->bus_master_enable_region,
165 OBJECT(pci_dev), "bus master",
166 dma_as->root, 0, memory_region_size(dma_as->root));
167 pci_set_master(pci_dev, false);
168 memory_region_add_subregion(&pci_dev->bus_master_container_region, 0,
169 &pci_dev->bus_master_enable_region);
170 }
171
172 static void pcibus_machine_done(Notifier *notifier, void *data)
173 {
174 PCIBus *bus = container_of(notifier, PCIBus, machine_done);
175 int i;
176
177 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
178 if (bus->devices[i]) {
179 pci_init_bus_master(bus->devices[i]);
180 }
181 }
182 }
183
184 static void pci_bus_realize(BusState *qbus, Error **errp)
185 {
186 PCIBus *bus = PCI_BUS(qbus);
187
188 bus->machine_done.notify = pcibus_machine_done;
189 qemu_add_machine_init_done_notifier(&bus->machine_done);
190
191 bus->acpi_pcihp_bsel_val = UINT32_MAX;
192
193 vmstate_register_any(NULL, &vmstate_pcibus, bus);
194 }
195
196 static void pcie_bus_realize(BusState *qbus, Error **errp)
197 {
198 PCIBus *bus = PCI_BUS(qbus);
199 Error *local_err = NULL;
200
201 pci_bus_realize(qbus, &local_err);
202 if (local_err) {
203 error_propagate(errp, local_err);
204 return;
205 }
206
207 /*
208 * A PCI-E bus can support extended config space if it's the root
209 * bus, or if the bus/bridge above it does as well
210 */
211 if (pci_bus_is_root(bus)) {
212 bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
213 } else {
214 PCIBus *parent_bus = pci_get_bus(bus->parent_dev);
215
216 if (pci_bus_allows_extended_config_space(parent_bus)) {
217 bus->flags |= PCI_BUS_EXTENDED_CONFIG_SPACE;
218 }
219 }
220 }
221
222 static void pci_bus_unrealize(BusState *qbus)
223 {
224 PCIBus *bus = PCI_BUS(qbus);
225
226 qemu_remove_machine_init_done_notifier(&bus->machine_done);
227
228 vmstate_unregister(NULL, &vmstate_pcibus, bus);
229 }
230
231 static int pcibus_num(PCIBus *bus)
232 {
233 if (pci_bus_is_root(bus)) {
234 return 0; /* pci host bridge */
235 }
236 return bus->parent_dev->config[PCI_SECONDARY_BUS];
237 }
238
239 static uint16_t pcibus_numa_node(PCIBus *bus)
240 {
241 return NUMA_NODE_UNASSIGNED;
242 }
243
244 bool pci_bus_add_fw_cfg_extra_pci_roots(FWCfgState *fw_cfg,
245 PCIBus *bus,
246 Error **errp)
247 {
248 Object *obj;
249
250 if (!bus) {
251 return true;
252 }
253 obj = OBJECT(bus);
254
255 return fw_cfg_add_file_from_generator(fw_cfg, obj->parent,
256 object_get_canonical_path_component(obj),
257 "etc/extra-pci-roots", errp);
258 }
259
260 static GByteArray *pci_bus_fw_cfg_gen_data(Object *obj, Error **errp)
261 {
262 PCIBus *bus = PCI_BUS(obj);
263 GByteArray *byte_array;
264 uint64_t extra_hosts = 0;
265
266 if (!bus) {
267 return NULL;
268 }
269
270 QLIST_FOREACH(bus, &bus->child, sibling) {
271 /* look for expander root buses */
272 if (pci_bus_is_root(bus)) {
273 extra_hosts++;
274 }
275 }
276
277 if (!extra_hosts) {
278 return NULL;
279 }
280 extra_hosts = cpu_to_le64(extra_hosts);
281
282 byte_array = g_byte_array_new();
283 g_byte_array_append(byte_array,
284 (const void *)&extra_hosts, sizeof(extra_hosts));
285
286 return byte_array;
287 }
288
289 static void pci_bus_class_init(ObjectClass *klass, const void *data)
290 {
291 BusClass *k = BUS_CLASS(klass);
292 PCIBusClass *pbc = PCI_BUS_CLASS(klass);
293 ResettableClass *rc = RESETTABLE_CLASS(klass);
294 FWCfgDataGeneratorClass *fwgc = FW_CFG_DATA_GENERATOR_CLASS(klass);
295
296 #ifdef CONFIG_HMP
297 k->print_dev = pcibus_dev_print;
298 #endif
299 k->get_dev_path = pcibus_get_dev_path;
300 k->get_fw_dev_path = pcibus_get_fw_dev_path;
301 k->realize = pci_bus_realize;
302 k->unrealize = pci_bus_unrealize;
303
304 rc->phases.hold = pcibus_reset_hold;
305
306 pbc->bus_num = pcibus_num;
307 pbc->numa_node = pcibus_numa_node;
308
309 fwgc->get_data = pci_bus_fw_cfg_gen_data;
310
311 object_class_property_add_uint32_ptr(klass, ACPI_PCIHP_PROP_BSEL,
312 offsetof(PCIBus, acpi_pcihp_bsel_val),
313 OBJ_PROP_FLAG_READWRITE);
314 }
315
316 static const TypeInfo pci_bus_info = {
317 .name = TYPE_PCI_BUS,
318 .parent = TYPE_BUS,
319 .instance_size = sizeof(PCIBus),
320 .class_size = sizeof(PCIBusClass),
321 .class_init = pci_bus_class_init,
322 .interfaces = (const InterfaceInfo[]) {
323 { TYPE_FW_CFG_DATA_GENERATOR_INTERFACE },
324 { }
325 }
326 };
327
328 static const TypeInfo cxl_interface_info = {
329 .name = INTERFACE_CXL_DEVICE,
330 .parent = TYPE_INTERFACE,
331 };
332
333 static const TypeInfo pcie_interface_info = {
334 .name = INTERFACE_PCIE_DEVICE,
335 .parent = TYPE_INTERFACE,
336 };
337
338 static const TypeInfo conventional_pci_interface_info = {
339 .name = INTERFACE_CONVENTIONAL_PCI_DEVICE,
340 .parent = TYPE_INTERFACE,
341 };
342
343 static void pcie_bus_class_init(ObjectClass *klass, const void *data)
344 {
345 BusClass *k = BUS_CLASS(klass);
346
347 k->realize = pcie_bus_realize;
348 }
349
350 static const TypeInfo pcie_bus_info = {
351 .name = TYPE_PCIE_BUS,
352 .parent = TYPE_PCI_BUS,
353 .class_init = pcie_bus_class_init,
354 };
355
356 static const TypeInfo cxl_bus_info = {
357 .name = TYPE_CXL_BUS,
358 .parent = TYPE_PCIE_BUS,
359 .class_init = pcie_bus_class_init,
360 };
361
362 static void pci_update_mappings(PCIDevice *d);
363 static void pci_irq_handler(void *opaque, int irq_num, int level);
364 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
365 static void pci_del_option_rom(PCIDevice *pdev);
366
367 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
368 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
369
370 PCIHostStateList pci_host_bridges;
371
372 int pci_bar(PCIDevice *d, int reg)
373 {
374 uint8_t type;
375
376 /* PCIe virtual functions do not have their own BARs */
377 assert(!pci_is_vf(d));
378
379 if (reg != PCI_ROM_SLOT)
380 return PCI_BASE_ADDRESS_0 + reg * 4;
381
382 type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
383 return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
384 }
385
386 static inline int pci_irq_state(PCIDevice *d, int irq_num)
387 {
388 return (d->irq_state >> irq_num) & 0x1;
389 }
390
391 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
392 {
393 d->irq_state &= ~(0x1 << irq_num);
394 d->irq_state |= level << irq_num;
395 }
396
397 static void pci_bus_change_irq_level(PCIBus *bus, int irq_num, int change)
398 {
399 assert(irq_num >= 0);
400 assert(irq_num < bus->nirq);
401 bus->irq_count[irq_num] += change;
402 bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
403 }
404
405 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
406 {
407 PCIBus *bus;
408 for (;;) {
409 int dev_irq = irq_num;
410 bus = pci_get_bus(pci_dev);
411 assert(bus->map_irq);
412 irq_num = bus->map_irq(pci_dev, irq_num);
413 trace_pci_route_irq(dev_irq, DEVICE(pci_dev)->canonical_path, irq_num,
414 pci_bus_is_root(bus) ? "root-complex"
415 : DEVICE(bus->parent_dev)->canonical_path);
416 if (bus->set_irq)
417 break;
418 pci_dev = bus->parent_dev;
419 }
420 pci_bus_change_irq_level(bus, irq_num, change);
421 }
422
423 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
424 {
425 assert(irq_num >= 0);
426 assert(irq_num < bus->nirq);
427 return !!bus->irq_count[irq_num];
428 }
429
430 /* Update interrupt status bit in config space on interrupt
431 * state change. */
432 static void pci_update_irq_status(PCIDevice *dev)
433 {
434 if (dev->irq_state) {
435 dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
436 } else {
437 dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
438 }
439 }
440
441 void pci_device_deassert_intx(PCIDevice *dev)
442 {
443 int i;
444 for (i = 0; i < PCI_NUM_PINS; ++i) {
445 pci_irq_handler(dev, i, 0);
446 }
447 }
448
449 static void pci_msi_trigger(PCIDevice *dev, MSIMessage msg)
450 {
451 MemTxAttrs attrs = {};
452
453 /*
454 * Xen uses the high bits of the address to contain some of the bits
455 * of the PIRQ#. Therefore we can't just send the write cycle and
456 * trust that it's caught by the APIC at 0xfee00000 because the
457 * target of the write might be e.g. 0x0x1000fee46000 for PIRQ#4166.
458 * So we intercept the delivery here instead of in kvm_send_msi().
459 */
460 if (xen_mode == XEN_EMULATE &&
461 xen_evtchn_deliver_pirq_msi(msg.address, msg.data)) {
462 return;
463 }
464 attrs.requester_id = pci_requester_id(dev);
465 address_space_stl_le(&dev->bus_master_as, msg.address, msg.data,
466 attrs, NULL);
467 }
468
469 /*
470 * Register and track a PM capability. If wmask is also enabled for the power
471 * state field of the pmcsr register, guest writes may change the device PM
472 * state. BAR access is only enabled while the device is in the D0 state.
473 * Return the capability offset or negative error code.
474 */
475 int pci_pm_init(PCIDevice *d, uint8_t offset, Error **errp)
476 {
477 int cap = pci_add_capability(d, PCI_CAP_ID_PM, offset, PCI_PM_SIZEOF, errp);
478
479 if (cap < 0) {
480 return cap;
481 }
482
483 d->pm_cap = cap;
484 d->cap_present |= QEMU_PCI_CAP_PM;
485
486 return cap;
487 }
488
489 static uint8_t pci_pm_state(PCIDevice *d)
490 {
491 uint16_t pmcsr;
492
493 if (!(d->cap_present & QEMU_PCI_CAP_PM)) {
494 return 0;
495 }
496
497 pmcsr = pci_get_word(d->config + d->pm_cap + PCI_PM_CTRL);
498
499 return pmcsr & PCI_PM_CTRL_STATE_MASK;
500 }
501
502 /*
503 * Update the PM capability state based on the new value stored in config
504 * space respective to the old, pre-write state provided. If the new value
505 * is rejected (unsupported or invalid transition) restore the old value.
506 * Return the resulting PM state.
507 */
508 static uint8_t pci_pm_update(PCIDevice *d, uint32_t addr, int l, uint8_t old)
509 {
510 uint16_t pmc;
511 uint8_t new;
512
513 if (!(d->cap_present & QEMU_PCI_CAP_PM) ||
514 !range_covers_byte(addr, l, d->pm_cap + PCI_PM_CTRL)) {
515 return old;
516 }
517
518 new = pci_pm_state(d);
519 if (new == old) {
520 return old;
521 }
522
523 pmc = pci_get_word(d->config + d->pm_cap + PCI_PM_PMC);
524
525 /*
526 * Transitions to D1 & D2 are only allowed if supported. Devices may
527 * only transition to higher D-states or to D0.
528 */
529 if ((!(pmc & PCI_PM_CAP_D1) && new == 1) ||
530 (!(pmc & PCI_PM_CAP_D2) && new == 2) ||
531 (old && new && new < old)) {
532 pci_word_test_and_clear_mask(d->config + d->pm_cap + PCI_PM_CTRL,
533 PCI_PM_CTRL_STATE_MASK);
534 pci_word_test_and_set_mask(d->config + d->pm_cap + PCI_PM_CTRL,
535 old);
536 trace_pci_pm_bad_transition(d->name, pci_dev_bus_num(d),
537 PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
538 old, new);
539 return old;
540 }
541
542 trace_pci_pm_transition(d->name, pci_dev_bus_num(d), PCI_SLOT(d->devfn),
543 PCI_FUNC(d->devfn), old, new);
544 return new;
545 }
546
547 static void pci_reset_regions(PCIDevice *dev)
548 {
549 int r;
550 if (pci_is_vf(dev)) {
551 return;
552 }
553
554 for (r = 0; r < PCI_NUM_REGIONS; ++r) {
555 PCIIORegion *region = &dev->io_regions[r];
556 if (!region->size) {
557 continue;
558 }
559
560 if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
561 region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
562 pci_set_quad(dev->config + pci_bar(dev, r), region->type);
563 } else {
564 pci_set_long(dev->config + pci_bar(dev, r), region->type);
565 }
566 }
567 }
568
569 static void pci_do_device_reset(PCIDevice *dev)
570 {
571 if ((dev->cap_present & QEMU_PCI_SKIP_RESET_ON_CPR) && cpr_is_incoming()) {
572 return;
573 }
574
575 pci_device_deassert_intx(dev);
576 assert(dev->irq_state == 0);
577
578 /* Clear all writable bits */
579 pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
580 pci_get_word(dev->wmask + PCI_COMMAND) |
581 pci_get_word(dev->w1cmask + PCI_COMMAND));
582 pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
583 pci_get_word(dev->wmask + PCI_STATUS) |
584 pci_get_word(dev->w1cmask + PCI_STATUS));
585 /* Some devices make bits of PCI_INTERRUPT_LINE read only */
586 pci_byte_test_and_clear_mask(dev->config + PCI_INTERRUPT_LINE,
587 pci_get_word(dev->wmask + PCI_INTERRUPT_LINE) |
588 pci_get_word(dev->w1cmask + PCI_INTERRUPT_LINE));
589 dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
590 /* Default PM state is D0 */
591 if (dev->cap_present & QEMU_PCI_CAP_PM) {
592 pci_word_test_and_clear_mask(dev->config + dev->pm_cap + PCI_PM_CTRL,
593 PCI_PM_CTRL_STATE_MASK);
594 }
595 pci_reset_regions(dev);
596 pci_update_mappings(dev);
597
598 msi_reset(dev);
599 msix_reset(dev);
600 pcie_sriov_pf_reset(dev);
601 }
602
603 /*
604 * This function is called on #RST and FLR.
605 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
606 */
607 void pci_device_reset(PCIDevice *dev)
608 {
609 device_cold_reset(&dev->qdev);
610 pci_do_device_reset(dev);
611 }
612
613 /*
614 * Trigger pci bus reset under a given bus.
615 * Called via bus_cold_reset on RST# assert, after the devices
616 * have been reset device_cold_reset-ed already.
617 */
618 static void pcibus_reset_hold(Object *obj, ResetType type)
619 {
620 PCIBus *bus = PCI_BUS(obj);
621 int i;
622
623 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
624 if (bus->devices[i]) {
625 pci_do_device_reset(bus->devices[i]);
626 }
627 }
628
629 for (i = 0; i < bus->nirq; i++) {
630 assert(bus->irq_count[i] == 0);
631 }
632 }
633
634 static void pci_host_bus_register(DeviceState *host)
635 {
636 PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
637
638 QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
639 }
640
641 static void pci_host_bus_unregister(DeviceState *host)
642 {
643 PCIHostState *host_bridge = PCI_HOST_BRIDGE(host);
644
645 QLIST_REMOVE(host_bridge, next);
646 }
647
648 PCIBus *pci_device_root_bus(const PCIDevice *d)
649 {
650 PCIBus *bus = pci_get_bus(d);
651
652 while (!pci_bus_is_root(bus)) {
653 d = bus->parent_dev;
654 assert(d != NULL);
655
656 bus = pci_get_bus(d);
657 }
658
659 return bus;
660 }
661
662 const char *pci_root_bus_path(PCIDevice *dev)
663 {
664 PCIBus *rootbus = pci_device_root_bus(dev);
665 PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
666 PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
667
668 assert(host_bridge->bus == rootbus);
669
670 if (hc->root_bus_path) {
671 return (*hc->root_bus_path)(host_bridge, rootbus);
672 }
673
674 return rootbus->qbus.name;
675 }
676
677 bool pci_bus_bypass_iommu(PCIBus *bus)
678 {
679 PCIBus *rootbus = bus;
680 PCIHostState *host_bridge;
681
682 if (!pci_bus_is_root(bus)) {
683 rootbus = pci_device_root_bus(bus->parent_dev);
684 }
685
686 host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
687
688 assert(host_bridge->bus == rootbus);
689
690 return host_bridge->bypass_iommu;
691 }
692
693 static void pci_root_bus_internal_init(PCIBus *bus, DeviceState *parent,
694 MemoryRegion *mem, MemoryRegion *io,
695 uint8_t devfn_min)
696 {
697 assert(PCI_FUNC(devfn_min) == 0);
698 bus->devfn_min = devfn_min;
699 bus->slot_reserved_mask = 0x0;
700 bus->address_space_mem = mem;
701 bus->address_space_io = io;
702 bus->flags |= PCI_BUS_IS_ROOT;
703
704 /* host bridge */
705 QLIST_INIT(&bus->child);
706
707 pci_host_bus_register(parent);
708 }
709
710 static void pci_bus_uninit(PCIBus *bus)
711 {
712 pci_host_bus_unregister(BUS(bus)->parent);
713 }
714
715 bool pci_bus_is_express(const PCIBus *bus)
716 {
717 return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
718 }
719
720 void pci_root_bus_init(PCIBus *bus, size_t bus_size, DeviceState *parent,
721 const char *name,
722 MemoryRegion *mem, MemoryRegion *io,
723 uint8_t devfn_min, const char *typename)
724 {
725 qbus_init(bus, bus_size, typename, parent, name);
726 pci_root_bus_internal_init(bus, parent, mem, io, devfn_min);
727 }
728
729 PCIBus *pci_root_bus_new(DeviceState *parent, const char *name,
730 MemoryRegion *mem, MemoryRegion *io,
731 uint8_t devfn_min, const char *typename)
732 {
733 PCIBus *bus;
734
735 bus = PCI_BUS(qbus_new(typename, parent, name));
736 pci_root_bus_internal_init(bus, parent, mem, io, devfn_min);
737 return bus;
738 }
739
740 void pci_root_bus_cleanup(PCIBus *bus)
741 {
742 pci_bus_uninit(bus);
743 /* the caller of the unplug hotplug handler will delete this device */
744 qbus_unrealize(BUS(bus));
745 }
746
747 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq,
748 void *irq_opaque, int nirq)
749 {
750 bus->set_irq = set_irq;
751 bus->irq_opaque = irq_opaque;
752 bus->nirq = nirq;
753 g_free(bus->irq_count);
754 bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
755 }
756
757 void pci_bus_map_irqs(PCIBus *bus, pci_map_irq_fn map_irq)
758 {
759 bus->map_irq = map_irq;
760 }
761
762 void pci_bus_irqs_cleanup(PCIBus *bus)
763 {
764 bus->set_irq = NULL;
765 bus->map_irq = NULL;
766 bus->irq_opaque = NULL;
767 bus->nirq = 0;
768 g_free(bus->irq_count);
769 bus->irq_count = NULL;
770 }
771
772 PCIBus *pci_register_root_bus(DeviceState *parent, const char *name,
773 pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
774 void *irq_opaque,
775 MemoryRegion *mem, MemoryRegion *io,
776 uint8_t devfn_min, int nirq,
777 const char *typename)
778 {
779 PCIBus *bus;
780
781 bus = pci_root_bus_new(parent, name, mem, io, devfn_min, typename);
782 pci_bus_irqs(bus, set_irq, irq_opaque, nirq);
783 pci_bus_map_irqs(bus, map_irq);
784 return bus;
785 }
786
787 void pci_unregister_root_bus(PCIBus *bus)
788 {
789 pci_bus_irqs_cleanup(bus);
790 pci_root_bus_cleanup(bus);
791 }
792
793 int pci_bus_num(PCIBus *s)
794 {
795 return PCI_BUS_GET_CLASS(s)->bus_num(s);
796 }
797
798 /* Returns the min and max bus numbers of a PCI bus hierarchy */
799 void pci_bus_range(PCIBus *bus, int *min_bus, int *max_bus)
800 {
801 int i;
802 *min_bus = *max_bus = pci_bus_num(bus);
803
804 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
805 PCIDevice *dev = bus->devices[i];
806
807 if (dev && IS_PCI_BRIDGE(dev)) {
808 *min_bus = MIN(*min_bus, dev->config[PCI_SECONDARY_BUS]);
809 *max_bus = MAX(*max_bus, dev->config[PCI_SUBORDINATE_BUS]);
810 }
811 }
812 }
813
814 int pci_bus_numa_node(PCIBus *bus)
815 {
816 return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
817 }
818
819 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size,
820 const VMStateField *field)
821 {
822 PCIDevice *s = container_of(pv, PCIDevice, config);
823 uint8_t *config;
824 int i;
825
826 assert(size == pci_config_size(s));
827 config = g_malloc(size);
828
829 qemu_get_buffer(f, config, size);
830 for (i = 0; i < size; ++i) {
831 if ((config[i] ^ s->config[i]) &
832 s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
833 error_report("%s: Bad config data: i=0x%x read: %x device: %x "
834 "cmask: %x wmask: %x w1cmask:%x", __func__,
835 i, config[i], s->config[i],
836 s->cmask[i], s->wmask[i], s->w1cmask[i]);
837 g_free(config);
838 return -EINVAL;
839 }
840 }
841 memcpy(s->config, config, size);
842
843 pci_update_mappings(s);
844 if (IS_PCI_BRIDGE(s)) {
845 pci_bridge_update_mappings(PCI_BRIDGE(s));
846 }
847
848 pci_set_master(s, pci_get_word(s->config + PCI_COMMAND)
849 & PCI_COMMAND_MASTER);
850
851 g_free(config);
852 return 0;
853 }
854
855 /* just put buffer */
856 static int put_pci_config_device(QEMUFile *f, void *pv, size_t size,
857 const VMStateField *field, JSONWriter *vmdesc)
858 {
859 const uint8_t **v = pv;
860 assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
861 qemu_put_buffer(f, *v, size);
862
863 return 0;
864 }
865
866 static const VMStateInfo vmstate_info_pci_config = {
867 .name = "pci config",
868 .get = get_pci_config_device,
869 .put = put_pci_config_device,
870 };
871
872 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size,
873 const VMStateField *field)
874 {
875 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
876 uint32_t irq_state[PCI_NUM_PINS];
877 int i;
878 for (i = 0; i < PCI_NUM_PINS; ++i) {
879 irq_state[i] = qemu_get_be32(f);
880 if (irq_state[i] != 0x1 && irq_state[i] != 0) {
881 fprintf(stderr, "irq state %d: must be 0 or 1.\n",
882 irq_state[i]);
883 return -EINVAL;
884 }
885 }
886
887 for (i = 0; i < PCI_NUM_PINS; ++i) {
888 pci_set_irq_state(s, i, irq_state[i]);
889 }
890
891 return 0;
892 }
893
894 static int put_pci_irq_state(QEMUFile *f, void *pv, size_t size,
895 const VMStateField *field, JSONWriter *vmdesc)
896 {
897 int i;
898 PCIDevice *s = container_of(pv, PCIDevice, irq_state);
899
900 for (i = 0; i < PCI_NUM_PINS; ++i) {
901 qemu_put_be32(f, pci_irq_state(s, i));
902 }
903
904 return 0;
905 }
906
907 static const VMStateInfo vmstate_info_pci_irq_state = {
908 .name = "pci irq state",
909 .get = get_pci_irq_state,
910 .put = put_pci_irq_state,
911 };
912
913 static bool migrate_is_pcie(void *opaque, int version_id)
914 {
915 return pci_is_express((PCIDevice *)opaque);
916 }
917
918 static bool migrate_is_not_pcie(void *opaque, int version_id)
919 {
920 return !pci_is_express((PCIDevice *)opaque);
921 }
922
923 static int pci_post_load(void *opaque, int version_id)
924 {
925 pcie_sriov_pf_post_load(opaque);
926 return 0;
927 }
928
929 const VMStateDescription vmstate_pci_device = {
930 .name = "PCIDevice",
931 .version_id = 2,
932 .minimum_version_id = 1,
933 .post_load = pci_post_load,
934 .fields = (const VMStateField[]) {
935 VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
936 VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
937 migrate_is_not_pcie,
938 0, vmstate_info_pci_config,
939 PCI_CONFIG_SPACE_SIZE),
940 VMSTATE_BUFFER_UNSAFE_INFO_TEST(config, PCIDevice,
941 migrate_is_pcie,
942 0, vmstate_info_pci_config,
943 PCIE_CONFIG_SPACE_SIZE),
944 VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
945 vmstate_info_pci_irq_state,
946 PCI_NUM_PINS * sizeof(int32_t)),
947 VMSTATE_END_OF_LIST()
948 }
949 };
950
951
952 void pci_device_save(PCIDevice *s, QEMUFile *f)
953 {
954 Error *local_err = NULL;
955 int ret;
956
957 /* Clear interrupt status bit: it is implicit
958 * in irq_state which we are saving.
959 * This makes us compatible with old devices
960 * which never set or clear this bit. */
961 s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
962 ret = vmstate_save_state(f, &vmstate_pci_device, s, NULL, &local_err);
963 if (ret < 0) {
964 error_report_err(local_err);
965 }
966 /* Restore the interrupt status bit. */
967 pci_update_irq_status(s);
968 }
969
970 int pci_device_load(PCIDevice *s, QEMUFile *f)
971 {
972 Error *local_err = NULL;
973 int ret;
974
975 ret = vmstate_load_state(f, &vmstate_pci_device, s, s->version_id,
976 &local_err);
977 if (ret < 0) {
978 error_report_err(local_err);
979 }
980 /* Restore the interrupt status bit. */
981 pci_update_irq_status(s);
982 return ret;
983 }
984
985 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
986 {
987 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
988 pci_default_sub_vendor_id);
989 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
990 pci_default_sub_device_id);
991 }
992
993 /*
994 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
995 * [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
996 */
997 static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
998 unsigned int *slotp, unsigned int *funcp)
999 {
1000 const char *p;
1001 char *e;
1002 unsigned long val;
1003 unsigned long dom = 0, bus = 0;
1004 unsigned int slot = 0;
1005 unsigned int func = 0;
1006
1007 p = addr;
1008 val = strtoul(p, &e, 16);
1009 if (e == p)
1010 return -1;
1011 if (*e == ':') {
1012 bus = val;
1013 p = e + 1;
1014 val = strtoul(p, &e, 16);
1015 if (e == p)
1016 return -1;
1017 if (*e == ':') {
1018 dom = bus;
1019 bus = val;
1020 p = e + 1;
1021 val = strtoul(p, &e, 16);
1022 if (e == p)
1023 return -1;
1024 }
1025 }
1026
1027 slot = val;
1028
1029 if (funcp != NULL && *e != '\0') {
1030 if (*e != '.') {
1031 return -1;
1032 }
1033 p = e + 1;
1034 val = strtoul(p, &e, 16);
1035 if (e == p) {
1036 return -1;
1037 }
1038
1039 func = val;
1040 }
1041
1042 /* if funcp == NULL func is 0 */
1043 if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
1044 return -1;
1045
1046 if (*e)
1047 return -1;
1048
1049 *domp = dom;
1050 *busp = bus;
1051 *slotp = slot;
1052 if (funcp != NULL)
1053 *funcp = func;
1054 return 0;
1055 }
1056
1057 static void pci_init_cmask(PCIDevice *dev)
1058 {
1059 pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
1060 pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
1061 dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
1062 dev->cmask[PCI_REVISION_ID] = 0xff;
1063 dev->cmask[PCI_CLASS_PROG] = 0xff;
1064 pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
1065 dev->cmask[PCI_HEADER_TYPE] = 0xff;
1066 dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
1067 }
1068
1069 static void pci_init_wmask(PCIDevice *dev)
1070 {
1071 int config_size = pci_config_size(dev);
1072
1073 dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
1074 dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
1075 pci_set_word(dev->wmask + PCI_COMMAND,
1076 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
1077 PCI_COMMAND_INTX_DISABLE);
1078 pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
1079
1080 memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
1081 config_size - PCI_CONFIG_HEADER_SIZE);
1082 }
1083
1084 static void pci_init_w1cmask(PCIDevice *dev)
1085 {
1086 /*
1087 * Note: It's okay to set w1cmask even for readonly bits as
1088 * long as their value is hardwired to 0.
1089 */
1090 pci_set_word(dev->w1cmask + PCI_STATUS,
1091 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
1092 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
1093 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
1094 }
1095
1096 static void pci_init_mask_bridge(PCIDevice *d)
1097 {
1098 /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
1099 PCI_SEC_LATENCY_TIMER */
1100 memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
1101
1102 /* base and limit */
1103 d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
1104 d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
1105 pci_set_word(d->wmask + PCI_MEMORY_BASE,
1106 PCI_MEMORY_RANGE_MASK & 0xffff);
1107 pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
1108 PCI_MEMORY_RANGE_MASK & 0xffff);
1109 pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
1110 PCI_PREF_RANGE_MASK & 0xffff);
1111 pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
1112 PCI_PREF_RANGE_MASK & 0xffff);
1113
1114 /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
1115 memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
1116
1117 /* Supported memory and i/o types */
1118 d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
1119 d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
1120 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
1121 PCI_PREF_RANGE_TYPE_64);
1122 pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
1123 PCI_PREF_RANGE_TYPE_64);
1124
1125 /*
1126 * TODO: Bridges default to 10-bit VGA decoding but we currently only
1127 * implement 16-bit decoding (no alias support).
1128 */
1129 pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
1130 PCI_BRIDGE_CTL_PARITY |
1131 PCI_BRIDGE_CTL_SERR |
1132 PCI_BRIDGE_CTL_ISA |
1133 PCI_BRIDGE_CTL_VGA |
1134 PCI_BRIDGE_CTL_VGA_16BIT |
1135 PCI_BRIDGE_CTL_MASTER_ABORT |
1136 PCI_BRIDGE_CTL_BUS_RESET |
1137 PCI_BRIDGE_CTL_FAST_BACK |
1138 PCI_BRIDGE_CTL_DISCARD |
1139 PCI_BRIDGE_CTL_SEC_DISCARD |
1140 PCI_BRIDGE_CTL_DISCARD_SERR);
1141 /* Below does not do anything as we never set this bit, put here for
1142 * completeness. */
1143 pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
1144 PCI_BRIDGE_CTL_DISCARD_STATUS);
1145 d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
1146 d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
1147 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
1148 PCI_PREF_RANGE_TYPE_MASK);
1149 pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
1150 PCI_PREF_RANGE_TYPE_MASK);
1151 }
1152
1153 static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
1154 {
1155 uint8_t slot = PCI_SLOT(dev->devfn);
1156 uint8_t func;
1157
1158 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
1159 dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
1160 }
1161
1162 /* SR/IOV is not handled here. */
1163 if (pci_is_vf(dev)) {
1164 return;
1165 }
1166
1167 /*
1168 * multifunction bit is interpreted in two ways as follows.
1169 * - all functions must set the bit to 1.
1170 * Example: Intel X53
1171 * - function 0 must set the bit, but the rest function (> 0)
1172 * is allowed to leave the bit to 0.
1173 * Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
1174 *
1175 * So OS (at least Linux) checks the bit of only function 0,
1176 * and doesn't see the bit of function > 0.
1177 *
1178 * The below check allows both interpretation.
1179 */
1180 if (PCI_FUNC(dev->devfn)) {
1181 PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
1182 if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
1183 /* function 0 should set multifunction bit */
1184 error_setg(errp, "PCI: single function device can't be populated "
1185 "in function %x.%x", slot, PCI_FUNC(dev->devfn));
1186 return;
1187 }
1188 return;
1189 }
1190
1191 if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
1192 return;
1193 }
1194 /* function 0 indicates single function, so function > 0 must be NULL */
1195 for (func = 1; func < PCI_FUNC_MAX; ++func) {
1196 PCIDevice *device = bus->devices[PCI_DEVFN(slot, func)];
1197 if (device && !pci_is_vf(device)) {
1198 error_setg(errp, "PCI: %x.0 indicates single function, "
1199 "but %x.%x is already populated.",
1200 slot, slot, func);
1201 return;
1202 }
1203 }
1204 }
1205
1206 static void pci_config_alloc(PCIDevice *pci_dev)
1207 {
1208 int config_size = pci_config_size(pci_dev);
1209
1210 pci_dev->config = g_malloc0(config_size);
1211 pci_dev->cmask = g_malloc0(config_size);
1212 pci_dev->wmask = g_malloc0(config_size);
1213 pci_dev->w1cmask = g_malloc0(config_size);
1214 pci_dev->used = g_malloc0(config_size);
1215 }
1216
1217 static void pci_config_free(PCIDevice *pci_dev)
1218 {
1219 g_free(pci_dev->config);
1220 g_free(pci_dev->cmask);
1221 g_free(pci_dev->wmask);
1222 g_free(pci_dev->w1cmask);
1223 g_free(pci_dev->used);
1224 }
1225
1226 static void do_pci_unregister_device(PCIDevice *pci_dev)
1227 {
1228 pci_get_bus(pci_dev)->devices[pci_dev->devfn] = NULL;
1229 pci_config_free(pci_dev);
1230
1231 if (xen_mode == XEN_EMULATE) {
1232 xen_evtchn_remove_pci_device(pci_dev);
1233 }
1234 if (memory_region_is_mapped(&pci_dev->bus_master_enable_region)) {
1235 memory_region_del_subregion(&pci_dev->bus_master_container_region,
1236 &pci_dev->bus_master_enable_region);
1237 }
1238 address_space_destroy(&pci_dev->bus_master_as);
1239 }
1240
1241 /* Extract PCIReqIDCache into BDF format */
1242 static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)
1243 {
1244 uint8_t bus_n;
1245 uint16_t result;
1246
1247 switch (cache->type) {
1248 case PCI_REQ_ID_BDF:
1249 result = pci_get_bdf(cache->dev);
1250 break;
1251 case PCI_REQ_ID_SECONDARY_BUS:
1252 bus_n = pci_dev_bus_num(cache->dev);
1253 result = PCI_BUILD_BDF(bus_n, 0);
1254 break;
1255 default:
1256 error_report("Invalid PCI requester ID cache type: %d",
1257 cache->type);
1258 exit(1);
1259 break;
1260 }
1261
1262 return result;
1263 }
1264
1265 /* Parse bridges up to the root complex and return requester ID
1266 * cache for specific device. For full PCIe topology, the cache
1267 * result would be exactly the same as getting BDF of the device.
1268 * However, several tricks are required when system mixed up with
1269 * legacy PCI devices and PCIe-to-PCI bridges.
1270 *
1271 * Here we cache the proxy device (and type) not requester ID since
1272 * bus number might change from time to time.
1273 */
1274 static PCIReqIDCache pci_req_id_cache_get(PCIDevice *dev)
1275 {
1276 PCIDevice *parent;
1277 PCIReqIDCache cache = {
1278 .dev = dev,
1279 .type = PCI_REQ_ID_BDF,
1280 };
1281
1282 while (!pci_bus_is_root(pci_get_bus(dev))) {
1283 /* We are under PCI/PCIe bridges */
1284 parent = pci_get_bus(dev)->parent_dev;
1285 if (pci_is_express(parent)) {
1286 if (pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
1287 /* When we pass through PCIe-to-PCI/PCIX bridges, we
1288 * override the requester ID using secondary bus
1289 * number of parent bridge with zeroed devfn
1290 * (pcie-to-pci bridge spec chap 2.3). */
1291 cache.type = PCI_REQ_ID_SECONDARY_BUS;
1292 cache.dev = dev;
1293 }
1294 } else {
1295 /* Legacy PCI, override requester ID with the bridge's
1296 * BDF upstream. When the root complex connects to
1297 * legacy PCI devices (including buses), it can only
1298 * obtain requester ID info from directly attached
1299 * devices. If devices are attached under bridges, only
1300 * the requester ID of the bridge that is directly
1301 * attached to the root complex can be recognized. */
1302 cache.type = PCI_REQ_ID_BDF;
1303 cache.dev = parent;
1304 }
1305 dev = parent;
1306 }
1307
1308 return cache;
1309 }
1310
1311 uint16_t pci_requester_id(PCIDevice *dev)
1312 {
1313 return pci_req_id_cache_extract(&dev->requester_id_cache);
1314 }
1315
1316 static bool pci_bus_devfn_available(PCIBus *bus, int devfn)
1317 {
1318 return !(bus->devices[devfn]);
1319 }
1320
1321 static bool pci_bus_devfn_reserved(PCIBus *bus, int devfn)
1322 {
1323 return bus->slot_reserved_mask & (1UL << PCI_SLOT(devfn));
1324 }
1325
1326 uint32_t pci_bus_get_slot_reserved_mask(PCIBus *bus)
1327 {
1328 return bus->slot_reserved_mask;
1329 }
1330
1331 void pci_bus_set_slot_reserved_mask(PCIBus *bus, uint32_t mask)
1332 {
1333 bus->slot_reserved_mask |= mask;
1334 }
1335
1336 void pci_bus_clear_slot_reserved_mask(PCIBus *bus, uint32_t mask)
1337 {
1338 bus->slot_reserved_mask &= ~mask;
1339 }
1340
1341 /* -1 for devfn means auto assign */
1342 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev,
1343 const char *name, int devfn,
1344 Error **errp)
1345 {
1346 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1347 PCIConfigReadFunc *config_read = pc->config_read;
1348 PCIConfigWriteFunc *config_write = pc->config_write;
1349 Error *local_err = NULL;
1350 DeviceState *dev = DEVICE(pci_dev);
1351 PCIBus *bus = pci_get_bus(pci_dev);
1352 bool is_bridge = IS_PCI_BRIDGE(pci_dev);
1353
1354 /* Only pci bridges can be attached to extra PCI root buses */
1355 if (pci_bus_is_root(bus) && bus->parent_dev && !is_bridge) {
1356 error_setg(errp,
1357 "PCI: Only PCI/PCIe bridges can be plugged into %s",
1358 bus->parent_dev->name);
1359 return NULL;
1360 }
1361
1362 if (devfn < 0) {
1363 for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
1364 devfn += PCI_FUNC_MAX) {
1365 if (pci_bus_devfn_available(bus, devfn) &&
1366 !pci_bus_devfn_reserved(bus, devfn)) {
1367 goto found;
1368 }
1369 }
1370 error_setg(errp, "PCI: no slot/function available for %s, all in use "
1371 "or reserved", name);
1372 return NULL;
1373 found: ;
1374 } else if (pci_bus_devfn_reserved(bus, devfn)) {
1375 error_setg(errp, "PCI: slot %d function %d not available for %s,"
1376 " reserved",
1377 PCI_SLOT(devfn), PCI_FUNC(devfn), name);
1378 return NULL;
1379 } else if (!pci_bus_devfn_available(bus, devfn)) {
1380 error_setg(errp, "PCI: slot %d function %d not available for %s,"
1381 " in use by %s,id=%s",
1382 PCI_SLOT(devfn), PCI_FUNC(devfn), name,
1383 bus->devices[devfn]->name, bus->devices[devfn]->qdev.id);
1384 return NULL;
1385 }
1386
1387 /*
1388 * Populating function 0 triggers a scan from the guest that
1389 * exposes other non-zero functions. Hence we need to ensure that
1390 * function 0 wasn't added yet.
1391 */
1392 if (dev->hotplugged && !pci_is_vf(pci_dev) &&
1393 pci_get_function_0(pci_dev)) {
1394 error_setg(errp, "PCI: slot %d function 0 already occupied by %s,"
1395 " new func %s cannot be exposed to guest.",
1396 PCI_SLOT(pci_get_function_0(pci_dev)->devfn),
1397 pci_get_function_0(pci_dev)->name,
1398 name);
1399
1400 return NULL;
1401 }
1402
1403 pci_dev->devfn = devfn;
1404 pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);
1405 pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
1406
1407 memory_region_init(&pci_dev->bus_master_container_region, OBJECT(pci_dev),
1408 "bus master container", UINT64_MAX);
1409 address_space_init(&pci_dev->bus_master_as,
1410 &pci_dev->bus_master_container_region, pci_dev->name);
1411 pci_dev->bus_master_as.max_bounce_buffer_size =
1412 pci_dev->max_bounce_buffer_size;
1413
1414 pci_dev->irq_state = 0;
1415 pci_config_alloc(pci_dev);
1416
1417 pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
1418 pci_config_set_device_id(pci_dev->config, pc->device_id);
1419 pci_config_set_revision(pci_dev->config, pc->revision);
1420 pci_config_set_class(pci_dev->config, pc->class_id);
1421
1422 if (!is_bridge) {
1423 if (pc->subsystem_vendor_id || pc->subsystem_id) {
1424 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
1425 pc->subsystem_vendor_id);
1426 pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
1427 pc->subsystem_id);
1428 } else {
1429 pci_set_default_subsystem_id(pci_dev);
1430 }
1431 } else {
1432 /* subsystem_vendor_id/subsystem_id are only for header type 0 */
1433 assert(!pc->subsystem_vendor_id);
1434 assert(!pc->subsystem_id);
1435 }
1436 pci_init_cmask(pci_dev);
1437 pci_init_wmask(pci_dev);
1438 pci_init_w1cmask(pci_dev);
1439 if (is_bridge) {
1440 pci_init_mask_bridge(pci_dev);
1441 }
1442 pci_init_multifunction(bus, pci_dev, &local_err);
1443 if (local_err) {
1444 error_propagate(errp, local_err);
1445 do_pci_unregister_device(pci_dev);
1446 return NULL;
1447 }
1448
1449 if (!config_read)
1450 config_read = pci_default_read_config;
1451 if (!config_write)
1452 config_write = pci_default_write_config;
1453 pci_dev->config_read = config_read;
1454 pci_dev->config_write = config_write;
1455 bus->devices[devfn] = pci_dev;
1456 pci_dev->version_id = 2; /* Current pci device vmstate version */
1457 if (!pci_device_supports_iommu_address_space(pci_dev, errp)) {
1458 do_pci_unregister_device(pci_dev);
1459 bus->devices[devfn] = NULL;
1460 return NULL;
1461 }
1462 if (phase_check(PHASE_MACHINE_READY)) {
1463 pci_init_bus_master(pci_dev);
1464 }
1465 return pci_dev;
1466 }
1467
1468 static void pci_unregister_io_regions(PCIDevice *pci_dev)
1469 {
1470 PCIIORegion *r;
1471 int i;
1472
1473 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1474 r = &pci_dev->io_regions[i];
1475 if (!r->size || r->addr == PCI_BAR_UNMAPPED)
1476 continue;
1477 memory_region_del_subregion(r->address_space, r->memory);
1478 }
1479
1480 pci_unregister_vga(pci_dev);
1481 }
1482
1483 static void pci_qdev_unrealize(DeviceState *dev)
1484 {
1485 PCIDevice *pci_dev = PCI_DEVICE(dev);
1486 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1487
1488 pci_unregister_io_regions(pci_dev);
1489 pci_del_option_rom(pci_dev);
1490 pcie_sriov_unregister_device(pci_dev);
1491
1492 if (pc->exit) {
1493 pc->exit(pci_dev);
1494 }
1495
1496 pci_device_deassert_intx(pci_dev);
1497 do_pci_unregister_device(pci_dev);
1498
1499 pci_dev->msi_trigger = NULL;
1500
1501 /*
1502 * clean up acpi-index so it could reused by another device
1503 */
1504 if (pci_dev->acpi_index) {
1505 GSequence *used_indexes = pci_acpi_index_list();
1506
1507 g_sequence_remove(g_sequence_lookup(used_indexes,
1508 GINT_TO_POINTER(pci_dev->acpi_index),
1509 g_cmp_uint32, NULL));
1510 }
1511 }
1512
1513 void pci_register_bar(PCIDevice *pci_dev, int region_num,
1514 uint8_t type, MemoryRegion *memory)
1515 {
1516 PCIIORegion *r;
1517 uint32_t addr; /* offset in pci config space */
1518 uint64_t wmask;
1519 pcibus_t size = memory_region_size(memory);
1520 uint8_t hdr_type;
1521
1522 assert(region_num >= 0);
1523 assert(region_num < PCI_NUM_REGIONS);
1524 assert(is_power_of_2(size));
1525
1526 /* A PCI bridge device (with Type 1 header) may only have at most 2 BARs */
1527 hdr_type =
1528 pci_dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1529 assert(hdr_type != PCI_HEADER_TYPE_BRIDGE || region_num < 2);
1530
1531 r = &pci_dev->io_regions[region_num];
1532 assert(!r->size);
1533 r->size = size;
1534 r->type = type;
1535 r->memory = memory;
1536 r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO
1537 ? pci_get_bus(pci_dev)->address_space_io
1538 : pci_get_bus(pci_dev)->address_space_mem;
1539
1540 if (pci_is_vf(pci_dev)) {
1541 r->addr = pci_bar_address(pci_dev, region_num, r->type, r->size);
1542 if (r->addr != PCI_BAR_UNMAPPED) {
1543 memory_region_add_subregion_overlap(r->address_space,
1544 r->addr, r->memory, 1);
1545 }
1546 } else {
1547 r->addr = PCI_BAR_UNMAPPED;
1548
1549 wmask = ~(size - 1);
1550 if (region_num == PCI_ROM_SLOT) {
1551 /* ROM enable bit is writable */
1552 wmask |= PCI_ROM_ADDRESS_ENABLE;
1553 }
1554
1555 addr = pci_bar(pci_dev, region_num);
1556 pci_set_long(pci_dev->config + addr, type);
1557
1558 if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
1559 r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1560 pci_set_quad(pci_dev->wmask + addr, wmask);
1561 pci_set_quad(pci_dev->cmask + addr, ~0ULL);
1562 } else {
1563 pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
1564 pci_set_long(pci_dev->cmask + addr, 0xffffffff);
1565 }
1566 }
1567 }
1568
1569 static void pci_update_vga(PCIDevice *pci_dev)
1570 {
1571 uint16_t cmd;
1572
1573 if (!pci_dev->has_vga) {
1574 return;
1575 }
1576
1577 cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1578
1579 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1580 cmd & PCI_COMMAND_MEMORY);
1581 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1582 cmd & PCI_COMMAND_IO);
1583 memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1584 cmd & PCI_COMMAND_IO);
1585 }
1586
1587 void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1588 MemoryRegion *io_lo, MemoryRegion *io_hi)
1589 {
1590 PCIBus *bus = pci_get_bus(pci_dev);
1591
1592 assert(!pci_dev->has_vga);
1593
1594 assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1595 pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1596 memory_region_add_subregion_overlap(bus->address_space_mem,
1597 QEMU_PCI_VGA_MEM_BASE, mem, 1);
1598
1599 assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1600 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1601 memory_region_add_subregion_overlap(bus->address_space_io,
1602 QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1603
1604 assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1605 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1606 memory_region_add_subregion_overlap(bus->address_space_io,
1607 QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1608 pci_dev->has_vga = true;
1609
1610 pci_update_vga(pci_dev);
1611 }
1612
1613 void pci_unregister_vga(PCIDevice *pci_dev)
1614 {
1615 PCIBus *bus = pci_get_bus(pci_dev);
1616
1617 if (!pci_dev->has_vga) {
1618 return;
1619 }
1620
1621 memory_region_del_subregion(bus->address_space_mem,
1622 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1623 memory_region_del_subregion(bus->address_space_io,
1624 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1625 memory_region_del_subregion(bus->address_space_io,
1626 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1627 pci_dev->has_vga = false;
1628 }
1629
1630 pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1631 {
1632 return pci_dev->io_regions[region_num].addr;
1633 }
1634
1635 static pcibus_t pci_config_get_bar_addr(PCIDevice *d, int reg,
1636 uint8_t type, pcibus_t size)
1637 {
1638 pcibus_t new_addr;
1639 if (!pci_is_vf(d)) {
1640 int bar = pci_bar(d, reg);
1641 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1642 new_addr = pci_get_quad(d->config + bar);
1643 } else {
1644 new_addr = pci_get_long(d->config + bar);
1645 }
1646 } else {
1647 PCIDevice *pf = d->exp.sriov_vf.pf;
1648 uint16_t sriov_cap = pf->exp.sriov_cap;
1649 int bar = sriov_cap + PCI_SRIOV_BAR + reg * 4;
1650 uint16_t vf_offset =
1651 pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_OFFSET);
1652 uint16_t vf_stride =
1653 pci_get_word(pf->config + sriov_cap + PCI_SRIOV_VF_STRIDE);
1654 uint32_t vf_num = d->devfn - (pf->devfn + vf_offset);
1655
1656 if (vf_num) {
1657 vf_num /= vf_stride;
1658 }
1659
1660 if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1661 new_addr = pci_get_quad(pf->config + bar);
1662 } else {
1663 new_addr = pci_get_long(pf->config + bar);
1664 }
1665 new_addr += vf_num * size;
1666 }
1667 /* The ROM slot has a specific enable bit, keep it intact */
1668 if (reg != PCI_ROM_SLOT) {
1669 new_addr &= ~(size - 1);
1670 }
1671 return new_addr;
1672 }
1673
1674 pcibus_t pci_bar_address(PCIDevice *d,
1675 int reg, uint8_t type, pcibus_t size)
1676 {
1677 pcibus_t new_addr, last_addr;
1678 uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1679 MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
1680 bool allow_0_address = mc->pci_allow_0_address;
1681
1682 if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1683 if (!(cmd & PCI_COMMAND_IO)) {
1684 return PCI_BAR_UNMAPPED;
1685 }
1686 new_addr = pci_config_get_bar_addr(d, reg, type, size);
1687 last_addr = new_addr + size - 1;
1688 /* Check if 32 bit BAR wraps around explicitly.
1689 * TODO: make priorities correct and remove this work around.
1690 */
1691 if (last_addr <= new_addr || last_addr >= UINT32_MAX ||
1692 (!allow_0_address && new_addr == 0)) {
1693 return PCI_BAR_UNMAPPED;
1694 }
1695 return new_addr;
1696 }
1697
1698 if (!(cmd & PCI_COMMAND_MEMORY)) {
1699 return PCI_BAR_UNMAPPED;
1700 }
1701 new_addr = pci_config_get_bar_addr(d, reg, type, size);
1702 /* the ROM slot has a specific enable bit */
1703 if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1704 return PCI_BAR_UNMAPPED;
1705 }
1706 new_addr &= ~(size - 1);
1707 last_addr = new_addr + size - 1;
1708 /* NOTE: we do not support wrapping */
1709 /* XXX: as we cannot support really dynamic
1710 mappings, we handle specific values as invalid
1711 mappings. */
1712 if (last_addr <= new_addr || last_addr == PCI_BAR_UNMAPPED ||
1713 (!allow_0_address && new_addr == 0)) {
1714 return PCI_BAR_UNMAPPED;
1715 }
1716
1717 /* Now pcibus_t is 64bit.
1718 * Check if 32 bit BAR wraps around explicitly.
1719 * Without this, PC ide doesn't work well.
1720 * TODO: remove this work around.
1721 */
1722 if (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1723 return PCI_BAR_UNMAPPED;
1724 }
1725
1726 /*
1727 * OS is allowed to set BAR beyond its addressable
1728 * bits. For example, 32 bit OS can set 64bit bar
1729 * to >4G. Check it. TODO: we might need to support
1730 * it in the future for e.g. PAE.
1731 */
1732 if (last_addr >= HWADDR_MAX) {
1733 return PCI_BAR_UNMAPPED;
1734 }
1735
1736 return new_addr;
1737 }
1738
1739 static void pci_update_mappings(PCIDevice *d)
1740 {
1741 PCIIORegion *r;
1742 int i;
1743 pcibus_t new_addr;
1744
1745 for(i = 0; i < PCI_NUM_REGIONS; i++) {
1746 r = &d->io_regions[i];
1747
1748 /* this region isn't registered */
1749 if (!r->size)
1750 continue;
1751
1752 new_addr = pci_bar_address(d, i, r->type, r->size);
1753 if (!d->enabled || pci_pm_state(d)) {
1754 new_addr = PCI_BAR_UNMAPPED;
1755 }
1756
1757 /* This bar isn't changed */
1758 if (new_addr == r->addr)
1759 continue;
1760
1761 /* now do the real mapping */
1762 if (r->addr != PCI_BAR_UNMAPPED) {
1763 trace_pci_update_mappings_del(d->name, pci_dev_bus_num(d),
1764 PCI_SLOT(d->devfn),
1765 PCI_FUNC(d->devfn),
1766 i, r->addr, r->size);
1767 memory_region_del_subregion(r->address_space, r->memory);
1768 }
1769 r->addr = new_addr;
1770 if (r->addr != PCI_BAR_UNMAPPED) {
1771 trace_pci_update_mappings_add(d->name, pci_dev_bus_num(d),
1772 PCI_SLOT(d->devfn),
1773 PCI_FUNC(d->devfn),
1774 i, r->addr, r->size);
1775 memory_region_add_subregion_overlap(r->address_space,
1776 r->addr, r->memory, 1);
1777 }
1778 }
1779
1780 pci_update_vga(d);
1781 }
1782
1783 int pci_irq_disabled(PCIDevice *d)
1784 {
1785 return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1786 }
1787
1788 /* Called after interrupt disabled field update in config space,
1789 * assert/deassert interrupts if necessary.
1790 * Gets original interrupt disable bit value (before update). */
1791 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1792 {
1793 int i, disabled = pci_irq_disabled(d);
1794 if (disabled == was_irq_disabled)
1795 return;
1796 for (i = 0; i < PCI_NUM_PINS; ++i) {
1797 int state = pci_irq_state(d, i);
1798 pci_change_irq_level(d, i, disabled ? -state : state);
1799 }
1800 }
1801
1802 uint32_t pci_default_read_config(PCIDevice *d,
1803 uint32_t address, int len)
1804 {
1805 uint32_t val = 0;
1806
1807 assert(address + len <= pci_config_size(d));
1808
1809 if (pci_is_express_downstream_port(d) &&
1810 ranges_overlap(address, len, d->exp.exp_cap + PCI_EXP_LNKSTA, 2)) {
1811 pcie_sync_bridge_lnk(d);
1812 }
1813 memcpy(&val, d->config + address, len);
1814 return le32_to_cpu(val);
1815 }
1816
1817 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1818 {
1819 uint8_t new_pm_state, old_pm_state = pci_pm_state(d);
1820 int i, was_irq_disabled = pci_irq_disabled(d);
1821 uint32_t val = val_in;
1822
1823 assert(addr + l <= pci_config_size(d));
1824
1825 for (i = 0; i < l; val >>= 8, ++i) {
1826 uint8_t wmask = d->wmask[addr + i];
1827 uint8_t w1cmask = d->w1cmask[addr + i];
1828 assert(!(wmask & w1cmask));
1829 d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1830 d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1831 }
1832
1833 new_pm_state = pci_pm_update(d, addr, l, old_pm_state);
1834
1835 if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1836 ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1837 ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1838 range_covers_byte(addr, l, PCI_COMMAND) ||
1839 !!new_pm_state != !!old_pm_state) {
1840 pci_update_mappings(d);
1841 }
1842
1843 if (ranges_overlap(addr, l, PCI_COMMAND, 2)) {
1844 pci_update_irq_disabled(d, was_irq_disabled);
1845 pci_set_master(d, (pci_get_word(d->config + PCI_COMMAND) &
1846 PCI_COMMAND_MASTER) && d->enabled);
1847 }
1848
1849 msi_write_config(d, addr, val_in, l);
1850 msix_write_config(d, addr, val_in, l);
1851 pcie_sriov_config_write(d, addr, val_in, l);
1852 }
1853
1854 /***********************************************************/
1855 /* generic PCI irq support */
1856
1857 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1858 static void pci_irq_handler(void *opaque, int irq_num, int level)
1859 {
1860 PCIDevice *pci_dev = opaque;
1861 int change;
1862
1863 assert(0 <= irq_num && irq_num < PCI_NUM_PINS);
1864 assert(level == 0 || level == 1);
1865 change = level - pci_irq_state(pci_dev, irq_num);
1866 if (!change)
1867 return;
1868
1869 pci_set_irq_state(pci_dev, irq_num, level);
1870 pci_update_irq_status(pci_dev);
1871 if (pci_irq_disabled(pci_dev))
1872 return;
1873 pci_change_irq_level(pci_dev, irq_num, change);
1874 }
1875
1876 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1877 {
1878 int intx = pci_intx(pci_dev);
1879 assert(0 <= intx && intx < PCI_NUM_PINS);
1880
1881 return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1882 }
1883
1884 void pci_set_irq(PCIDevice *pci_dev, int level)
1885 {
1886 int intx = pci_intx(pci_dev);
1887 pci_irq_handler(pci_dev, intx, level);
1888 }
1889
1890 /* Special hooks used by device assignment */
1891 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1892 {
1893 assert(pci_bus_is_root(bus));
1894 bus->route_intx_to_irq = route_intx_to_irq;
1895 }
1896
1897 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1898 {
1899 PCIBus *bus;
1900
1901 do {
1902 int dev_irq = pin;
1903 bus = pci_get_bus(dev);
1904 pin = bus->map_irq(dev, pin);
1905 trace_pci_route_irq(dev_irq, DEVICE(dev)->canonical_path, pin,
1906 pci_bus_is_root(bus) ? "root-complex"
1907 : DEVICE(bus->parent_dev)->canonical_path);
1908 dev = bus->parent_dev;
1909 } while (dev);
1910
1911 if (!bus->route_intx_to_irq) {
1912 error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1913 object_get_typename(OBJECT(bus->qbus.parent)));
1914 return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1915 }
1916
1917 return bus->route_intx_to_irq(bus->irq_opaque, pin);
1918 }
1919
1920 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1921 {
1922 return old->mode != new->mode || old->irq != new->irq;
1923 }
1924
1925 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1926 {
1927 PCIDevice *dev;
1928 PCIBus *sec;
1929 int i;
1930
1931 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1932 dev = bus->devices[i];
1933 if (dev && dev->intx_routing_notifier) {
1934 dev->intx_routing_notifier(dev);
1935 }
1936 }
1937
1938 QLIST_FOREACH(sec, &bus->child, sibling) {
1939 pci_bus_fire_intx_routing_notifier(sec);
1940 }
1941 }
1942
1943 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1944 PCIINTxRoutingNotifier notifier)
1945 {
1946 dev->intx_routing_notifier = notifier;
1947 }
1948
1949 /*
1950 * PCI-to-PCI bridge specification
1951 * 9.1: Interrupt routing. Table 9-1
1952 *
1953 * the PCI Express Base Specification, Revision 2.1
1954 * 2.2.8.1: INTx interrupt signaling - Rules
1955 * the Implementation Note
1956 * Table 2-20
1957 */
1958 /*
1959 * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1960 * 0-origin unlike PCI interrupt pin register.
1961 */
1962 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1963 {
1964 return pci_swizzle(PCI_SLOT(pci_dev->devfn), pin);
1965 }
1966
1967 /***********************************************************/
1968 /* monitor info on PCI */
1969
1970 static const pci_class_desc pci_class_descriptions[] =
1971 {
1972 { 0x0001, "VGA controller", "display"},
1973 { 0x0100, "SCSI controller", "scsi"},
1974 { 0x0101, "IDE controller", "ide"},
1975 { 0x0102, "Floppy controller", "fdc"},
1976 { 0x0103, "IPI controller", "ipi"},
1977 { 0x0104, "RAID controller", "raid"},
1978 { 0x0106, "SATA controller"},
1979 { 0x0107, "SAS controller"},
1980 { 0x0180, "Storage controller"},
1981 { 0x0200, "Ethernet controller", "ethernet"},
1982 { 0x0201, "Token Ring controller", "token-ring"},
1983 { 0x0202, "FDDI controller", "fddi"},
1984 { 0x0203, "ATM controller", "atm"},
1985 { 0x0280, "Network controller"},
1986 { 0x0300, "VGA controller", "display", 0x00ff},
1987 { 0x0301, "XGA controller"},
1988 { 0x0302, "3D controller"},
1989 { 0x0380, "Display controller"},
1990 { 0x0400, "Video controller", "video"},
1991 { 0x0401, "Audio controller", "sound"},
1992 { 0x0402, "Phone"},
1993 { 0x0403, "Audio controller", "sound"},
1994 { 0x0480, "Multimedia controller"},
1995 { 0x0500, "RAM controller", "memory"},
1996 { 0x0501, "Flash controller", "flash"},
1997 { 0x0580, "Memory controller"},
1998 { 0x0600, "Host bridge", "host"},
1999 { 0x0601, "ISA bridge", "isa"},
2000 { 0x0602, "EISA bridge", "eisa"},
2001 { 0x0603, "MC bridge", "mca"},
2002 { 0x0604, "PCI bridge", "pci-bridge"},
2003 { 0x0605, "PCMCIA bridge", "pcmcia"},
2004 { 0x0606, "NUBUS bridge", "nubus"},
2005 { 0x0607, "CARDBUS bridge", "cardbus"},
2006 { 0x0608, "RACEWAY bridge"},
2007 { 0x0680, "Bridge"},
2008 { 0x0700, "Serial port", "serial"},
2009 { 0x0701, "Parallel port", "parallel"},
2010 { 0x0800, "Interrupt controller", "interrupt-controller"},
2011 { 0x0801, "DMA controller", "dma-controller"},
2012 { 0x0802, "Timer", "timer"},
2013 { 0x0803, "RTC", "rtc"},
2014 { 0x0900, "Keyboard", "keyboard"},
2015 { 0x0901, "Pen", "pen"},
2016 { 0x0902, "Mouse", "mouse"},
2017 { 0x0A00, "Dock station", "dock", 0x00ff},
2018 { 0x0B00, "i386 cpu", "cpu", 0x00ff},
2019 { 0x0c00, "Firewire controller", "firewire"},
2020 { 0x0c01, "Access bus controller", "access-bus"},
2021 { 0x0c02, "SSA controller", "ssa"},
2022 { 0x0c03, "USB controller", "usb"},
2023 { 0x0c04, "Fibre channel controller", "fibre-channel"},
2024 { 0x0c05, "SMBus"},
2025 { 0, NULL}
2026 };
2027
2028 void pci_for_each_device_under_bus_reverse(PCIBus *bus,
2029 pci_bus_dev_fn fn,
2030 void *opaque)
2031 {
2032 PCIDevice *d;
2033 int devfn;
2034
2035 for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
2036 d = bus->devices[ARRAY_SIZE(bus->devices) - 1 - devfn];
2037 if (d) {
2038 fn(bus, d, opaque);
2039 }
2040 }
2041 }
2042
2043 void pci_for_each_device_reverse(PCIBus *bus, int bus_num,
2044 pci_bus_dev_fn fn, void *opaque)
2045 {
2046 bus = pci_find_bus_nr(bus, bus_num);
2047
2048 if (bus) {
2049 pci_for_each_device_under_bus_reverse(bus, fn, opaque);
2050 }
2051 }
2052
2053 void pci_for_each_device_under_bus(PCIBus *bus,
2054 pci_bus_dev_fn fn, void *opaque)
2055 {
2056 PCIDevice *d;
2057 int devfn;
2058
2059 for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
2060 d = bus->devices[devfn];
2061 if (d) {
2062 fn(bus, d, opaque);
2063 }
2064 }
2065 }
2066
2067 void pci_for_each_device(PCIBus *bus, int bus_num,
2068 pci_bus_dev_fn fn, void *opaque)
2069 {
2070 bus = pci_find_bus_nr(bus, bus_num);
2071
2072 if (bus) {
2073 pci_for_each_device_under_bus(bus, fn, opaque);
2074 }
2075 }
2076
2077 const pci_class_desc *get_class_desc(int class)
2078 {
2079 const pci_class_desc *desc;
2080
2081 desc = pci_class_descriptions;
2082 while (desc->desc && class != desc->class) {
2083 desc++;
2084 }
2085
2086 return desc;
2087 }
2088
2089 void pci_init_nic_devices(PCIBus *bus, const char *default_model)
2090 {
2091 qemu_create_nic_bus_devices(&bus->qbus, TYPE_PCI_DEVICE, default_model,
2092 "virtio", "virtio-net-pci");
2093 }
2094
2095 bool pci_init_nic_in_slot(PCIBus *rootbus, const char *model,
2096 const char *alias, const char *devaddr)
2097 {
2098 NICInfo *nd = qemu_find_nic_info(model, true, alias);
2099 int dom, busnr, devfn;
2100 PCIDevice *pci_dev;
2101 unsigned slot;
2102 unsigned func;
2103
2104 PCIBus *bus;
2105
2106 if (!nd) {
2107 return false;
2108 }
2109
2110 if (!devaddr || pci_parse_devaddr(devaddr, &dom, &busnr, &slot, &func) < 0) {
2111 error_report("Invalid PCI device address %s for device %s",
2112 devaddr, model);
2113 exit(1);
2114 }
2115
2116 if (dom != 0) {
2117 error_report("No support for non-zero PCI domains");
2118 exit(1);
2119 }
2120
2121 devfn = PCI_DEVFN(slot, func);
2122
2123 bus = pci_find_bus_nr(rootbus, busnr);
2124 if (!bus) {
2125 error_report("Invalid PCI device address %s for device %s",
2126 devaddr, model);
2127 exit(1);
2128 }
2129
2130 pci_dev = pci_new(devfn, model);
2131 qdev_set_nic_properties(&pci_dev->qdev, nd);
2132 pci_realize_and_unref(pci_dev, bus, &error_fatal);
2133 return true;
2134 }
2135
2136 PCIDevice *pci_vga_init(PCIBus *bus)
2137 {
2138 vga_interface_created = true;
2139 switch (vga_interface_type) {
2140 case VGA_CIRRUS:
2141 return pci_create_simple(bus, -1, "cirrus-vga");
2142 case VGA_QXL:
2143 return pci_create_simple(bus, -1, "qxl-vga");
2144 case VGA_STD:
2145 return pci_create_simple(bus, -1, "VGA");
2146 case VGA_VMWARE:
2147 return pci_create_simple(bus, -1, "vmware-svga");
2148 case VGA_VIRTIO:
2149 return pci_create_simple(bus, -1, "virtio-vga");
2150 case VGA_NONE:
2151 default: /* Other non-PCI types. Checking for unsupported types is already
2152 done in vl.c. */
2153 return NULL;
2154 }
2155 }
2156
2157 /* Whether a given bus number is in range of the secondary
2158 * bus of the given bridge device. */
2159 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
2160 {
2161 return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
2162 PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
2163 dev->config[PCI_SECONDARY_BUS] <= bus_num &&
2164 bus_num <= dev->config[PCI_SUBORDINATE_BUS];
2165 }
2166
2167 /* Whether a given bus number is in a range of a root bus */
2168 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
2169 {
2170 int i;
2171
2172 for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
2173 PCIDevice *dev = bus->devices[i];
2174
2175 if (dev && IS_PCI_BRIDGE(dev)) {
2176 if (pci_secondary_bus_in_range(dev, bus_num)) {
2177 return true;
2178 }
2179 }
2180 }
2181
2182 return false;
2183 }
2184
2185 PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
2186 {
2187 PCIBus *sec;
2188
2189 if (!bus) {
2190 return NULL;
2191 }
2192
2193 if (pci_bus_num(bus) == bus_num) {
2194 return bus;
2195 }
2196
2197 /* Consider all bus numbers in range for the host pci bridge. */
2198 if (!pci_bus_is_root(bus) &&
2199 !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
2200 return NULL;
2201 }
2202
2203 /* try child bus */
2204 for (; bus; bus = sec) {
2205 QLIST_FOREACH(sec, &bus->child, sibling) {
2206 if (pci_bus_num(sec) == bus_num) {
2207 return sec;
2208 }
2209 /* PXB buses assumed to be children of bus 0 */
2210 if (pci_bus_is_root(sec)) {
2211 if (pci_root_bus_in_range(sec, bus_num)) {
2212 break;
2213 }
2214 } else {
2215 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
2216 break;
2217 }
2218 }
2219 }
2220 }
2221
2222 return NULL;
2223 }
2224
2225 void pci_for_each_bus_depth_first(PCIBus *bus, pci_bus_ret_fn begin,
2226 pci_bus_fn end, void *parent_state)
2227 {
2228 PCIBus *sec;
2229 void *state;
2230
2231 if (!bus) {
2232 return;
2233 }
2234
2235 if (begin) {
2236 state = begin(bus, parent_state);
2237 } else {
2238 state = parent_state;
2239 }
2240
2241 QLIST_FOREACH(sec, &bus->child, sibling) {
2242 pci_for_each_bus_depth_first(sec, begin, end, state);
2243 }
2244
2245 if (end) {
2246 end(bus, state);
2247 }
2248 }
2249
2250
2251 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
2252 {
2253 bus = pci_find_bus_nr(bus, bus_num);
2254
2255 if (!bus)
2256 return NULL;
2257
2258 return bus->devices[devfn];
2259 }
2260
2261 #define ONBOARD_INDEX_MAX (16 * 1024 - 1)
2262
2263 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
2264 {
2265 PCIDevice *pci_dev = (PCIDevice *)qdev;
2266 PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
2267 ObjectClass *klass = OBJECT_CLASS(pc);
2268 Error *local_err = NULL;
2269 bool is_default_rom;
2270 uint16_t class_id;
2271
2272 /*
2273 * capped by systemd (see: udev-builtin-net_id.c)
2274 * as it's the only known user honor it to avoid users
2275 * misconfigure QEMU and then wonder why acpi-index doesn't work
2276 */
2277 if (pci_dev->acpi_index > ONBOARD_INDEX_MAX) {
2278 error_setg(errp, "acpi-index should be less or equal to %u",
2279 ONBOARD_INDEX_MAX);
2280 return;
2281 }
2282
2283 /*
2284 * make sure that acpi-index is unique across all present PCI devices
2285 */
2286 if (pci_dev->acpi_index) {
2287 GSequence *used_indexes = pci_acpi_index_list();
2288
2289 if (g_sequence_lookup(used_indexes,
2290 GINT_TO_POINTER(pci_dev->acpi_index),
2291 g_cmp_uint32, NULL)) {
2292 error_setg(errp, "a PCI device with acpi-index = %" PRIu32
2293 " already exist", pci_dev->acpi_index);
2294 return;
2295 }
2296 g_sequence_insert_sorted(used_indexes,
2297 GINT_TO_POINTER(pci_dev->acpi_index),
2298 g_cmp_uint32, NULL);
2299 }
2300
2301 if (pci_dev->romsize != UINT32_MAX && !is_power_of_2(pci_dev->romsize)) {
2302 error_setg(errp, "ROM size %u is not a power of two", pci_dev->romsize);
2303 return;
2304 }
2305
2306 /* initialize cap_present for pci_is_express() and pci_config_size(),
2307 * Note that hybrid PCIs are not set automatically and need to manage
2308 * QEMU_PCI_CAP_EXPRESS manually */
2309 if (object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE) &&
2310 !object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE)) {
2311 pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2312 }
2313
2314 if (object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE)) {
2315 pci_dev->cap_present |= QEMU_PCIE_CAP_CXL;
2316 }
2317
2318 pci_dev = do_pci_register_device(pci_dev,
2319 object_get_typename(OBJECT(qdev)),
2320 pci_dev->devfn, errp);
2321 if (pci_dev == NULL)
2322 return;
2323
2324 if (pc->realize) {
2325 pc->realize(pci_dev, &local_err);
2326 if (local_err) {
2327 error_propagate(errp, local_err);
2328 do_pci_unregister_device(pci_dev);
2329 return;
2330 }
2331 }
2332
2333 if (!pcie_sriov_register_device(pci_dev, errp)) {
2334 pci_qdev_unrealize(DEVICE(pci_dev));
2335 return;
2336 }
2337
2338 /*
2339 * A PCIe Downstream Port that do not have ARI Forwarding enabled must
2340 * associate only Device 0 with the device attached to the bus
2341 * representing the Link from the Port (PCIe base spec rev 4.0 ver 0.3,
2342 * sec 7.3.1).
2343 * With ARI, PCI_SLOT() can return non-zero value as the traditional
2344 * 5-bit Device Number and 3-bit Function Number fields in its associated
2345 * Routing IDs, Requester IDs and Completer IDs are interpreted as a
2346 * single 8-bit Function Number. Hence, ignore ARI capable devices.
2347 */
2348 if (pci_is_express(pci_dev) &&
2349 !pcie_find_capability(pci_dev, PCI_EXT_CAP_ID_ARI) &&
2350 pcie_has_upstream_port(pci_dev) &&
2351 PCI_SLOT(pci_dev->devfn)) {
2352 warn_report("PCI: slot %d is not valid for %s,"
2353 " parent device only allows plugging into slot 0.",
2354 PCI_SLOT(pci_dev->devfn), pci_dev->name);
2355 }
2356
2357 if (pci_dev->failover_pair_id) {
2358 if (!pci_bus_is_express(pci_get_bus(pci_dev))) {
2359 error_setg(errp, "failover primary device must be on "
2360 "PCIExpress bus");
2361 pci_qdev_unrealize(DEVICE(pci_dev));
2362 return;
2363 }
2364 class_id = pci_get_word(pci_dev->config + PCI_CLASS_DEVICE);
2365 if (class_id != PCI_CLASS_NETWORK_ETHERNET) {
2366 error_setg(errp, "failover primary device is not an "
2367 "Ethernet device");
2368 pci_qdev_unrealize(DEVICE(pci_dev));
2369 return;
2370 }
2371 if ((pci_dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)
2372 || (PCI_FUNC(pci_dev->devfn) != 0)) {
2373 error_setg(errp, "failover: primary device must be in its own "
2374 "PCI slot");
2375 pci_qdev_unrealize(DEVICE(pci_dev));
2376 return;
2377 }
2378 qdev->allow_unplug_during_migration = true;
2379 }
2380
2381 /* rom loading */
2382 is_default_rom = false;
2383 if (pci_dev->romfile == NULL && pc->romfile != NULL) {
2384 pci_dev->romfile = g_strdup(pc->romfile);
2385 is_default_rom = true;
2386 }
2387
2388 pci_add_option_rom(pci_dev, is_default_rom, &local_err);
2389 if (local_err) {
2390 error_propagate(errp, local_err);
2391 pci_qdev_unrealize(DEVICE(pci_dev));
2392 return;
2393 }
2394
2395 pci_set_power(pci_dev, true);
2396
2397 pci_dev->msi_trigger = pci_msi_trigger;
2398 }
2399
2400 static PCIDevice *pci_new_internal(int devfn, bool multifunction,
2401 const char *name)
2402 {
2403 DeviceState *dev;
2404
2405 dev = qdev_new(name);
2406 qdev_prop_set_int32(dev, "addr", devfn);
2407 qdev_prop_set_bit(dev, "multifunction", multifunction);
2408 return PCI_DEVICE(dev);
2409 }
2410
2411 PCIDevice *pci_new_multifunction(int devfn, const char *name)
2412 {
2413 return pci_new_internal(devfn, true, name);
2414 }
2415
2416 PCIDevice *pci_new(int devfn, const char *name)
2417 {
2418 return pci_new_internal(devfn, false, name);
2419 }
2420
2421 bool pci_realize_and_unref(PCIDevice *dev, PCIBus *bus, Error **errp)
2422 {
2423 return qdev_realize_and_unref(&dev->qdev, &bus->qbus, errp);
2424 }
2425
2426 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2427 const char *name)
2428 {
2429 PCIDevice *dev = pci_new_multifunction(devfn, name);
2430 pci_realize_and_unref(dev, bus, &error_fatal);
2431 return dev;
2432 }
2433
2434 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2435 {
2436 PCIDevice *dev = pci_new(devfn, name);
2437 pci_realize_and_unref(dev, bus, &error_fatal);
2438 return dev;
2439 }
2440
2441 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2442 {
2443 int offset = PCI_CONFIG_HEADER_SIZE;
2444 int i;
2445 for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2446 if (pdev->used[i])
2447 offset = i + 1;
2448 else if (i - offset + 1 == size)
2449 return offset;
2450 }
2451 return 0;
2452 }
2453
2454 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2455 uint8_t *prev_p)
2456 {
2457 uint8_t next, prev;
2458
2459 if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2460 return 0;
2461
2462 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2463 prev = next + PCI_CAP_LIST_NEXT)
2464 if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2465 break;
2466
2467 if (prev_p)
2468 *prev_p = prev;
2469 return next;
2470 }
2471
2472 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2473 {
2474 uint8_t next, prev, found = 0;
2475
2476 if (!(pdev->used[offset])) {
2477 return 0;
2478 }
2479
2480 assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2481
2482 for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2483 prev = next + PCI_CAP_LIST_NEXT) {
2484 if (next <= offset && next > found) {
2485 found = next;
2486 }
2487 }
2488 return found;
2489 }
2490
2491 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2492 This is needed for an option rom which is used for more than one device. */
2493 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, uint32_t size)
2494 {
2495 uint16_t vendor_id;
2496 uint16_t device_id;
2497 uint16_t rom_vendor_id;
2498 uint16_t rom_device_id;
2499 uint16_t rom_magic;
2500 uint16_t pcir_offset;
2501 uint8_t checksum;
2502
2503 /* Words in rom data are little endian (like in PCI configuration),
2504 so they can be read / written with pci_get_word / pci_set_word. */
2505
2506 /* Only a valid rom will be patched. */
2507 rom_magic = pci_get_word(ptr);
2508 if (rom_magic != 0xaa55) {
2509 trace_pci_bad_rom_magic(rom_magic, 0xaa55);
2510 return;
2511 }
2512 pcir_offset = pci_get_word(ptr + 0x18);
2513 if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2514 trace_pci_bad_pcir_offset(pcir_offset);
2515 return;
2516 }
2517
2518 vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2519 device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2520 rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2521 rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2522
2523 trace_pci_rom_and_pci_ids(pdev->romfile, vendor_id, device_id,
2524 rom_vendor_id, rom_device_id);
2525
2526 checksum = ptr[6];
2527
2528 if (vendor_id != rom_vendor_id) {
2529 /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2530 checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2531 checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2532 trace_pci_rom_checksum_change(ptr[6], checksum);
2533 ptr[6] = checksum;
2534 pci_set_word(ptr + pcir_offset + 4, vendor_id);
2535 }
2536
2537 if (device_id != rom_device_id) {
2538 /* Patch device id and checksum (at offset 6 for etherboot roms). */
2539 checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2540 checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2541 trace_pci_rom_checksum_change(ptr[6], checksum);
2542 ptr[6] = checksum;
2543 pci_set_word(ptr + pcir_offset + 6, device_id);
2544 }
2545 }
2546
2547 /* Add an option rom for the device */
2548 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2549 Error **errp)
2550 {
2551 int64_t size = 0;
2552 g_autofree char *path = NULL;
2553 char name[32];
2554 const VMStateDescription *vmsd;
2555
2556 /*
2557 * In case of incoming migration ROM will come with migration stream, no
2558 * reason to load the file. Neither we want to fail if local ROM file
2559 * mismatches with specified romsize.
2560 */
2561 bool load_file = !runstate_check(RUN_STATE_INMIGRATE);
2562
2563 if (!pdev->romfile || !strlen(pdev->romfile)) {
2564 return;
2565 }
2566
2567 if (!pdev->rom_bar) {
2568 /*
2569 * Load rom via fw_cfg instead of creating a rom bar,
2570 * for 0.11 compatibility.
2571 */
2572 int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2573
2574 /*
2575 * Hot-plugged devices can't use the option ROM
2576 * if the rom bar is disabled.
2577 */
2578 if (DEVICE(pdev)->hotplugged) {
2579 error_setg(errp, "Hot-plugged device without ROM bar"
2580 " can't have an option ROM");
2581 return;
2582 }
2583
2584 if (class == 0x0300) {
2585 rom_add_vga(pdev->romfile);
2586 } else {
2587 rom_add_option(pdev->romfile, -1);
2588 }
2589 return;
2590 }
2591
2592 if (pci_is_vf(pdev)) {
2593 if (pdev->rom_bar > 0) {
2594 error_setg(errp, "ROM BAR cannot be enabled for SR-IOV VF");
2595 }
2596
2597 return;
2598 }
2599
2600 if (load_file || pdev->romsize == UINT32_MAX) {
2601 path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2602 if (path == NULL) {
2603 path = g_strdup(pdev->romfile);
2604 }
2605
2606 size = get_image_size(path, NULL);
2607 if (size < 0) {
2608 error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2609 return;
2610 } else if (size == 0) {
2611 error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2612 return;
2613 } else if (size > 2 * GiB) {
2614 error_setg(errp,
2615 "romfile \"%s\" too large (size cannot exceed 2 GiB)",
2616 pdev->romfile);
2617 return;
2618 }
2619 if (pdev->romsize != UINT_MAX) {
2620 if (size > pdev->romsize) {
2621 error_setg(errp, "romfile \"%s\" (%u bytes) "
2622 "is too large for ROM size %u",
2623 pdev->romfile, (uint32_t)size, pdev->romsize);
2624 return;
2625 }
2626 } else {
2627 pdev->romsize = pow2ceil(size);
2628 }
2629 }
2630
2631 vmsd = qdev_get_vmsd(DEVICE(pdev));
2632 snprintf(name, sizeof(name), "%s.rom",
2633 vmsd ? vmsd->name : object_get_typename(OBJECT(pdev)));
2634
2635 pdev->has_rom = true;
2636 memory_region_init_rom(&pdev->rom, OBJECT(pdev), name, pdev->romsize,
2637 &error_fatal);
2638
2639 if (load_file) {
2640 void *ptr = memory_region_get_ram_ptr(&pdev->rom);
2641
2642 if (load_image_size(path, ptr, size) < 0) {
2643 error_setg(errp, "failed to load romfile \"%s\"", pdev->romfile);
2644 return;
2645 }
2646
2647 if (is_default_rom) {
2648 /* Only the default rom images will be patched (if needed). */
2649 pci_patch_ids(pdev, ptr, size);
2650 }
2651 }
2652
2653 pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2654 }
2655
2656 static void pci_del_option_rom(PCIDevice *pdev)
2657 {
2658 if (!pdev->has_rom)
2659 return;
2660
2661 vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2662 pdev->has_rom = false;
2663 }
2664
2665 /*
2666 * On success, pci_add_capability() returns a positive value
2667 * that the offset of the pci capability.
2668 * On failure, it sets an error and returns a negative error
2669 * code.
2670 */
2671 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2672 uint8_t offset, uint8_t size,
2673 Error **errp)
2674 {
2675 uint8_t *config;
2676 int i, overlapping_cap;
2677
2678 if (!offset) {
2679 offset = pci_find_space(pdev, size);
2680 /* out of PCI config space is programming error */
2681 assert(offset);
2682 } else {
2683 /* Verify that capabilities don't overlap. Note: device assignment
2684 * depends on this check to verify that the device is not broken.
2685 * Should never trigger for emulated devices, but it's helpful
2686 * for debugging these. */
2687 for (i = offset; i < offset + size; i++) {
2688 overlapping_cap = pci_find_capability_at_offset(pdev, i);
2689 if (overlapping_cap) {
2690 error_setg(errp, "%s:%02x:%02x.%x "
2691 "Attempt to add PCI capability %x at offset "
2692 "%x overlaps existing capability %x at offset %x",
2693 pci_root_bus_path(pdev), pci_dev_bus_num(pdev),
2694 PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2695 cap_id, offset, overlapping_cap, i);
2696 return -EINVAL;
2697 }
2698 }
2699 }
2700
2701 config = pdev->config + offset;
2702 config[PCI_CAP_LIST_ID] = cap_id;
2703 config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2704 pdev->config[PCI_CAPABILITY_LIST] = offset;
2705 pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2706 memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2707 /* Make capability read-only by default */
2708 memset(pdev->wmask + offset, 0, size);
2709 /* Check capability by default */
2710 memset(pdev->cmask + offset, 0xFF, size);
2711 return offset;
2712 }
2713
2714 /* Unlink capability from the pci config space. */
2715 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2716 {
2717 uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2718 if (!offset)
2719 return;
2720 pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2721 /* Make capability writable again */
2722 memset(pdev->wmask + offset, 0xff, size);
2723 memset(pdev->w1cmask + offset, 0, size);
2724 /* Clear cmask as device-specific registers can't be checked */
2725 memset(pdev->cmask + offset, 0, size);
2726 memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2727
2728 if (!pdev->config[PCI_CAPABILITY_LIST])
2729 pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2730 }
2731
2732 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2733 {
2734 return pci_find_capability_list(pdev, cap_id, NULL);
2735 }
2736
2737 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2738 {
2739 PCIDevice *d = (PCIDevice *)dev;
2740 const char *name = NULL;
2741 const pci_class_desc *desc = pci_class_descriptions;
2742 int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2743
2744 while (desc->desc &&
2745 (class & ~desc->fw_ign_bits) !=
2746 (desc->class & ~desc->fw_ign_bits)) {
2747 desc++;
2748 }
2749
2750 if (desc->desc) {
2751 name = desc->fw_name;
2752 }
2753
2754 if (name) {
2755 pstrcpy(buf, len, name);
2756 } else {
2757 snprintf(buf, len, "pci%04x,%04x",
2758 pci_get_word(d->config + PCI_VENDOR_ID),
2759 pci_get_word(d->config + PCI_DEVICE_ID));
2760 }
2761
2762 return buf;
2763 }
2764
2765 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2766 {
2767 PCIDevice *d = (PCIDevice *)dev;
2768 char name[33];
2769 int has_func = !!PCI_FUNC(d->devfn);
2770
2771 return g_strdup_printf("%s@%x%s%.*x",
2772 pci_dev_fw_name(dev, name, sizeof(name)),
2773 PCI_SLOT(d->devfn),
2774 has_func ? "," : "",
2775 has_func,
2776 PCI_FUNC(d->devfn));
2777 }
2778
2779 static char *pcibus_get_dev_path(DeviceState *dev)
2780 {
2781 PCIDevice *d = container_of(dev, PCIDevice, qdev);
2782 PCIDevice *t;
2783 int slot_depth;
2784 /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2785 * 00 is added here to make this format compatible with
2786 * domain:Bus:Slot.Func for systems without nested PCI bridges.
2787 * Slot.Function list specifies the slot and function numbers for all
2788 * devices on the path from root to the specific device. */
2789 const char *root_bus_path;
2790 int root_bus_len;
2791 char slot[] = ":SS.F";
2792 int slot_len = sizeof slot - 1 /* For '\0' */;
2793 int path_len;
2794 char *path, *p;
2795 int s;
2796
2797 root_bus_path = pci_root_bus_path(d);
2798 root_bus_len = strlen(root_bus_path);
2799
2800 /* Calculate # of slots on path between device and root. */;
2801 slot_depth = 0;
2802 for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2803 ++slot_depth;
2804 }
2805
2806 path_len = root_bus_len + slot_len * slot_depth;
2807
2808 /* Allocate memory, fill in the terminating null byte. */
2809 path = g_malloc(path_len + 1 /* For '\0' */);
2810 path[path_len] = '\0';
2811
2812 memcpy(path, root_bus_path, root_bus_len);
2813
2814 /* Fill in slot numbers. We walk up from device to root, so need to print
2815 * them in the reverse order, last to first. */
2816 p = path + path_len;
2817 for (t = d; t; t = pci_get_bus(t)->parent_dev) {
2818 p -= slot_len;
2819 s = snprintf(slot, sizeof slot, ":%02x.%x",
2820 PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2821 assert(s == slot_len);
2822 memcpy(p, slot, slot_len);
2823 }
2824
2825 return path;
2826 }
2827
2828 static int pci_qdev_find_recursive(PCIBus *bus,
2829 const char *id, PCIDevice **pdev)
2830 {
2831 DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2832 if (!qdev) {
2833 return -ENODEV;
2834 }
2835
2836 /* roughly check if given qdev is pci device */
2837 if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2838 *pdev = PCI_DEVICE(qdev);
2839 return 0;
2840 }
2841 return -EINVAL;
2842 }
2843
2844 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2845 {
2846 PCIHostState *host_bridge;
2847 int rc = -ENODEV;
2848
2849 QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2850 int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2851 if (!tmp) {
2852 rc = 0;
2853 break;
2854 }
2855 if (tmp != -ENODEV) {
2856 rc = tmp;
2857 }
2858 }
2859
2860 return rc;
2861 }
2862
2863 static char *pci_qdev_property_get_loadparm(Object *obj, Error **errp)
2864 {
2865 return g_strdup(PCI_DEVICE(obj)->loadparm);
2866 }
2867
2868 static void pci_qdev_property_set_loadparm(Object *obj, const char *value,
2869 Error **errp)
2870 {
2871 void *lp_str;
2872
2873 if (object_property_get_int(obj, "bootindex", NULL) < 0) {
2874 error_setg(errp, "'loadparm' is only valid for boot devices");
2875 return;
2876 }
2877
2878 lp_str = g_malloc0(strlen(value) + 1);
2879 if (!qdev_prop_sanitize_s390x_loadparm(lp_str, value, errp)) {
2880 g_free(lp_str);
2881 return;
2882 }
2883 PCI_DEVICE(obj)->loadparm = lp_str;
2884 }
2885
2886 void pci_qdev_property_add_specifics(DeviceClass *dc)
2887 {
2888 ObjectClass *oc = OBJECT_CLASS(dc);
2889
2890 /* The loadparm property is only supported on s390x */
2891 if (target_s390x()) {
2892 object_class_property_add_str(oc, "loadparm",
2893 pci_qdev_property_get_loadparm,
2894 pci_qdev_property_set_loadparm);
2895 object_class_property_set_description(oc, "loadparm",
2896 "load parameter (s390x only)");
2897 }
2898 }
2899
2900 MemoryRegion *pci_address_space(PCIDevice *dev)
2901 {
2902 return pci_get_bus(dev)->address_space_mem;
2903 }
2904
2905 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2906 {
2907 return pci_get_bus(dev)->address_space_io;
2908 }
2909
2910 static void pci_device_class_init(ObjectClass *klass, const void *data)
2911 {
2912 DeviceClass *k = DEVICE_CLASS(klass);
2913
2914 k->realize = pci_qdev_realize;
2915 k->unrealize = pci_qdev_unrealize;
2916 k->bus_type = TYPE_PCI_BUS;
2917 device_class_set_props(k, pci_props);
2918 object_class_property_set_description(
2919 klass, "x-max-bounce-buffer-size",
2920 "Maximum buffer size allocated for bounce buffers used for mapped "
2921 "access to indirect DMA memory");
2922 }
2923
2924 static void pci_device_class_base_init(ObjectClass *klass, const void *data)
2925 {
2926 if (!object_class_is_abstract(klass)) {
2927 ObjectClass *conventional =
2928 object_class_dynamic_cast(klass, INTERFACE_CONVENTIONAL_PCI_DEVICE);
2929 ObjectClass *pcie =
2930 object_class_dynamic_cast(klass, INTERFACE_PCIE_DEVICE);
2931 ObjectClass *cxl =
2932 object_class_dynamic_cast(klass, INTERFACE_CXL_DEVICE);
2933 assert(conventional || pcie || cxl);
2934 }
2935 }
2936
2937 /*
2938 * Get IOMMU root bus, aliased bus and devfn of a PCI device
2939 *
2940 * IOMMU root bus is needed by all call sites to call into iommu_ops.
2941 * For call sites which don't need aliased BDF, passing NULL to
2942 * aliased_[bus|devfn] is allowed.
2943 *
2944 * Returns true if PCI device RID is aliased or false otherwise.
2945 *
2946 * @piommu_bus: return root #PCIBus backed by an IOMMU for the PCI device.
2947 *
2948 * @aliased_bus: return aliased #PCIBus of the PCI device, optional.
2949 *
2950 * @aliased_devfn: return aliased devfn of the PCI device, optional.
2951 */
2952 bool pci_device_get_iommu_bus_devfn(PCIDevice *dev, PCIBus **piommu_bus,
2953 PCIBus **aliased_bus, int *aliased_devfn)
2954 {
2955 PCIBus *bus = pci_get_bus(dev);
2956 PCIBus *iommu_bus = bus;
2957 int devfn = dev->devfn;
2958 bool aliased = false;
2959
2960 while (iommu_bus && !iommu_bus->iommu_ops && iommu_bus->parent_dev) {
2961 PCIBus *parent_bus = pci_get_bus(iommu_bus->parent_dev);
2962
2963 /*
2964 * The requester ID of the provided device may be aliased, as seen from
2965 * the IOMMU, due to topology limitations. The IOMMU relies on a
2966 * requester ID to provide a unique AddressSpace for devices, but
2967 * conventional PCI buses pre-date such concepts. Instead, the PCIe-
2968 * to-PCI bridge creates and accepts transactions on behalf of down-
2969 * stream devices. When doing so, all downstream devices are masked
2970 * (aliased) behind a single requester ID. The requester ID used
2971 * depends on the format of the bridge devices. Proper PCIe-to-PCI
2972 * bridges, with a PCIe capability indicating such, follow the
2973 * guidelines of chapter 2.3 of the PCIe-to-PCI/X bridge specification,
2974 * where the bridge uses the seconary bus as the bridge portion of the
2975 * requester ID and devfn of 00.0. For other bridges, typically those
2976 * found on the root complex such as the dmi-to-pci-bridge, we follow
2977 * the convention of typical bare-metal hardware, which uses the
2978 * requester ID of the bridge itself. There are device specific
2979 * exceptions to these rules, but these are the defaults that the
2980 * Linux kernel uses when determining DMA aliases itself and believed
2981 * to be true for the bare metal equivalents of the devices emulated
2982 * in QEMU.
2983 */
2984 if (!pci_bus_is_express(iommu_bus)) {
2985 PCIDevice *parent = iommu_bus->parent_dev;
2986
2987 if (pci_is_express(parent) &&
2988 pcie_cap_get_type(parent) == PCI_EXP_TYPE_PCI_BRIDGE) {
2989 devfn = PCI_DEVFN(0, 0);
2990 bus = iommu_bus;
2991 } else {
2992 devfn = parent->devfn;
2993 bus = parent_bus;
2994 }
2995 aliased = true;
2996 }
2997
2998 /*
2999 * When multiple PCI Express Root Buses are defined using pxb-pcie,
3000 * the IOMMU configuration may be specific to each root bus. However,
3001 * pxb-pcie acts as a special root complex whose parent is effectively
3002 * the default root complex(pcie.0). Ensure that we retrieve the
3003 * correct IOMMU ops(if any) in such cases.
3004 */
3005 if (pci_bus_is_express(iommu_bus) && pci_bus_is_root(iommu_bus)) {
3006 if (parent_bus->iommu_per_bus) {
3007 break;
3008 }
3009 }
3010
3011 iommu_bus = parent_bus;
3012 }
3013
3014 assert(0 <= devfn && devfn < PCI_DEVFN_MAX);
3015 assert(iommu_bus);
3016
3017 if (pci_bus_bypass_iommu(bus) || !iommu_bus->iommu_ops) {
3018 iommu_bus = NULL;
3019 }
3020
3021 *piommu_bus = iommu_bus;
3022
3023 if (aliased_bus) {
3024 *aliased_bus = bus;
3025 }
3026
3027 if (aliased_devfn) {
3028 *aliased_devfn = devfn;
3029 }
3030
3031 return aliased;
3032 }
3033
3034 bool pci_device_iommu_msi_direct_gpa(PCIDevice *dev, hwaddr *out_doorbell)
3035 {
3036 PCIBus *bus;
3037 PCIBus *iommu_bus;
3038 int devfn;
3039
3040 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3041 if (iommu_bus) {
3042 if (iommu_bus->iommu_ops->get_msi_direct_gpa) {
3043 *out_doorbell = iommu_bus->iommu_ops->get_msi_direct_gpa(bus,
3044 iommu_bus->iommu_opaque, devfn);
3045 return true;
3046 }
3047 }
3048 return false;
3049 }
3050
3051 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
3052 {
3053 PCIBus *bus;
3054 PCIBus *iommu_bus;
3055 int devfn;
3056
3057 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3058 if (iommu_bus) {
3059 return iommu_bus->iommu_ops->get_address_space(bus,
3060 iommu_bus->iommu_opaque, devfn);
3061 }
3062 return &address_space_memory;
3063 }
3064
3065 int pci_iommu_init_iotlb_notifier(PCIDevice *dev, IOMMUNotifier *n,
3066 IOMMUNotify fn, void *opaque)
3067 {
3068 PCIBus *bus;
3069 PCIBus *iommu_bus;
3070 int devfn;
3071
3072 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3073 if (iommu_bus && iommu_bus->iommu_ops->init_iotlb_notifier) {
3074 iommu_bus->iommu_ops->init_iotlb_notifier(bus, iommu_bus->iommu_opaque,
3075 devfn, n, fn, opaque);
3076 return 0;
3077 }
3078
3079 return -ENODEV;
3080 }
3081
3082 bool pci_device_set_iommu_device(PCIDevice *dev, HostIOMMUDevice *hiod,
3083 Error **errp)
3084 {
3085 PCIBus *iommu_bus, *aliased_bus;
3086 int aliased_devfn;
3087
3088 /* set_iommu_device requires device's direct BDF instead of aliased BDF */
3089 pci_device_get_iommu_bus_devfn(dev, &iommu_bus,
3090 &aliased_bus, &aliased_devfn);
3091 if (iommu_bus && iommu_bus->iommu_ops->set_iommu_device) {
3092 hiod->aliased_bus = aliased_bus;
3093 hiod->aliased_devfn = aliased_devfn;
3094 return iommu_bus->iommu_ops->set_iommu_device(pci_get_bus(dev),
3095 iommu_bus->iommu_opaque,
3096 dev->devfn, hiod, errp);
3097 }
3098 return true;
3099 }
3100
3101 void pci_device_unset_iommu_device(PCIDevice *dev)
3102 {
3103 PCIBus *iommu_bus;
3104
3105 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, NULL, NULL);
3106 if (iommu_bus && iommu_bus->iommu_ops->unset_iommu_device) {
3107 return iommu_bus->iommu_ops->unset_iommu_device(pci_get_bus(dev),
3108 iommu_bus->iommu_opaque,
3109 dev->devfn);
3110 }
3111 }
3112
3113 uint64_t pci_device_get_viommu_flags(PCIDevice *dev)
3114 {
3115 PCIBus *iommu_bus;
3116
3117 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, NULL, NULL);
3118 if (iommu_bus && iommu_bus->iommu_ops->get_viommu_flags) {
3119 return iommu_bus->iommu_ops->get_viommu_flags(iommu_bus->iommu_opaque);
3120 }
3121 return 0;
3122 }
3123
3124 uint64_t pci_device_get_host_iommu_quirks(PCIDevice *dev, uint32_t type,
3125 void *caps, uint32_t size)
3126 {
3127 PCIBus *iommu_bus;
3128
3129 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, NULL, NULL);
3130 if (iommu_bus && iommu_bus->iommu_ops->get_host_iommu_quirks) {
3131 return iommu_bus->iommu_ops->get_host_iommu_quirks(type, caps, size);
3132 }
3133 return 0;
3134 }
3135
3136 int pci_pri_request_page(PCIDevice *dev, uint32_t pasid, bool priv_req,
3137 bool exec_req, hwaddr addr, bool lpig,
3138 uint16_t prgi, bool is_read, bool is_write)
3139 {
3140 PCIBus *bus;
3141 PCIBus *iommu_bus;
3142 int devfn;
3143
3144 if (!dev->is_master ||
3145 ((pasid != PCI_NO_PASID) && !pcie_pasid_enabled(dev))) {
3146 return -EPERM;
3147 }
3148
3149 if (!pcie_pri_enabled(dev)) {
3150 return -EPERM;
3151 }
3152
3153 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3154 if (iommu_bus && iommu_bus->iommu_ops->pri_request_page) {
3155 return iommu_bus->iommu_ops->pri_request_page(bus,
3156 iommu_bus->iommu_opaque,
3157 devfn, pasid, priv_req,
3158 exec_req, addr, lpig, prgi,
3159 is_read, is_write);
3160 }
3161
3162 return -ENODEV;
3163 }
3164
3165 int pci_pri_register_notifier(PCIDevice *dev, uint32_t pasid,
3166 IOMMUPRINotifier *notifier)
3167 {
3168 PCIBus *bus;
3169 PCIBus *iommu_bus;
3170 int devfn;
3171
3172 if (!dev->is_master ||
3173 ((pasid != PCI_NO_PASID) && !pcie_pasid_enabled(dev))) {
3174 return -EPERM;
3175 }
3176
3177 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3178 if (iommu_bus && iommu_bus->iommu_ops->pri_register_notifier) {
3179 iommu_bus->iommu_ops->pri_register_notifier(bus,
3180 iommu_bus->iommu_opaque,
3181 devfn, pasid, notifier);
3182 return 0;
3183 }
3184
3185 return -ENODEV;
3186 }
3187
3188 void pci_pri_unregister_notifier(PCIDevice *dev, uint32_t pasid)
3189 {
3190 PCIBus *bus;
3191 PCIBus *iommu_bus;
3192 int devfn;
3193
3194 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3195 if (iommu_bus && iommu_bus->iommu_ops->pri_unregister_notifier) {
3196 iommu_bus->iommu_ops->pri_unregister_notifier(bus,
3197 iommu_bus->iommu_opaque,
3198 devfn, pasid);
3199 }
3200 }
3201
3202 ssize_t pci_ats_request_translation(PCIDevice *dev, uint32_t pasid,
3203 bool priv_req, bool exec_req,
3204 hwaddr addr, size_t length,
3205 bool no_write, IOMMUTLBEntry *result,
3206 size_t result_length,
3207 uint32_t *err_count)
3208 {
3209 PCIBus *bus;
3210 PCIBus *iommu_bus;
3211 int devfn;
3212
3213 if (!dev->is_master ||
3214 ((pasid != PCI_NO_PASID) && !pcie_pasid_enabled(dev))) {
3215 return -EPERM;
3216 }
3217
3218 if (result_length == 0) {
3219 return -ENOSPC;
3220 }
3221
3222 if (!pcie_ats_enabled(dev)) {
3223 return -EPERM;
3224 }
3225
3226 if (priv_req && !pcie_pasid_priv_enabled(dev)) {
3227 return -EPERM;
3228 }
3229
3230 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3231 if (iommu_bus && iommu_bus->iommu_ops->ats_request_translation) {
3232 return iommu_bus->iommu_ops->ats_request_translation(bus,
3233 iommu_bus->iommu_opaque,
3234 devfn, pasid, priv_req,
3235 exec_req, addr, length,
3236 no_write, result,
3237 result_length, err_count);
3238 }
3239
3240 return -ENODEV;
3241 }
3242
3243 int pci_iommu_register_iotlb_notifier(PCIDevice *dev, uint32_t pasid,
3244 IOMMUNotifier *n)
3245 {
3246 PCIBus *bus;
3247 PCIBus *iommu_bus;
3248 int devfn;
3249
3250 if ((pasid != PCI_NO_PASID) && !pcie_pasid_enabled(dev)) {
3251 return -EPERM;
3252 }
3253
3254 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3255 if (iommu_bus && iommu_bus->iommu_ops->register_iotlb_notifier) {
3256 iommu_bus->iommu_ops->register_iotlb_notifier(bus,
3257 iommu_bus->iommu_opaque, devfn,
3258 pasid, n);
3259 return 0;
3260 }
3261
3262 return -ENODEV;
3263 }
3264
3265 int pci_iommu_unregister_iotlb_notifier(PCIDevice *dev, uint32_t pasid,
3266 IOMMUNotifier *n)
3267 {
3268 PCIBus *bus;
3269 PCIBus *iommu_bus;
3270 int devfn;
3271
3272 if ((pasid != PCI_NO_PASID) && !pcie_pasid_enabled(dev)) {
3273 return -EPERM;
3274 }
3275
3276 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, &bus, &devfn);
3277 if (iommu_bus && iommu_bus->iommu_ops->unregister_iotlb_notifier) {
3278 iommu_bus->iommu_ops->unregister_iotlb_notifier(bus,
3279 iommu_bus->iommu_opaque,
3280 devfn, pasid, n);
3281 return 0;
3282 }
3283
3284 return -ENODEV;
3285 }
3286
3287 int pci_iommu_get_iotlb_info(PCIDevice *dev, uint8_t *addr_width,
3288 uint32_t *min_page_size)
3289 {
3290 PCIBus *iommu_bus;
3291
3292 pci_device_get_iommu_bus_devfn(dev, &iommu_bus, NULL, NULL);
3293 if (iommu_bus && iommu_bus->iommu_ops->get_iotlb_info) {
3294 iommu_bus->iommu_ops->get_iotlb_info(iommu_bus->iommu_opaque,
3295 addr_width, min_page_size);
3296 return 0;
3297 }
3298
3299 return -ENODEV;
3300 }
3301
3302 void pci_setup_iommu(PCIBus *bus, const PCIIOMMUOps *ops, void *opaque)
3303 {
3304 /*
3305 * If called, pci_setup_iommu() should provide a minimum set of
3306 * useful callbacks for the bus.
3307 */
3308 assert(ops);
3309 assert(ops->get_address_space);
3310
3311 bus->iommu_ops = ops;
3312 bus->iommu_opaque = opaque;
3313 }
3314
3315 /*
3316 * Similar to pci_setup_iommu(), but sets iommu_per_bus to true,
3317 * indicating that the IOMMU is specific to this bus. This is used by
3318 * IOMMU implementations that are tied to a specific PCIe root complex.
3319 *
3320 * In QEMU, pxb-pcie behaves as a special root complex whose parent is
3321 * effectively the default root complex (pcie.0). The iommu_per_bus
3322 * is checked in pci_device_get_iommu_bus_devfn() to ensure the correct
3323 * IOMMU ops are returned, avoiding the use of the parent’s IOMMU when
3324 * it's not appropriate.
3325 */
3326 bool pci_setup_iommu_per_bus(PCIBus *bus, const PCIIOMMUOps *ops,
3327 void *opaque, Error **errp)
3328 {
3329 if (bus->iommu_per_bus) {
3330 error_setg(errp, "An iommu is already attached to this bus");
3331 return false;
3332 }
3333 pci_setup_iommu(bus, ops, opaque);
3334 bus->iommu_per_bus = true;
3335 return true;
3336 }
3337
3338 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
3339 {
3340 Range *range = opaque;
3341 uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
3342 int i;
3343
3344 if (!(cmd & PCI_COMMAND_MEMORY)) {
3345 return;
3346 }
3347
3348 if (IS_PCI_BRIDGE(dev)) {
3349 pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
3350 pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
3351
3352 base = MAX(base, 0x1ULL << 32);
3353
3354 if (limit >= base) {
3355 Range pref_range;
3356 range_set_bounds(&pref_range, base, limit);
3357 range_extend(range, &pref_range);
3358 }
3359 }
3360 for (i = 0; i < PCI_NUM_REGIONS; ++i) {
3361 PCIIORegion *r = &dev->io_regions[i];
3362 pcibus_t lob, upb;
3363 Range region_range;
3364
3365 if (!r->size ||
3366 (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
3367 !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
3368 continue;
3369 }
3370
3371 lob = pci_bar_address(dev, i, r->type, r->size);
3372 upb = lob + r->size - 1;
3373 if (lob == PCI_BAR_UNMAPPED) {
3374 continue;
3375 }
3376
3377 lob = MAX(lob, 0x1ULL << 32);
3378
3379 if (upb >= lob) {
3380 range_set_bounds(&region_range, lob, upb);
3381 range_extend(range, &region_range);
3382 }
3383 }
3384 }
3385
3386 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
3387 {
3388 range_make_empty(range);
3389 pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
3390 }
3391
3392 static bool pcie_has_upstream_port(PCIDevice *dev)
3393 {
3394 PCIDevice *parent_dev = pci_bridge_get_device(pci_get_bus(dev));
3395
3396 /* Device associated with an upstream port.
3397 * As there are several types of these, it's easier to check the
3398 * parent device: upstream ports are always connected to
3399 * root or downstream ports.
3400 */
3401 return parent_dev &&
3402 pci_is_express(parent_dev) &&
3403 parent_dev->exp.exp_cap &&
3404 (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
3405 pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
3406 }
3407
3408 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
3409 {
3410 PCIBus *bus = pci_get_bus(pci_dev);
3411
3412 if(pcie_has_upstream_port(pci_dev)) {
3413 /* With an upstream PCIe port, we only support 1 device at slot 0 */
3414 return bus->devices[0];
3415 } else {
3416 /* Other bus types might support multiple devices at slots 0-31 */
3417 return bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
3418 }
3419 }
3420
3421 MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
3422 {
3423 MSIMessage msg;
3424 if (msix_enabled(dev)) {
3425 msg = msix_get_message(dev, vector);
3426 } else if (msi_enabled(dev)) {
3427 msg = msi_get_message(dev, vector);
3428 } else {
3429 /* Should never happen */
3430 error_report("%s: unknown interrupt type", __func__);
3431 abort();
3432 }
3433 return msg;
3434 }
3435
3436 void pci_set_power(PCIDevice *d, bool state)
3437 {
3438 /*
3439 * Don't change the enabled state of VFs when powering on/off the device.
3440 *
3441 * When powering on, VFs must not be enabled immediately but they must
3442 * wait until the guest configures SR-IOV.
3443 * When powering off, their corresponding PFs will be reset and disable
3444 * VFs.
3445 */
3446 if (!pci_is_vf(d)) {
3447 pci_set_enabled(d, state);
3448 }
3449 }
3450
3451 void pci_set_enabled(PCIDevice *d, bool state)
3452 {
3453 if (d->enabled == state) {
3454 return;
3455 }
3456
3457 d->enabled = state;
3458 pci_update_mappings(d);
3459 pci_set_master(d, (pci_get_word(d->config + PCI_COMMAND)
3460 & PCI_COMMAND_MASTER) && d->enabled);
3461 if (qdev_is_realized(&d->qdev)) {
3462 pci_device_reset(d);
3463 }
3464 }
3465
3466 static const TypeInfo pci_device_type_info = {
3467 .name = TYPE_PCI_DEVICE,
3468 .parent = TYPE_DEVICE,
3469 .instance_size = sizeof(PCIDevice),
3470 .abstract = true,
3471 .class_size = sizeof(PCIDeviceClass),
3472 .class_init = pci_device_class_init,
3473 .class_base_init = pci_device_class_base_init,
3474 };
3475
3476 static void pci_register_types(void)
3477 {
3478 type_register_static(&pci_bus_info);
3479 type_register_static(&pcie_bus_info);
3480 type_register_static(&cxl_bus_info);
3481 type_register_static(&conventional_pci_interface_info);
3482 type_register_static(&cxl_interface_info);
3483 type_register_static(&pcie_interface_info);
3484 type_register_static(&pci_device_type_info);
3485 }
3486
3487 type_init(pci_register_types)