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