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