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