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