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