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