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