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