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