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