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