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