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