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