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