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