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