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