xref: /qemu/hw/pci/pci.c (revision 603476c2)
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(devfn),
986                    bus->devices[PCI_DEVFN(PCI_SLOT(devfn), 0)]->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     Error *err = NULL;
1783     PCIBus *bus;
1784     PCIDevice *pci_dev;
1785     DeviceState *dev;
1786     int devfn;
1787     int i;
1788 
1789     if (qemu_show_nic_models(nd->model, pci_nic_models)) {
1790         exit(0);
1791     }
1792 
1793     i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1794     if (i < 0) {
1795         exit(1);
1796     }
1797 
1798     bus = pci_get_bus_devfn(&devfn, rootbus, devaddr);
1799     if (!bus) {
1800         error_report("Invalid PCI device address %s for device %s",
1801                      devaddr, pci_nic_names[i]);
1802         exit(1);
1803     }
1804 
1805     pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1806     dev = &pci_dev->qdev;
1807     qdev_set_nic_properties(dev, nd);
1808 
1809     object_property_set_bool(OBJECT(dev), true, "realized", &err);
1810     if (err) {
1811         error_report_err(err);
1812         object_unparent(OBJECT(dev));
1813         exit(1);
1814     }
1815 
1816     return pci_dev;
1817 }
1818 
1819 PCIDevice *pci_vga_init(PCIBus *bus)
1820 {
1821     switch (vga_interface_type) {
1822     case VGA_CIRRUS:
1823         return pci_create_simple(bus, -1, "cirrus-vga");
1824     case VGA_QXL:
1825         return pci_create_simple(bus, -1, "qxl-vga");
1826     case VGA_STD:
1827         return pci_create_simple(bus, -1, "VGA");
1828     case VGA_VMWARE:
1829         return pci_create_simple(bus, -1, "vmware-svga");
1830     case VGA_VIRTIO:
1831         return pci_create_simple(bus, -1, "virtio-vga");
1832     case VGA_NONE:
1833     default: /* Other non-PCI types. Checking for unsupported types is already
1834                 done in vl.c. */
1835         return NULL;
1836     }
1837 }
1838 
1839 /* Whether a given bus number is in range of the secondary
1840  * bus of the given bridge device. */
1841 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1842 {
1843     return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1844              PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1845         dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1846         bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1847 }
1848 
1849 /* Whether a given bus number is in a range of a root bus */
1850 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1851 {
1852     int i;
1853 
1854     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1855         PCIDevice *dev = bus->devices[i];
1856 
1857         if (dev && PCI_DEVICE_GET_CLASS(dev)->is_bridge) {
1858             if (pci_secondary_bus_in_range(dev, bus_num)) {
1859                 return true;
1860             }
1861         }
1862     }
1863 
1864     return false;
1865 }
1866 
1867 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1868 {
1869     PCIBus *sec;
1870 
1871     if (!bus) {
1872         return NULL;
1873     }
1874 
1875     if (pci_bus_num(bus) == bus_num) {
1876         return bus;
1877     }
1878 
1879     /* Consider all bus numbers in range for the host pci bridge. */
1880     if (!pci_bus_is_root(bus) &&
1881         !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1882         return NULL;
1883     }
1884 
1885     /* try child bus */
1886     for (; bus; bus = sec) {
1887         QLIST_FOREACH(sec, &bus->child, sibling) {
1888             if (pci_bus_num(sec) == bus_num) {
1889                 return sec;
1890             }
1891             /* PXB buses assumed to be children of bus 0 */
1892             if (pci_bus_is_root(sec)) {
1893                 if (pci_root_bus_in_range(sec, bus_num)) {
1894                     break;
1895                 }
1896             } else {
1897                 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1898                     break;
1899                 }
1900             }
1901         }
1902     }
1903 
1904     return NULL;
1905 }
1906 
1907 void pci_for_each_bus_depth_first(PCIBus *bus,
1908                                   void *(*begin)(PCIBus *bus, void *parent_state),
1909                                   void (*end)(PCIBus *bus, void *state),
1910                                   void *parent_state)
1911 {
1912     PCIBus *sec;
1913     void *state;
1914 
1915     if (!bus) {
1916         return;
1917     }
1918 
1919     if (begin) {
1920         state = begin(bus, parent_state);
1921     } else {
1922         state = parent_state;
1923     }
1924 
1925     QLIST_FOREACH(sec, &bus->child, sibling) {
1926         pci_for_each_bus_depth_first(sec, begin, end, state);
1927     }
1928 
1929     if (end) {
1930         end(bus, state);
1931     }
1932 }
1933 
1934 
1935 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1936 {
1937     bus = pci_find_bus_nr(bus, bus_num);
1938 
1939     if (!bus)
1940         return NULL;
1941 
1942     return bus->devices[devfn];
1943 }
1944 
1945 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
1946 {
1947     PCIDevice *pci_dev = (PCIDevice *)qdev;
1948     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1949     Error *local_err = NULL;
1950     PCIBus *bus;
1951     bool is_default_rom;
1952 
1953     /* initialize cap_present for pci_is_express() and pci_config_size() */
1954     if (pc->is_express) {
1955         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1956     }
1957 
1958     bus = PCI_BUS(qdev_get_parent_bus(qdev));
1959     pci_dev = do_pci_register_device(pci_dev, bus,
1960                                      object_get_typename(OBJECT(qdev)),
1961                                      pci_dev->devfn, errp);
1962     if (pci_dev == NULL)
1963         return;
1964 
1965     if (pc->realize) {
1966         pc->realize(pci_dev, &local_err);
1967         if (local_err) {
1968             error_propagate(errp, local_err);
1969             do_pci_unregister_device(pci_dev);
1970             return;
1971         }
1972     }
1973 
1974     /* rom loading */
1975     is_default_rom = false;
1976     if (pci_dev->romfile == NULL && pc->romfile != NULL) {
1977         pci_dev->romfile = g_strdup(pc->romfile);
1978         is_default_rom = true;
1979     }
1980 
1981     pci_add_option_rom(pci_dev, is_default_rom, &local_err);
1982     if (local_err) {
1983         error_propagate(errp, local_err);
1984         pci_qdev_unrealize(DEVICE(pci_dev), NULL);
1985         return;
1986     }
1987 }
1988 
1989 static void pci_default_realize(PCIDevice *dev, Error **errp)
1990 {
1991     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
1992 
1993     if (pc->init) {
1994         if (pc->init(dev) < 0) {
1995             error_setg(errp, "Device initialization failed");
1996             return;
1997         }
1998     }
1999 }
2000 
2001 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
2002                                     const char *name)
2003 {
2004     DeviceState *dev;
2005 
2006     dev = qdev_create(&bus->qbus, name);
2007     qdev_prop_set_int32(dev, "addr", devfn);
2008     qdev_prop_set_bit(dev, "multifunction", multifunction);
2009     return PCI_DEVICE(dev);
2010 }
2011 
2012 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
2013                                            bool multifunction,
2014                                            const char *name)
2015 {
2016     PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
2017     qdev_init_nofail(&dev->qdev);
2018     return dev;
2019 }
2020 
2021 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
2022 {
2023     return pci_create_multifunction(bus, devfn, false, name);
2024 }
2025 
2026 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
2027 {
2028     return pci_create_simple_multifunction(bus, devfn, false, name);
2029 }
2030 
2031 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
2032 {
2033     int offset = PCI_CONFIG_HEADER_SIZE;
2034     int i;
2035     for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
2036         if (pdev->used[i])
2037             offset = i + 1;
2038         else if (i - offset + 1 == size)
2039             return offset;
2040     }
2041     return 0;
2042 }
2043 
2044 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
2045                                         uint8_t *prev_p)
2046 {
2047     uint8_t next, prev;
2048 
2049     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
2050         return 0;
2051 
2052     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2053          prev = next + PCI_CAP_LIST_NEXT)
2054         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
2055             break;
2056 
2057     if (prev_p)
2058         *prev_p = prev;
2059     return next;
2060 }
2061 
2062 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
2063 {
2064     uint8_t next, prev, found = 0;
2065 
2066     if (!(pdev->used[offset])) {
2067         return 0;
2068     }
2069 
2070     assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
2071 
2072     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
2073          prev = next + PCI_CAP_LIST_NEXT) {
2074         if (next <= offset && next > found) {
2075             found = next;
2076         }
2077     }
2078     return found;
2079 }
2080 
2081 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
2082    This is needed for an option rom which is used for more than one device. */
2083 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
2084 {
2085     uint16_t vendor_id;
2086     uint16_t device_id;
2087     uint16_t rom_vendor_id;
2088     uint16_t rom_device_id;
2089     uint16_t rom_magic;
2090     uint16_t pcir_offset;
2091     uint8_t checksum;
2092 
2093     /* Words in rom data are little endian (like in PCI configuration),
2094        so they can be read / written with pci_get_word / pci_set_word. */
2095 
2096     /* Only a valid rom will be patched. */
2097     rom_magic = pci_get_word(ptr);
2098     if (rom_magic != 0xaa55) {
2099         PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
2100         return;
2101     }
2102     pcir_offset = pci_get_word(ptr + 0x18);
2103     if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
2104         PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
2105         return;
2106     }
2107 
2108     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
2109     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
2110     rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
2111     rom_device_id = pci_get_word(ptr + pcir_offset + 6);
2112 
2113     PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
2114                 vendor_id, device_id, rom_vendor_id, rom_device_id);
2115 
2116     checksum = ptr[6];
2117 
2118     if (vendor_id != rom_vendor_id) {
2119         /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
2120         checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
2121         checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
2122         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2123         ptr[6] = checksum;
2124         pci_set_word(ptr + pcir_offset + 4, vendor_id);
2125     }
2126 
2127     if (device_id != rom_device_id) {
2128         /* Patch device id and checksum (at offset 6 for etherboot roms). */
2129         checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2130         checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2131         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2132         ptr[6] = checksum;
2133         pci_set_word(ptr + pcir_offset + 6, device_id);
2134     }
2135 }
2136 
2137 /* Add an option rom for the device */
2138 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2139                                Error **errp)
2140 {
2141     int size;
2142     char *path;
2143     void *ptr;
2144     char name[32];
2145     const VMStateDescription *vmsd;
2146 
2147     if (!pdev->romfile)
2148         return;
2149     if (strlen(pdev->romfile) == 0)
2150         return;
2151 
2152     if (!pdev->rom_bar) {
2153         /*
2154          * Load rom via fw_cfg instead of creating a rom bar,
2155          * for 0.11 compatibility.
2156          */
2157         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2158 
2159         /*
2160          * Hot-plugged devices can't use the option ROM
2161          * if the rom bar is disabled.
2162          */
2163         if (DEVICE(pdev)->hotplugged) {
2164             error_setg(errp, "Hot-plugged device without ROM bar"
2165                        " can't have an option ROM");
2166             return;
2167         }
2168 
2169         if (class == 0x0300) {
2170             rom_add_vga(pdev->romfile);
2171         } else {
2172             rom_add_option(pdev->romfile, -1);
2173         }
2174         return;
2175     }
2176 
2177     path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2178     if (path == NULL) {
2179         path = g_strdup(pdev->romfile);
2180     }
2181 
2182     size = get_image_size(path);
2183     if (size < 0) {
2184         error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2185         g_free(path);
2186         return;
2187     } else if (size == 0) {
2188         error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2189         g_free(path);
2190         return;
2191     }
2192     size = pow2ceil(size);
2193 
2194     vmsd = qdev_get_vmsd(DEVICE(pdev));
2195 
2196     if (vmsd) {
2197         snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2198     } else {
2199         snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2200     }
2201     pdev->has_rom = true;
2202     memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_fatal);
2203     vmstate_register_ram(&pdev->rom, &pdev->qdev);
2204     ptr = memory_region_get_ram_ptr(&pdev->rom);
2205     load_image(path, ptr);
2206     g_free(path);
2207 
2208     if (is_default_rom) {
2209         /* Only the default rom images will be patched (if needed). */
2210         pci_patch_ids(pdev, ptr, size);
2211     }
2212 
2213     pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2214 }
2215 
2216 static void pci_del_option_rom(PCIDevice *pdev)
2217 {
2218     if (!pdev->has_rom)
2219         return;
2220 
2221     vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2222     pdev->has_rom = false;
2223 }
2224 
2225 /*
2226  * if offset = 0,
2227  * Find and reserve space and add capability to the linked list
2228  * in pci config space
2229  */
2230 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2231                        uint8_t offset, uint8_t size)
2232 {
2233     int ret;
2234     Error *local_err = NULL;
2235 
2236     ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err);
2237     if (local_err) {
2238         assert(ret < 0);
2239         error_report_err(local_err);
2240     } else {
2241         /* success implies a positive offset in config space */
2242         assert(ret > 0);
2243     }
2244     return ret;
2245 }
2246 
2247 int pci_add_capability2(PCIDevice *pdev, uint8_t cap_id,
2248                        uint8_t offset, uint8_t size,
2249                        Error **errp)
2250 {
2251     uint8_t *config;
2252     int i, overlapping_cap;
2253 
2254     if (!offset) {
2255         offset = pci_find_space(pdev, size);
2256         /* out of PCI config space is programming error */
2257         assert(offset);
2258     } else {
2259         /* Verify that capabilities don't overlap.  Note: device assignment
2260          * depends on this check to verify that the device is not broken.
2261          * Should never trigger for emulated devices, but it's helpful
2262          * for debugging these. */
2263         for (i = offset; i < offset + size; i++) {
2264             overlapping_cap = pci_find_capability_at_offset(pdev, i);
2265             if (overlapping_cap) {
2266                 error_setg(errp, "%s:%02x:%02x.%x "
2267                            "Attempt to add PCI capability %x at offset "
2268                            "%x overlaps existing capability %x at offset %x",
2269                            pci_root_bus_path(pdev), pci_bus_num(pdev->bus),
2270                            PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2271                            cap_id, offset, overlapping_cap, i);
2272                 return -EINVAL;
2273             }
2274         }
2275     }
2276 
2277     config = pdev->config + offset;
2278     config[PCI_CAP_LIST_ID] = cap_id;
2279     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2280     pdev->config[PCI_CAPABILITY_LIST] = offset;
2281     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2282     memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2283     /* Make capability read-only by default */
2284     memset(pdev->wmask + offset, 0, size);
2285     /* Check capability by default */
2286     memset(pdev->cmask + offset, 0xFF, size);
2287     return offset;
2288 }
2289 
2290 /* Unlink capability from the pci config space. */
2291 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2292 {
2293     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2294     if (!offset)
2295         return;
2296     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2297     /* Make capability writable again */
2298     memset(pdev->wmask + offset, 0xff, size);
2299     memset(pdev->w1cmask + offset, 0, size);
2300     /* Clear cmask as device-specific registers can't be checked */
2301     memset(pdev->cmask + offset, 0, size);
2302     memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2303 
2304     if (!pdev->config[PCI_CAPABILITY_LIST])
2305         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2306 }
2307 
2308 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2309 {
2310     return pci_find_capability_list(pdev, cap_id, NULL);
2311 }
2312 
2313 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2314 {
2315     PCIDevice *d = (PCIDevice *)dev;
2316     const pci_class_desc *desc;
2317     char ctxt[64];
2318     PCIIORegion *r;
2319     int i, class;
2320 
2321     class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2322     desc = pci_class_descriptions;
2323     while (desc->desc && class != desc->class)
2324         desc++;
2325     if (desc->desc) {
2326         snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2327     } else {
2328         snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2329     }
2330 
2331     monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2332                    "pci id %04x:%04x (sub %04x:%04x)\n",
2333                    indent, "", ctxt, pci_bus_num(d->bus),
2334                    PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2335                    pci_get_word(d->config + PCI_VENDOR_ID),
2336                    pci_get_word(d->config + PCI_DEVICE_ID),
2337                    pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2338                    pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2339     for (i = 0; i < PCI_NUM_REGIONS; i++) {
2340         r = &d->io_regions[i];
2341         if (!r->size)
2342             continue;
2343         monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2344                        " [0x%"FMT_PCIBUS"]\n",
2345                        indent, "",
2346                        i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2347                        r->addr, r->addr + r->size - 1);
2348     }
2349 }
2350 
2351 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2352 {
2353     PCIDevice *d = (PCIDevice *)dev;
2354     const char *name = NULL;
2355     const pci_class_desc *desc =  pci_class_descriptions;
2356     int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2357 
2358     while (desc->desc &&
2359           (class & ~desc->fw_ign_bits) !=
2360           (desc->class & ~desc->fw_ign_bits)) {
2361         desc++;
2362     }
2363 
2364     if (desc->desc) {
2365         name = desc->fw_name;
2366     }
2367 
2368     if (name) {
2369         pstrcpy(buf, len, name);
2370     } else {
2371         snprintf(buf, len, "pci%04x,%04x",
2372                  pci_get_word(d->config + PCI_VENDOR_ID),
2373                  pci_get_word(d->config + PCI_DEVICE_ID));
2374     }
2375 
2376     return buf;
2377 }
2378 
2379 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2380 {
2381     PCIDevice *d = (PCIDevice *)dev;
2382     char path[50], name[33];
2383     int off;
2384 
2385     off = snprintf(path, sizeof(path), "%s@%x",
2386                    pci_dev_fw_name(dev, name, sizeof name),
2387                    PCI_SLOT(d->devfn));
2388     if (PCI_FUNC(d->devfn))
2389         snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2390     return g_strdup(path);
2391 }
2392 
2393 static char *pcibus_get_dev_path(DeviceState *dev)
2394 {
2395     PCIDevice *d = container_of(dev, PCIDevice, qdev);
2396     PCIDevice *t;
2397     int slot_depth;
2398     /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2399      * 00 is added here to make this format compatible with
2400      * domain:Bus:Slot.Func for systems without nested PCI bridges.
2401      * Slot.Function list specifies the slot and function numbers for all
2402      * devices on the path from root to the specific device. */
2403     const char *root_bus_path;
2404     int root_bus_len;
2405     char slot[] = ":SS.F";
2406     int slot_len = sizeof slot - 1 /* For '\0' */;
2407     int path_len;
2408     char *path, *p;
2409     int s;
2410 
2411     root_bus_path = pci_root_bus_path(d);
2412     root_bus_len = strlen(root_bus_path);
2413 
2414     /* Calculate # of slots on path between device and root. */;
2415     slot_depth = 0;
2416     for (t = d; t; t = t->bus->parent_dev) {
2417         ++slot_depth;
2418     }
2419 
2420     path_len = root_bus_len + slot_len * slot_depth;
2421 
2422     /* Allocate memory, fill in the terminating null byte. */
2423     path = g_malloc(path_len + 1 /* For '\0' */);
2424     path[path_len] = '\0';
2425 
2426     memcpy(path, root_bus_path, root_bus_len);
2427 
2428     /* Fill in slot numbers. We walk up from device to root, so need to print
2429      * them in the reverse order, last to first. */
2430     p = path + path_len;
2431     for (t = d; t; t = t->bus->parent_dev) {
2432         p -= slot_len;
2433         s = snprintf(slot, sizeof slot, ":%02x.%x",
2434                      PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2435         assert(s == slot_len);
2436         memcpy(p, slot, slot_len);
2437     }
2438 
2439     return path;
2440 }
2441 
2442 static int pci_qdev_find_recursive(PCIBus *bus,
2443                                    const char *id, PCIDevice **pdev)
2444 {
2445     DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2446     if (!qdev) {
2447         return -ENODEV;
2448     }
2449 
2450     /* roughly check if given qdev is pci device */
2451     if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2452         *pdev = PCI_DEVICE(qdev);
2453         return 0;
2454     }
2455     return -EINVAL;
2456 }
2457 
2458 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2459 {
2460     PCIHostState *host_bridge;
2461     int rc = -ENODEV;
2462 
2463     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2464         int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2465         if (!tmp) {
2466             rc = 0;
2467             break;
2468         }
2469         if (tmp != -ENODEV) {
2470             rc = tmp;
2471         }
2472     }
2473 
2474     return rc;
2475 }
2476 
2477 MemoryRegion *pci_address_space(PCIDevice *dev)
2478 {
2479     return dev->bus->address_space_mem;
2480 }
2481 
2482 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2483 {
2484     return dev->bus->address_space_io;
2485 }
2486 
2487 static void pci_device_class_init(ObjectClass *klass, void *data)
2488 {
2489     DeviceClass *k = DEVICE_CLASS(klass);
2490     PCIDeviceClass *pc = PCI_DEVICE_CLASS(klass);
2491 
2492     k->realize = pci_qdev_realize;
2493     k->unrealize = pci_qdev_unrealize;
2494     k->bus_type = TYPE_PCI_BUS;
2495     k->props = pci_props;
2496     pc->realize = pci_default_realize;
2497 }
2498 
2499 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2500 {
2501     PCIBus *bus = PCI_BUS(dev->bus);
2502     PCIBus *iommu_bus = bus;
2503 
2504     while(iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {
2505         iommu_bus = PCI_BUS(iommu_bus->parent_dev->bus);
2506     }
2507     if (iommu_bus && iommu_bus->iommu_fn) {
2508         return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, dev->devfn);
2509     }
2510     return &address_space_memory;
2511 }
2512 
2513 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2514 {
2515     bus->iommu_fn = fn;
2516     bus->iommu_opaque = opaque;
2517 }
2518 
2519 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2520 {
2521     Range *range = opaque;
2522     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2523     uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2524     int i;
2525 
2526     if (!(cmd & PCI_COMMAND_MEMORY)) {
2527         return;
2528     }
2529 
2530     if (pc->is_bridge) {
2531         pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2532         pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2533 
2534         base = MAX(base, 0x1ULL << 32);
2535 
2536         if (limit >= base) {
2537             Range pref_range;
2538             range_set_bounds(&pref_range, base, limit);
2539             range_extend(range, &pref_range);
2540         }
2541     }
2542     for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2543         PCIIORegion *r = &dev->io_regions[i];
2544         pcibus_t lob, upb;
2545         Range region_range;
2546 
2547         if (!r->size ||
2548             (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2549             !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2550             continue;
2551         }
2552 
2553         lob = pci_bar_address(dev, i, r->type, r->size);
2554         upb = lob + r->size - 1;
2555         if (lob == PCI_BAR_UNMAPPED) {
2556             continue;
2557         }
2558 
2559         lob = MAX(lob, 0x1ULL << 32);
2560 
2561         if (upb >= lob) {
2562             range_set_bounds(&region_range, lob, upb);
2563             range_extend(range, &region_range);
2564         }
2565     }
2566 }
2567 
2568 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2569 {
2570     range_make_empty(range);
2571     pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2572 }
2573 
2574 static bool pcie_has_upstream_port(PCIDevice *dev)
2575 {
2576     PCIDevice *parent_dev = pci_bridge_get_device(dev->bus);
2577 
2578     /* Device associated with an upstream port.
2579      * As there are several types of these, it's easier to check the
2580      * parent device: upstream ports are always connected to
2581      * root or downstream ports.
2582      */
2583     return parent_dev &&
2584         pci_is_express(parent_dev) &&
2585         parent_dev->exp.exp_cap &&
2586         (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||
2587          pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);
2588 }
2589 
2590 PCIDevice *pci_get_function_0(PCIDevice *pci_dev)
2591 {
2592     if(pcie_has_upstream_port(pci_dev)) {
2593         /* With an upstream PCIe port, we only support 1 device at slot 0 */
2594         return pci_dev->bus->devices[0];
2595     } else {
2596         /* Other bus types might support multiple devices at slots 0-31 */
2597         return pci_dev->bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];
2598     }
2599 }
2600 
2601 MSIMessage pci_get_msi_message(PCIDevice *dev, int vector)
2602 {
2603     MSIMessage msg;
2604     if (msix_enabled(dev)) {
2605         msg = msix_get_message(dev, vector);
2606     } else if (msi_enabled(dev)) {
2607         msg = msi_get_message(dev, vector);
2608     } else {
2609         /* Should never happen */
2610         error_report("%s: unknown interrupt type", __func__);
2611         abort();
2612     }
2613     return msg;
2614 }
2615 
2616 static const TypeInfo pci_device_type_info = {
2617     .name = TYPE_PCI_DEVICE,
2618     .parent = TYPE_DEVICE,
2619     .instance_size = sizeof(PCIDevice),
2620     .abstract = true,
2621     .class_size = sizeof(PCIDeviceClass),
2622     .class_init = pci_device_class_init,
2623 };
2624 
2625 static void pci_register_types(void)
2626 {
2627     type_register_static(&pci_bus_info);
2628     type_register_static(&pcie_bus_info);
2629     type_register_static(&pci_device_type_info);
2630 }
2631 
2632 type_init(pci_register_types)
2633