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