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