]> Git Repo - qemu.git/blob - hw/pci.c
QMP: Fix asynchronous events delivery
[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 "monitor.h"
27 #include "net.h"
28 #include "sysemu.h"
29 #include "loader.h"
30
31 //#define DEBUG_PCI
32 #ifdef DEBUG_PCI
33 # define PCI_DPRINTF(format, ...)       printf(format, ## __VA_ARGS__)
34 #else
35 # define PCI_DPRINTF(format, ...)       do { } while (0)
36 #endif
37
38 struct PCIBus {
39     BusState qbus;
40     int devfn_min;
41     pci_set_irq_fn set_irq;
42     pci_map_irq_fn map_irq;
43     pci_hotplug_fn hotplug;
44     void *irq_opaque;
45     PCIDevice *devices[256];
46     PCIDevice *parent_dev;
47     target_phys_addr_t mem_base;
48
49     QLIST_HEAD(, PCIBus) child; /* this will be replaced by qdev later */
50     QLIST_ENTRY(PCIBus) sibling;/* this will be replaced by qdev later */
51
52     /* The bus IRQ state is the logical OR of the connected devices.
53        Keep a count of the number of devices with raised IRQs.  */
54     int nirq;
55     int *irq_count;
56 };
57
58 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
59
60 static struct BusInfo pci_bus_info = {
61     .name       = "PCI",
62     .size       = sizeof(PCIBus),
63     .print_dev  = pcibus_dev_print,
64     .props      = (Property[]) {
65         DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
66         DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
67         DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
68         DEFINE_PROP_END_OF_LIST()
69     }
70 };
71
72 static void pci_update_mappings(PCIDevice *d);
73 static void pci_set_irq(void *opaque, int irq_num, int level);
74 static int pci_add_option_rom(PCIDevice *pdev);
75
76 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
77 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
78
79 struct PCIHostBus {
80     int domain;
81     struct PCIBus *bus;
82     QLIST_ENTRY(PCIHostBus) next;
83 };
84 static QLIST_HEAD(, PCIHostBus) host_buses;
85
86 static const VMStateDescription vmstate_pcibus = {
87     .name = "PCIBUS",
88     .version_id = 1,
89     .minimum_version_id = 1,
90     .minimum_version_id_old = 1,
91     .fields      = (VMStateField []) {
92         VMSTATE_INT32_EQUAL(nirq, PCIBus),
93         VMSTATE_VARRAY_INT32(irq_count, PCIBus, nirq, 0, vmstate_info_int32, int32_t),
94         VMSTATE_END_OF_LIST()
95     }
96 };
97
98 static int pci_bar(PCIDevice *d, int reg)
99 {
100     uint8_t type;
101
102     if (reg != PCI_ROM_SLOT)
103         return PCI_BASE_ADDRESS_0 + reg * 4;
104
105     type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
106     return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
107 }
108
109 static inline int pci_irq_state(PCIDevice *d, int irq_num)
110 {
111         return (d->irq_state >> irq_num) & 0x1;
112 }
113
114 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
115 {
116         d->irq_state &= ~(0x1 << irq_num);
117         d->irq_state |= level << irq_num;
118 }
119
120 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
121 {
122     PCIBus *bus;
123     for (;;) {
124         bus = pci_dev->bus;
125         irq_num = bus->map_irq(pci_dev, irq_num);
126         if (bus->set_irq)
127             break;
128         pci_dev = bus->parent_dev;
129     }
130     bus->irq_count[irq_num] += change;
131     bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
132 }
133
134 /* Update interrupt status bit in config space on interrupt
135  * state change. */
136 static void pci_update_irq_status(PCIDevice *dev)
137 {
138     if (dev->irq_state) {
139         dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
140     } else {
141         dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
142     }
143 }
144
145 static void pci_device_reset(PCIDevice *dev)
146 {
147     int r;
148
149     dev->irq_state = 0;
150     pci_update_irq_status(dev);
151     dev->config[PCI_COMMAND] &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY |
152                                   PCI_COMMAND_MASTER);
153     dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
154     dev->config[PCI_INTERRUPT_LINE] = 0x0;
155     for (r = 0; r < PCI_NUM_REGIONS; ++r) {
156         if (!dev->io_regions[r].size) {
157             continue;
158         }
159         pci_set_long(dev->config + pci_bar(dev, r), dev->io_regions[r].type);
160     }
161     pci_update_mappings(dev);
162 }
163
164 static void pci_bus_reset(void *opaque)
165 {
166     PCIBus *bus = opaque;
167     int i;
168
169     for (i = 0; i < bus->nirq; i++) {
170         bus->irq_count[i] = 0;
171     }
172     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
173         if (bus->devices[i]) {
174             pci_device_reset(bus->devices[i]);
175         }
176     }
177 }
178
179 static void pci_host_bus_register(int domain, PCIBus *bus)
180 {
181     struct PCIHostBus *host;
182     host = qemu_mallocz(sizeof(*host));
183     host->domain = domain;
184     host->bus = bus;
185     QLIST_INSERT_HEAD(&host_buses, host, next);
186 }
187
188 PCIBus *pci_find_root_bus(int domain)
189 {
190     struct PCIHostBus *host;
191
192     QLIST_FOREACH(host, &host_buses, next) {
193         if (host->domain == domain) {
194             return host->bus;
195         }
196     }
197
198     return NULL;
199 }
200
201 void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
202                          const char *name, int devfn_min)
203 {
204     qbus_create_inplace(&bus->qbus, &pci_bus_info, parent, name);
205     bus->devfn_min = devfn_min;
206
207     /* host bridge */
208     QLIST_INIT(&bus->child);
209     pci_host_bus_register(0, bus); /* for now only pci domain 0 is supported */
210
211     vmstate_register(-1, &vmstate_pcibus, bus);
212     qemu_register_reset(pci_bus_reset, bus);
213 }
214
215 PCIBus *pci_bus_new(DeviceState *parent, const char *name, int devfn_min)
216 {
217     PCIBus *bus;
218
219     bus = qemu_mallocz(sizeof(*bus));
220     bus->qbus.qdev_allocated = 1;
221     pci_bus_new_inplace(bus, parent, name, devfn_min);
222     return bus;
223 }
224
225 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
226                   void *irq_opaque, int nirq)
227 {
228     bus->set_irq = set_irq;
229     bus->map_irq = map_irq;
230     bus->irq_opaque = irq_opaque;
231     bus->nirq = nirq;
232     bus->irq_count = qemu_mallocz(nirq * sizeof(bus->irq_count[0]));
233 }
234
235 void pci_bus_hotplug(PCIBus *bus, pci_hotplug_fn hotplug)
236 {
237     bus->qbus.allow_hotplug = 1;
238     bus->hotplug = hotplug;
239 }
240
241 void pci_bus_set_mem_base(PCIBus *bus, target_phys_addr_t base)
242 {
243     bus->mem_base = base;
244 }
245
246 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
247                          pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
248                          void *irq_opaque, int devfn_min, int nirq)
249 {
250     PCIBus *bus;
251
252     bus = pci_bus_new(parent, name, devfn_min);
253     pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
254     return bus;
255 }
256
257 static void pci_register_secondary_bus(PCIBus *parent,
258                                        PCIBus *bus,
259                                        PCIDevice *dev,
260                                        pci_map_irq_fn map_irq,
261                                        const char *name)
262 {
263     qbus_create_inplace(&bus->qbus, &pci_bus_info, &dev->qdev, name);
264     bus->map_irq = map_irq;
265     bus->parent_dev = dev;
266
267     QLIST_INIT(&bus->child);
268     QLIST_INSERT_HEAD(&parent->child, bus, sibling);
269 }
270
271 static void pci_unregister_secondary_bus(PCIBus *bus)
272 {
273     assert(QLIST_EMPTY(&bus->child));
274     QLIST_REMOVE(bus, sibling);
275 }
276
277 int pci_bus_num(PCIBus *s)
278 {
279     if (!s->parent_dev)
280         return 0;       /* pci host bridge */
281     return s->parent_dev->config[PCI_SECONDARY_BUS];
282 }
283
284 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
285 {
286     PCIDevice *s = container_of(pv, PCIDevice, config);
287     uint8_t *config;
288     int i;
289
290     assert(size == pci_config_size(s));
291     config = qemu_malloc(size);
292
293     qemu_get_buffer(f, config, size);
294     for (i = 0; i < size; ++i) {
295         if ((config[i] ^ s->config[i]) & s->cmask[i] & ~s->wmask[i]) {
296             qemu_free(config);
297             return -EINVAL;
298         }
299     }
300     memcpy(s->config, config, size);
301
302     pci_update_mappings(s);
303
304     qemu_free(config);
305     return 0;
306 }
307
308 /* just put buffer */
309 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
310 {
311     const uint8_t **v = pv;
312     assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
313     qemu_put_buffer(f, *v, size);
314 }
315
316 static VMStateInfo vmstate_info_pci_config = {
317     .name = "pci config",
318     .get  = get_pci_config_device,
319     .put  = put_pci_config_device,
320 };
321
322 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
323 {
324     PCIDevice *s = container_of(pv, PCIDevice, config);
325     uint32_t irq_state[PCI_NUM_PINS];
326     int i;
327     for (i = 0; i < PCI_NUM_PINS; ++i) {
328         irq_state[i] = qemu_get_be32(f);
329         if (irq_state[i] != 0x1 && irq_state[i] != 0) {
330             fprintf(stderr, "irq state %d: must be 0 or 1.\n",
331                     irq_state[i]);
332             return -EINVAL;
333         }
334     }
335
336     for (i = 0; i < PCI_NUM_PINS; ++i) {
337         pci_set_irq_state(s, i, irq_state[i]);
338     }
339
340     return 0;
341 }
342
343 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
344 {
345     int i;
346     PCIDevice *s = container_of(pv, PCIDevice, config);
347
348     for (i = 0; i < PCI_NUM_PINS; ++i) {
349         qemu_put_be32(f, pci_irq_state(s, i));
350     }
351 }
352
353 static VMStateInfo vmstate_info_pci_irq_state = {
354     .name = "pci irq state",
355     .get  = get_pci_irq_state,
356     .put  = put_pci_irq_state,
357 };
358
359 const VMStateDescription vmstate_pci_device = {
360     .name = "PCIDevice",
361     .version_id = 2,
362     .minimum_version_id = 1,
363     .minimum_version_id_old = 1,
364     .fields      = (VMStateField []) {
365         VMSTATE_INT32_LE(version_id, PCIDevice),
366         VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
367                                    vmstate_info_pci_config,
368                                    PCI_CONFIG_SPACE_SIZE),
369         VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
370                                    vmstate_info_pci_irq_state,
371                                    PCI_NUM_PINS * sizeof(int32_t)),
372         VMSTATE_END_OF_LIST()
373     }
374 };
375
376 const VMStateDescription vmstate_pcie_device = {
377     .name = "PCIDevice",
378     .version_id = 2,
379     .minimum_version_id = 1,
380     .minimum_version_id_old = 1,
381     .fields      = (VMStateField []) {
382         VMSTATE_INT32_LE(version_id, PCIDevice),
383         VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
384                                    vmstate_info_pci_config,
385                                    PCIE_CONFIG_SPACE_SIZE),
386         VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
387                                    vmstate_info_pci_irq_state,
388                                    PCI_NUM_PINS * sizeof(int32_t)),
389         VMSTATE_END_OF_LIST()
390     }
391 };
392
393 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
394 {
395     return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
396 }
397
398 void pci_device_save(PCIDevice *s, QEMUFile *f)
399 {
400     /* Clear interrupt status bit: it is implicit
401      * in irq_state which we are saving.
402      * This makes us compatible with old devices
403      * which never set or clear this bit. */
404     s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
405     vmstate_save_state(f, pci_get_vmstate(s), s);
406     /* Restore the interrupt status bit. */
407     pci_update_irq_status(s);
408 }
409
410 int pci_device_load(PCIDevice *s, QEMUFile *f)
411 {
412     int ret;
413     ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
414     /* Restore the interrupt status bit. */
415     pci_update_irq_status(s);
416     return ret;
417 }
418
419 static int pci_set_default_subsystem_id(PCIDevice *pci_dev)
420 {
421     uint16_t *id;
422
423     id = (void*)(&pci_dev->config[PCI_SUBSYSTEM_VENDOR_ID]);
424     id[0] = cpu_to_le16(pci_default_sub_vendor_id);
425     id[1] = cpu_to_le16(pci_default_sub_device_id);
426     return 0;
427 }
428
429 /*
430  * Parse [[<domain>:]<bus>:]<slot>, return -1 on error
431  */
432 static int pci_parse_devaddr(const char *addr, int *domp, int *busp, unsigned *slotp)
433 {
434     const char *p;
435     char *e;
436     unsigned long val;
437     unsigned long dom = 0, bus = 0;
438     unsigned slot = 0;
439
440     p = addr;
441     val = strtoul(p, &e, 16);
442     if (e == p)
443         return -1;
444     if (*e == ':') {
445         bus = val;
446         p = e + 1;
447         val = strtoul(p, &e, 16);
448         if (e == p)
449             return -1;
450         if (*e == ':') {
451             dom = bus;
452             bus = val;
453             p = e + 1;
454             val = strtoul(p, &e, 16);
455             if (e == p)
456                 return -1;
457         }
458     }
459
460     if (dom > 0xffff || bus > 0xff || val > 0x1f)
461         return -1;
462
463     slot = val;
464
465     if (*e)
466         return -1;
467
468     /* Note: QEMU doesn't implement domains other than 0 */
469     if (!pci_find_bus(pci_find_root_bus(dom), bus))
470         return -1;
471
472     *domp = dom;
473     *busp = bus;
474     *slotp = slot;
475     return 0;
476 }
477
478 int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
479                      unsigned *slotp)
480 {
481     /* strip legacy tag */
482     if (!strncmp(addr, "pci_addr=", 9)) {
483         addr += 9;
484     }
485     if (pci_parse_devaddr(addr, domp, busp, slotp)) {
486         monitor_printf(mon, "Invalid pci address\n");
487         return -1;
488     }
489     return 0;
490 }
491
492 PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
493 {
494     int dom, bus;
495     unsigned slot;
496
497     if (!devaddr) {
498         *devfnp = -1;
499         return pci_find_bus(pci_find_root_bus(0), 0);
500     }
501
502     if (pci_parse_devaddr(devaddr, &dom, &bus, &slot) < 0) {
503         return NULL;
504     }
505
506     *devfnp = slot << 3;
507     return pci_find_bus(pci_find_root_bus(0), bus);
508 }
509
510 static void pci_init_cmask(PCIDevice *dev)
511 {
512     pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
513     pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
514     dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
515     dev->cmask[PCI_REVISION_ID] = 0xff;
516     dev->cmask[PCI_CLASS_PROG] = 0xff;
517     pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
518     dev->cmask[PCI_HEADER_TYPE] = 0xff;
519     dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
520 }
521
522 static void pci_init_wmask(PCIDevice *dev)
523 {
524     int config_size = pci_config_size(dev);
525
526     dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
527     dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
528     pci_set_word(dev->wmask + PCI_COMMAND,
529                  PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
530                  PCI_COMMAND_INTX_DISABLE);
531
532     memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
533            config_size - PCI_CONFIG_HEADER_SIZE);
534 }
535
536 static void pci_init_wmask_bridge(PCIDevice *d)
537 {
538     /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
539        PCI_SEC_LETENCY_TIMER */
540     memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
541
542     /* base and limit */
543     d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
544     d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
545     pci_set_word(d->wmask + PCI_MEMORY_BASE,
546                  PCI_MEMORY_RANGE_MASK & 0xffff);
547     pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
548                  PCI_MEMORY_RANGE_MASK & 0xffff);
549     pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
550                  PCI_PREF_RANGE_MASK & 0xffff);
551     pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
552                  PCI_PREF_RANGE_MASK & 0xffff);
553
554     /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
555     memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
556
557     pci_set_word(d->wmask + PCI_BRIDGE_CONTROL, 0xffff);
558 }
559
560 static void pci_config_alloc(PCIDevice *pci_dev)
561 {
562     int config_size = pci_config_size(pci_dev);
563
564     pci_dev->config = qemu_mallocz(config_size);
565     pci_dev->cmask = qemu_mallocz(config_size);
566     pci_dev->wmask = qemu_mallocz(config_size);
567     pci_dev->used = qemu_mallocz(config_size);
568 }
569
570 static void pci_config_free(PCIDevice *pci_dev)
571 {
572     qemu_free(pci_dev->config);
573     qemu_free(pci_dev->cmask);
574     qemu_free(pci_dev->wmask);
575     qemu_free(pci_dev->used);
576 }
577
578 /* -1 for devfn means auto assign */
579 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
580                                          const char *name, int devfn,
581                                          PCIConfigReadFunc *config_read,
582                                          PCIConfigWriteFunc *config_write,
583                                          uint8_t header_type)
584 {
585     if (devfn < 0) {
586         for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
587             devfn += 8) {
588             if (!bus->devices[devfn])
589                 goto found;
590         }
591         qemu_error("PCI: no devfn available for %s, all in use\n", name);
592         return NULL;
593     found: ;
594     } else if (bus->devices[devfn]) {
595         qemu_error("PCI: devfn %d not available for %s, in use by %s\n", devfn,
596                  name, bus->devices[devfn]->name);
597         return NULL;
598     }
599     pci_dev->bus = bus;
600     pci_dev->devfn = devfn;
601     pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
602     pci_dev->irq_state = 0;
603     pci_config_alloc(pci_dev);
604
605     header_type &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
606     if (header_type == PCI_HEADER_TYPE_NORMAL) {
607         pci_set_default_subsystem_id(pci_dev);
608     }
609     pci_init_cmask(pci_dev);
610     pci_init_wmask(pci_dev);
611     if (header_type == PCI_HEADER_TYPE_BRIDGE) {
612         pci_init_wmask_bridge(pci_dev);
613     }
614
615     if (!config_read)
616         config_read = pci_default_read_config;
617     if (!config_write)
618         config_write = pci_default_write_config;
619     pci_dev->config_read = config_read;
620     pci_dev->config_write = config_write;
621     bus->devices[devfn] = pci_dev;
622     pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
623     pci_dev->version_id = 2; /* Current pci device vmstate version */
624     return pci_dev;
625 }
626
627 PCIDevice *pci_register_device(PCIBus *bus, const char *name,
628                                int instance_size, int devfn,
629                                PCIConfigReadFunc *config_read,
630                                PCIConfigWriteFunc *config_write)
631 {
632     PCIDevice *pci_dev;
633
634     pci_dev = qemu_mallocz(instance_size);
635     pci_dev = do_pci_register_device(pci_dev, bus, name, devfn,
636                                      config_read, config_write,
637                                      PCI_HEADER_TYPE_NORMAL);
638     if (pci_dev == NULL) {
639         hw_error("PCI: can't register device\n");
640     }
641     return pci_dev;
642 }
643
644 static target_phys_addr_t pci_to_cpu_addr(PCIBus *bus,
645                                           target_phys_addr_t addr)
646 {
647     return addr + bus->mem_base;
648 }
649
650 static void pci_unregister_io_regions(PCIDevice *pci_dev)
651 {
652     PCIIORegion *r;
653     int i;
654
655     for(i = 0; i < PCI_NUM_REGIONS; i++) {
656         r = &pci_dev->io_regions[i];
657         if (!r->size || r->addr == PCI_BAR_UNMAPPED)
658             continue;
659         if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
660             isa_unassign_ioport(r->addr, r->filtered_size);
661         } else {
662             cpu_register_physical_memory(pci_to_cpu_addr(pci_dev->bus,
663                                                          r->addr),
664                                          r->filtered_size,
665                                          IO_MEM_UNASSIGNED);
666         }
667     }
668 }
669
670 static int pci_unregister_device(DeviceState *dev)
671 {
672     PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
673     PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
674     int ret = 0;
675
676     if (info->exit)
677         ret = info->exit(pci_dev);
678     if (ret)
679         return ret;
680
681     pci_unregister_io_regions(pci_dev);
682
683     qemu_free_irqs(pci_dev->irq);
684     pci_dev->bus->devices[pci_dev->devfn] = NULL;
685     pci_config_free(pci_dev);
686     return 0;
687 }
688
689 void pci_register_bar(PCIDevice *pci_dev, int region_num,
690                             pcibus_t size, int type,
691                             PCIMapIORegionFunc *map_func)
692 {
693     PCIIORegion *r;
694     uint32_t addr;
695     pcibus_t wmask;
696
697     if ((unsigned int)region_num >= PCI_NUM_REGIONS)
698         return;
699
700     if (size & (size-1)) {
701         fprintf(stderr, "ERROR: PCI region size must be pow2 "
702                     "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
703         exit(1);
704     }
705
706     r = &pci_dev->io_regions[region_num];
707     r->addr = PCI_BAR_UNMAPPED;
708     r->size = size;
709     r->filtered_size = size;
710     r->type = type;
711     r->map_func = map_func;
712
713     wmask = ~(size - 1);
714     addr = pci_bar(pci_dev, region_num);
715     if (region_num == PCI_ROM_SLOT) {
716         /* ROM enable bit is writeable */
717         wmask |= PCI_ROM_ADDRESS_ENABLE;
718     }
719     pci_set_long(pci_dev->config + addr, type);
720     if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
721         r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
722         pci_set_quad(pci_dev->wmask + addr, wmask);
723         pci_set_quad(pci_dev->cmask + addr, ~0ULL);
724     } else {
725         pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
726         pci_set_long(pci_dev->cmask + addr, 0xffffffff);
727     }
728 }
729
730 static uint32_t pci_config_get_io_base(PCIDevice *d,
731                                        uint32_t base, uint32_t base_upper16)
732 {
733     uint32_t val;
734
735     val = ((uint32_t)d->config[base] & PCI_IO_RANGE_MASK) << 8;
736     if (d->config[base] & PCI_IO_RANGE_TYPE_32) {
737         val |= (uint32_t)pci_get_word(d->config + base_upper16) << 16;
738     }
739     return val;
740 }
741
742 static pcibus_t pci_config_get_memory_base(PCIDevice *d, uint32_t base)
743 {
744     return ((pcibus_t)pci_get_word(d->config + base) & PCI_MEMORY_RANGE_MASK)
745         << 16;
746 }
747
748 static pcibus_t pci_config_get_pref_base(PCIDevice *d,
749                                          uint32_t base, uint32_t upper)
750 {
751     pcibus_t tmp;
752     pcibus_t val;
753
754     tmp = (pcibus_t)pci_get_word(d->config + base);
755     val = (tmp & PCI_PREF_RANGE_MASK) << 16;
756     if (tmp & PCI_PREF_RANGE_TYPE_64) {
757         val |= (pcibus_t)pci_get_long(d->config + upper) << 32;
758     }
759     return val;
760 }
761
762 static pcibus_t pci_bridge_get_base(PCIDevice *bridge, uint8_t type)
763 {
764     pcibus_t base;
765     if (type & PCI_BASE_ADDRESS_SPACE_IO) {
766         base = pci_config_get_io_base(bridge,
767                                       PCI_IO_BASE, PCI_IO_BASE_UPPER16);
768     } else {
769         if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
770             base = pci_config_get_pref_base(
771                 bridge, PCI_PREF_MEMORY_BASE, PCI_PREF_BASE_UPPER32);
772         } else {
773             base = pci_config_get_memory_base(bridge, PCI_MEMORY_BASE);
774         }
775     }
776
777     return base;
778 }
779
780 static pcibus_t pci_bridge_get_limit(PCIDevice *bridge, uint8_t type)
781 {
782     pcibus_t limit;
783     if (type & PCI_BASE_ADDRESS_SPACE_IO) {
784         limit = pci_config_get_io_base(bridge,
785                                       PCI_IO_LIMIT, PCI_IO_LIMIT_UPPER16);
786         limit |= 0xfff;         /* PCI bridge spec 3.2.5.6. */
787     } else {
788         if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
789             limit = pci_config_get_pref_base(
790                 bridge, PCI_PREF_MEMORY_LIMIT, PCI_PREF_LIMIT_UPPER32);
791         } else {
792             limit = pci_config_get_memory_base(bridge, PCI_MEMORY_LIMIT);
793         }
794         limit |= 0xfffff;       /* PCI bridge spec 3.2.5.{1, 8}. */
795     }
796     return limit;
797 }
798
799 static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
800                               uint8_t type)
801 {
802     pcibus_t base = *addr;
803     pcibus_t limit = *addr + *size - 1;
804     PCIDevice *br;
805
806     for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
807         uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
808
809         if (type & PCI_BASE_ADDRESS_SPACE_IO) {
810             if (!(cmd & PCI_COMMAND_IO)) {
811                 goto no_map;
812             }
813         } else {
814             if (!(cmd & PCI_COMMAND_MEMORY)) {
815                 goto no_map;
816             }
817         }
818
819         base = MAX(base, pci_bridge_get_base(br, type));
820         limit = MIN(limit, pci_bridge_get_limit(br, type));
821     }
822
823     if (base > limit) {
824         goto no_map;
825     }
826     *addr = base;
827     *size = limit - base + 1;
828     return;
829 no_map:
830     *addr = PCI_BAR_UNMAPPED;
831     *size = 0;
832 }
833
834 static pcibus_t pci_bar_address(PCIDevice *d,
835                                 int reg, uint8_t type, pcibus_t size)
836 {
837     pcibus_t new_addr, last_addr;
838     int bar = pci_bar(d, reg);
839     uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
840
841     if (type & PCI_BASE_ADDRESS_SPACE_IO) {
842         if (!(cmd & PCI_COMMAND_IO)) {
843             return PCI_BAR_UNMAPPED;
844         }
845         new_addr = pci_get_long(d->config + bar) & ~(size - 1);
846         last_addr = new_addr + size - 1;
847         /* NOTE: we have only 64K ioports on PC */
848         if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
849             return PCI_BAR_UNMAPPED;
850         }
851         return new_addr;
852     }
853
854     if (!(cmd & PCI_COMMAND_MEMORY)) {
855         return PCI_BAR_UNMAPPED;
856     }
857     if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
858         new_addr = pci_get_quad(d->config + bar);
859     } else {
860         new_addr = pci_get_long(d->config + bar);
861     }
862     /* the ROM slot has a specific enable bit */
863     if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
864         return PCI_BAR_UNMAPPED;
865     }
866     new_addr &= ~(size - 1);
867     last_addr = new_addr + size - 1;
868     /* NOTE: we do not support wrapping */
869     /* XXX: as we cannot support really dynamic
870        mappings, we handle specific values as invalid
871        mappings. */
872     if (last_addr <= new_addr || new_addr == 0 ||
873         last_addr == PCI_BAR_UNMAPPED) {
874         return PCI_BAR_UNMAPPED;
875     }
876
877     /* Now pcibus_t is 64bit.
878      * Check if 32 bit BAR wraps around explicitly.
879      * Without this, PC ide doesn't work well.
880      * TODO: remove this work around.
881      */
882     if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
883         return PCI_BAR_UNMAPPED;
884     }
885
886     /*
887      * OS is allowed to set BAR beyond its addressable
888      * bits. For example, 32 bit OS can set 64bit bar
889      * to >4G. Check it. TODO: we might need to support
890      * it in the future for e.g. PAE.
891      */
892     if (last_addr >= TARGET_PHYS_ADDR_MAX) {
893         return PCI_BAR_UNMAPPED;
894     }
895
896     return new_addr;
897 }
898
899 static void pci_update_mappings(PCIDevice *d)
900 {
901     PCIIORegion *r;
902     int i;
903     pcibus_t new_addr, filtered_size;
904
905     for(i = 0; i < PCI_NUM_REGIONS; i++) {
906         r = &d->io_regions[i];
907
908         /* this region isn't registered */
909         if (!r->size)
910             continue;
911
912         new_addr = pci_bar_address(d, i, r->type, r->size);
913
914         /* bridge filtering */
915         filtered_size = r->size;
916         if (new_addr != PCI_BAR_UNMAPPED) {
917             pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
918         }
919
920         /* This bar isn't changed */
921         if (new_addr == r->addr && filtered_size == r->filtered_size)
922             continue;
923
924         /* now do the real mapping */
925         if (r->addr != PCI_BAR_UNMAPPED) {
926             if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
927                 int class;
928                 /* NOTE: specific hack for IDE in PC case:
929                    only one byte must be mapped. */
930                 class = pci_get_word(d->config + PCI_CLASS_DEVICE);
931                 if (class == 0x0101 && r->size == 4) {
932                     isa_unassign_ioport(r->addr + 2, 1);
933                 } else {
934                     isa_unassign_ioport(r->addr, r->filtered_size);
935                 }
936             } else {
937                 cpu_register_physical_memory(pci_to_cpu_addr(d->bus, r->addr),
938                                              r->filtered_size,
939                                              IO_MEM_UNASSIGNED);
940                 qemu_unregister_coalesced_mmio(r->addr, r->filtered_size);
941             }
942         }
943         r->addr = new_addr;
944         r->filtered_size = filtered_size;
945         if (r->addr != PCI_BAR_UNMAPPED) {
946             /*
947              * TODO: currently almost all the map funcions assumes
948              * filtered_size == size and addr & ~(size - 1) == addr.
949              * However with bridge filtering, they aren't always true.
950              * Teach them such cases, such that filtered_size < size and
951              * addr & (size - 1) != 0.
952              */
953             if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
954                 r->map_func(d, i, r->addr, r->filtered_size, r->type);
955             } else {
956                 r->map_func(d, i, pci_to_cpu_addr(d->bus, r->addr),
957                             r->filtered_size, r->type);
958             }
959         }
960     }
961 }
962
963 static inline int pci_irq_disabled(PCIDevice *d)
964 {
965     return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
966 }
967
968 /* Called after interrupt disabled field update in config space,
969  * assert/deassert interrupts if necessary.
970  * Gets original interrupt disable bit value (before update). */
971 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
972 {
973     int i, disabled = pci_irq_disabled(d);
974     if (disabled == was_irq_disabled)
975         return;
976     for (i = 0; i < PCI_NUM_PINS; ++i) {
977         int state = pci_irq_state(d, i);
978         pci_change_irq_level(d, i, disabled ? -state : state);
979     }
980 }
981
982 uint32_t pci_default_read_config(PCIDevice *d,
983                                  uint32_t address, int len)
984 {
985     uint32_t val = 0;
986     assert(len == 1 || len == 2 || len == 4);
987     len = MIN(len, pci_config_size(d) - address);
988     memcpy(&val, d->config + address, len);
989     return le32_to_cpu(val);
990 }
991
992 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
993 {
994     int i, was_irq_disabled = pci_irq_disabled(d);
995     uint32_t config_size = pci_config_size(d);
996
997     for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
998         uint8_t wmask = d->wmask[addr + i];
999         d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1000     }
1001     if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1002         ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1003         ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1004         range_covers_byte(addr, l, PCI_COMMAND))
1005         pci_update_mappings(d);
1006
1007     if (range_covers_byte(addr, l, PCI_COMMAND))
1008         pci_update_irq_disabled(d, was_irq_disabled);
1009 }
1010
1011 /***********************************************************/
1012 /* generic PCI irq support */
1013
1014 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1015 static void pci_set_irq(void *opaque, int irq_num, int level)
1016 {
1017     PCIDevice *pci_dev = opaque;
1018     int change;
1019
1020     change = level - pci_irq_state(pci_dev, irq_num);
1021     if (!change)
1022         return;
1023
1024     pci_set_irq_state(pci_dev, irq_num, level);
1025     pci_update_irq_status(pci_dev);
1026     if (pci_irq_disabled(pci_dev))
1027         return;
1028     pci_change_irq_level(pci_dev, irq_num, change);
1029 }
1030
1031 /***********************************************************/
1032 /* monitor info on PCI */
1033
1034 typedef struct {
1035     uint16_t class;
1036     const char *desc;
1037 } pci_class_desc;
1038
1039 static const pci_class_desc pci_class_descriptions[] =
1040 {
1041     { 0x0100, "SCSI controller"},
1042     { 0x0101, "IDE controller"},
1043     { 0x0102, "Floppy controller"},
1044     { 0x0103, "IPI controller"},
1045     { 0x0104, "RAID controller"},
1046     { 0x0106, "SATA controller"},
1047     { 0x0107, "SAS controller"},
1048     { 0x0180, "Storage controller"},
1049     { 0x0200, "Ethernet controller"},
1050     { 0x0201, "Token Ring controller"},
1051     { 0x0202, "FDDI controller"},
1052     { 0x0203, "ATM controller"},
1053     { 0x0280, "Network controller"},
1054     { 0x0300, "VGA controller"},
1055     { 0x0301, "XGA controller"},
1056     { 0x0302, "3D controller"},
1057     { 0x0380, "Display controller"},
1058     { 0x0400, "Video controller"},
1059     { 0x0401, "Audio controller"},
1060     { 0x0402, "Phone"},
1061     { 0x0480, "Multimedia controller"},
1062     { 0x0500, "RAM controller"},
1063     { 0x0501, "Flash controller"},
1064     { 0x0580, "Memory controller"},
1065     { 0x0600, "Host bridge"},
1066     { 0x0601, "ISA bridge"},
1067     { 0x0602, "EISA bridge"},
1068     { 0x0603, "MC bridge"},
1069     { 0x0604, "PCI bridge"},
1070     { 0x0605, "PCMCIA bridge"},
1071     { 0x0606, "NUBUS bridge"},
1072     { 0x0607, "CARDBUS bridge"},
1073     { 0x0608, "RACEWAY bridge"},
1074     { 0x0680, "Bridge"},
1075     { 0x0c03, "USB controller"},
1076     { 0, NULL}
1077 };
1078
1079 static void pci_info_device(PCIBus *bus, PCIDevice *d)
1080 {
1081     Monitor *mon = cur_mon;
1082     int i, class;
1083     PCIIORegion *r;
1084     const pci_class_desc *desc;
1085
1086     monitor_printf(mon, "  Bus %2d, device %3d, function %d:\n",
1087                    pci_bus_num(d->bus),
1088                    PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));
1089     class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1090     monitor_printf(mon, "    ");
1091     desc = pci_class_descriptions;
1092     while (desc->desc && class != desc->class)
1093         desc++;
1094     if (desc->desc) {
1095         monitor_printf(mon, "%s", desc->desc);
1096     } else {
1097         monitor_printf(mon, "Class %04x", class);
1098     }
1099     monitor_printf(mon, ": PCI device %04x:%04x\n",
1100            pci_get_word(d->config + PCI_VENDOR_ID),
1101            pci_get_word(d->config + PCI_DEVICE_ID));
1102
1103     if (d->config[PCI_INTERRUPT_PIN] != 0) {
1104         monitor_printf(mon, "      IRQ %d.\n",
1105                        d->config[PCI_INTERRUPT_LINE]);
1106     }
1107     if (class == 0x0604) {
1108         uint64_t base;
1109         uint64_t limit;
1110
1111         monitor_printf(mon, "      BUS %d.\n", d->config[0x19]);
1112         monitor_printf(mon, "      secondary bus %d.\n",
1113                        d->config[PCI_SECONDARY_BUS]);
1114         monitor_printf(mon, "      subordinate bus %d.\n",
1115                        d->config[PCI_SUBORDINATE_BUS]);
1116
1117         base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_IO);
1118         limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_IO);
1119         monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1120                        base, limit);
1121
1122         base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY);
1123         limit= pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_MEMORY);
1124         monitor_printf(mon,
1125                        "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1126                        base, limit);
1127
1128         base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY |
1129                                    PCI_BASE_ADDRESS_MEM_PREFETCH);
1130         limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_MEMORY |
1131                                      PCI_BASE_ADDRESS_MEM_PREFETCH);
1132         monitor_printf(mon, "      prefetchable memory range "
1133                        "[0x%08"PRIx64", 0x%08"PRIx64"]\n", base, limit);
1134     }
1135     for(i = 0;i < PCI_NUM_REGIONS; i++) {
1136         r = &d->io_regions[i];
1137         if (r->size != 0) {
1138             monitor_printf(mon, "      BAR%d: ", i);
1139             if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1140                 monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1141                                " [0x%04"FMT_PCIBUS"].\n",
1142                                r->addr, r->addr + r->size - 1);
1143             } else {
1144                 const char *type = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64 ?
1145                     "64 bit" : "32 bit";
1146                 const char *prefetch =
1147                     r->type & PCI_BASE_ADDRESS_MEM_PREFETCH ?
1148                     " prefetchable" : "";
1149
1150                 monitor_printf(mon, "%s%s memory at 0x%08"FMT_PCIBUS
1151                                " [0x%08"FMT_PCIBUS"].\n",
1152                                type, prefetch,
1153                                r->addr, r->addr + r->size - 1);
1154             }
1155         }
1156     }
1157     monitor_printf(mon, "      id \"%s\"\n", d->qdev.id ? d->qdev.id : "");
1158     if (class == 0x0604 && d->config[0x19] != 0) {
1159         pci_for_each_device(bus, d->config[0x19], pci_info_device);
1160     }
1161 }
1162
1163 static void pci_for_each_device_under_bus(PCIBus *bus,
1164                                           void (*fn)(PCIBus *b, PCIDevice *d))
1165 {
1166     PCIDevice *d;
1167     int devfn;
1168
1169     for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1170         d = bus->devices[devfn];
1171         if (d)
1172             fn(bus, d);
1173     }
1174 }
1175
1176 void pci_for_each_device(PCIBus *bus, int bus_num,
1177                          void (*fn)(PCIBus *b, PCIDevice *d))
1178 {
1179     bus = pci_find_bus(bus, bus_num);
1180
1181     if (bus) {
1182         pci_for_each_device_under_bus(bus, fn);
1183     }
1184 }
1185
1186 void pci_info(Monitor *mon)
1187 {
1188     struct PCIHostBus *host;
1189     QLIST_FOREACH(host, &host_buses, next) {
1190         pci_for_each_device(host->bus, 0, pci_info_device);
1191     }
1192 }
1193
1194 static const char * const pci_nic_models[] = {
1195     "ne2k_pci",
1196     "i82551",
1197     "i82557b",
1198     "i82559er",
1199     "rtl8139",
1200     "e1000",
1201     "pcnet",
1202     "virtio",
1203     NULL
1204 };
1205
1206 static const char * const pci_nic_names[] = {
1207     "ne2k_pci",
1208     "i82551",
1209     "i82557b",
1210     "i82559er",
1211     "rtl8139",
1212     "e1000",
1213     "pcnet",
1214     "virtio-net-pci",
1215     NULL
1216 };
1217
1218 /* Initialize a PCI NIC.  */
1219 /* FIXME callers should check for failure, but don't */
1220 PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1221                         const char *default_devaddr)
1222 {
1223     const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1224     PCIBus *bus;
1225     int devfn;
1226     PCIDevice *pci_dev;
1227     DeviceState *dev;
1228     int i;
1229
1230     i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1231     if (i < 0)
1232         return NULL;
1233
1234     bus = pci_get_bus_devfn(&devfn, devaddr);
1235     if (!bus) {
1236         qemu_error("Invalid PCI device address %s for device %s\n",
1237                    devaddr, pci_nic_names[i]);
1238         return NULL;
1239     }
1240
1241     pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1242     dev = &pci_dev->qdev;
1243     if (nd->name)
1244         dev->id = qemu_strdup(nd->name);
1245     qdev_set_nic_properties(dev, nd);
1246     if (qdev_init(dev) < 0)
1247         return NULL;
1248     return pci_dev;
1249 }
1250
1251 PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1252                                const char *default_devaddr)
1253 {
1254     PCIDevice *res;
1255
1256     if (qemu_show_nic_models(nd->model, pci_nic_models))
1257         exit(0);
1258
1259     res = pci_nic_init(nd, default_model, default_devaddr);
1260     if (!res)
1261         exit(1);
1262     return res;
1263 }
1264
1265 typedef struct {
1266     PCIDevice dev;
1267     PCIBus bus;
1268     uint32_t vid;
1269     uint32_t did;
1270 } PCIBridge;
1271
1272
1273 static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1274 {
1275     pci_update_mappings(d);
1276 }
1277
1278 static void pci_bridge_update_mappings(PCIBus *b)
1279 {
1280     PCIBus *child;
1281
1282     pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1283
1284     QLIST_FOREACH(child, &b->child, sibling) {
1285         pci_bridge_update_mappings(child);
1286     }
1287 }
1288
1289 static void pci_bridge_write_config(PCIDevice *d,
1290                              uint32_t address, uint32_t val, int len)
1291 {
1292     pci_default_write_config(d, address, val, len);
1293
1294     if (/* io base/limit */
1295         ranges_overlap(address, len, PCI_IO_BASE, 2) ||
1296
1297         /* memory base/limit, prefetchable base/limit and
1298            io base/limit upper 16 */
1299         ranges_overlap(address, len, PCI_MEMORY_BASE, 20)) {
1300         pci_bridge_update_mappings(d->bus);
1301     }
1302 }
1303
1304 PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1305 {
1306     PCIBus *sec;
1307
1308     if (!bus)
1309         return NULL;
1310
1311     if (pci_bus_num(bus) == bus_num) {
1312         return bus;
1313     }
1314
1315     /* try child bus */
1316     QLIST_FOREACH(sec, &bus->child, sibling) {
1317
1318         if (!bus->parent_dev /* pci host bridge */
1319             || (pci_bus_num(sec) <= bus_num &&
1320                 bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {
1321             return pci_find_bus(sec, bus_num);
1322         }
1323     }
1324
1325     return NULL;
1326 }
1327
1328 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function)
1329 {
1330     bus = pci_find_bus(bus, bus_num);
1331
1332     if (!bus)
1333         return NULL;
1334
1335     return bus->devices[PCI_DEVFN(slot, function)];
1336 }
1337
1338 static int pci_bridge_initfn(PCIDevice *dev)
1339 {
1340     PCIBridge *s = DO_UPCAST(PCIBridge, dev, dev);
1341
1342     pci_config_set_vendor_id(s->dev.config, s->vid);
1343     pci_config_set_device_id(s->dev.config, s->did);
1344
1345     pci_set_word(dev->config + PCI_STATUS,
1346                  PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1347     pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_PCI);
1348     dev->config[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_BRIDGE;
1349     pci_set_word(dev->config + PCI_SEC_STATUS,
1350                  PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1351     return 0;
1352 }
1353
1354 static int pci_bridge_exitfn(PCIDevice *pci_dev)
1355 {
1356     PCIBridge *s = DO_UPCAST(PCIBridge, dev, pci_dev);
1357     PCIBus *bus = &s->bus;
1358     pci_unregister_secondary_bus(bus);
1359     return 0;
1360 }
1361
1362 PCIBus *pci_bridge_init(PCIBus *bus, int devfn, uint16_t vid, uint16_t did,
1363                         pci_map_irq_fn map_irq, const char *name)
1364 {
1365     PCIDevice *dev;
1366     PCIBridge *s;
1367
1368     dev = pci_create(bus, devfn, "pci-bridge");
1369     qdev_prop_set_uint32(&dev->qdev, "vendorid", vid);
1370     qdev_prop_set_uint32(&dev->qdev, "deviceid", did);
1371     qdev_init_nofail(&dev->qdev);
1372
1373     s = DO_UPCAST(PCIBridge, dev, dev);
1374     pci_register_secondary_bus(bus, &s->bus, &s->dev, map_irq, name);
1375     return &s->bus;
1376 }
1377
1378 PCIDevice *pci_bridge_get_device(PCIBus *bus)
1379 {
1380     return bus->parent_dev;
1381 }
1382
1383 static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1384 {
1385     PCIDevice *pci_dev = (PCIDevice *)qdev;
1386     PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1387     PCIBus *bus;
1388     int devfn, rc;
1389
1390     /* initialize cap_present for pci_is_express() and pci_config_size() */
1391     if (info->is_express) {
1392         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1393     }
1394
1395     bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1396     devfn = pci_dev->devfn;
1397     pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
1398                                      info->config_read, info->config_write,
1399                                      info->header_type);
1400     if (pci_dev == NULL)
1401         return -1;
1402     rc = info->init(pci_dev);
1403     if (rc != 0)
1404         return rc;
1405
1406     /* rom loading */
1407     if (pci_dev->romfile == NULL && info->romfile != NULL)
1408         pci_dev->romfile = qemu_strdup(info->romfile);
1409     pci_add_option_rom(pci_dev);
1410
1411     if (qdev->hotplugged)
1412         bus->hotplug(pci_dev, 1);
1413     return 0;
1414 }
1415
1416 static int pci_unplug_device(DeviceState *qdev)
1417 {
1418     PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1419
1420     dev->bus->hotplug(dev, 0);
1421     return 0;
1422 }
1423
1424 void pci_qdev_register(PCIDeviceInfo *info)
1425 {
1426     info->qdev.init = pci_qdev_init;
1427     info->qdev.unplug = pci_unplug_device;
1428     info->qdev.exit = pci_unregister_device;
1429     info->qdev.bus_info = &pci_bus_info;
1430     qdev_register(&info->qdev);
1431 }
1432
1433 void pci_qdev_register_many(PCIDeviceInfo *info)
1434 {
1435     while (info->qdev.name) {
1436         pci_qdev_register(info);
1437         info++;
1438     }
1439 }
1440
1441 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1442 {
1443     DeviceState *dev;
1444
1445     dev = qdev_create(&bus->qbus, name);
1446     qdev_prop_set_uint32(dev, "addr", devfn);
1447     return DO_UPCAST(PCIDevice, qdev, dev);
1448 }
1449
1450 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1451 {
1452     PCIDevice *dev = pci_create(bus, devfn, name);
1453     qdev_init_nofail(&dev->qdev);
1454     return dev;
1455 }
1456
1457 static int pci_find_space(PCIDevice *pdev, uint8_t size)
1458 {
1459     int config_size = pci_config_size(pdev);
1460     int offset = PCI_CONFIG_HEADER_SIZE;
1461     int i;
1462     for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1463         if (pdev->used[i])
1464             offset = i + 1;
1465         else if (i - offset + 1 == size)
1466             return offset;
1467     return 0;
1468 }
1469
1470 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1471                                         uint8_t *prev_p)
1472 {
1473     uint8_t next, prev;
1474
1475     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1476         return 0;
1477
1478     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1479          prev = next + PCI_CAP_LIST_NEXT)
1480         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1481             break;
1482
1483     if (prev_p)
1484         *prev_p = prev;
1485     return next;
1486 }
1487
1488 static void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1489 {
1490     cpu_register_physical_memory(addr, size, pdev->rom_offset);
1491 }
1492
1493 /* Add an option rom for the device */
1494 static int pci_add_option_rom(PCIDevice *pdev)
1495 {
1496     int size;
1497     char *path;
1498     void *ptr;
1499
1500     if (!pdev->romfile)
1501         return 0;
1502     if (strlen(pdev->romfile) == 0)
1503         return 0;
1504
1505     if (!pdev->rom_bar) {
1506         /*
1507          * Load rom via fw_cfg instead of creating a rom bar,
1508          * for 0.11 compatibility.
1509          */
1510         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
1511         if (class == 0x0300) {
1512             rom_add_vga(pdev->romfile);
1513         } else {
1514             rom_add_option(pdev->romfile);
1515         }
1516         return 0;
1517     }
1518
1519     path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1520     if (path == NULL) {
1521         path = qemu_strdup(pdev->romfile);
1522     }
1523
1524     size = get_image_size(path);
1525     if (size < 0) {
1526         qemu_error("%s: failed to find romfile \"%s\"\n", __FUNCTION__,
1527                    pdev->romfile);
1528         return -1;
1529     }
1530     if (size & (size - 1)) {
1531         size = 1 << qemu_fls(size);
1532     }
1533
1534     pdev->rom_offset = qemu_ram_alloc(size);
1535
1536     ptr = qemu_get_ram_ptr(pdev->rom_offset);
1537     load_image(path, ptr);
1538     qemu_free(path);
1539
1540     pci_register_bar(pdev, PCI_ROM_SLOT, size,
1541                      0, pci_map_option_rom);
1542
1543     return 0;
1544 }
1545
1546 /* Reserve space and add capability to the linked list in pci config space */
1547 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1548 {
1549     uint8_t offset = pci_find_space(pdev, size);
1550     uint8_t *config = pdev->config + offset;
1551     if (!offset)
1552         return -ENOSPC;
1553     config[PCI_CAP_LIST_ID] = cap_id;
1554     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1555     pdev->config[PCI_CAPABILITY_LIST] = offset;
1556     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1557     memset(pdev->used + offset, 0xFF, size);
1558     /* Make capability read-only by default */
1559     memset(pdev->wmask + offset, 0, size);
1560     /* Check capability by default */
1561     memset(pdev->cmask + offset, 0xFF, size);
1562     return offset;
1563 }
1564
1565 /* Unlink capability from the pci config space. */
1566 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1567 {
1568     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
1569     if (!offset)
1570         return;
1571     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
1572     /* Make capability writeable again */
1573     memset(pdev->wmask + offset, 0xff, size);
1574     /* Clear cmask as device-specific registers can't be checked */
1575     memset(pdev->cmask + offset, 0, size);
1576     memset(pdev->used + offset, 0, size);
1577
1578     if (!pdev->config[PCI_CAPABILITY_LIST])
1579         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
1580 }
1581
1582 /* Reserve space for capability at a known offset (to call after load). */
1583 void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
1584 {
1585     memset(pdev->used + offset, 0xff, size);
1586 }
1587
1588 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
1589 {
1590     return pci_find_capability_list(pdev, cap_id, NULL);
1591 }
1592
1593 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
1594 {
1595     PCIDevice *d = (PCIDevice *)dev;
1596     const pci_class_desc *desc;
1597     char ctxt[64];
1598     PCIIORegion *r;
1599     int i, class;
1600
1601     class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1602     desc = pci_class_descriptions;
1603     while (desc->desc && class != desc->class)
1604         desc++;
1605     if (desc->desc) {
1606         snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
1607     } else {
1608         snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
1609     }
1610
1611     monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
1612                    "pci id %04x:%04x (sub %04x:%04x)\n",
1613                    indent, "", ctxt,
1614                    d->config[PCI_SECONDARY_BUS],
1615                    PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
1616                    pci_get_word(d->config + PCI_VENDOR_ID),
1617                    pci_get_word(d->config + PCI_DEVICE_ID),
1618                    pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
1619                    pci_get_word(d->config + PCI_SUBSYSTEM_ID));
1620     for (i = 0; i < PCI_NUM_REGIONS; i++) {
1621         r = &d->io_regions[i];
1622         if (!r->size)
1623             continue;
1624         monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
1625                        " [0x%"FMT_PCIBUS"]\n",
1626                        indent, "",
1627                        i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
1628                        r->addr, r->addr + r->size - 1);
1629     }
1630 }
1631
1632 static PCIDeviceInfo bridge_info = {
1633     .qdev.name    = "pci-bridge",
1634     .qdev.size    = sizeof(PCIBridge),
1635     .init         = pci_bridge_initfn,
1636     .exit         = pci_bridge_exitfn,
1637     .config_write = pci_bridge_write_config,
1638     .qdev.props   = (Property[]) {
1639         DEFINE_PROP_HEX32("vendorid", PCIBridge, vid, 0),
1640         DEFINE_PROP_HEX32("deviceid", PCIBridge, did, 0),
1641         DEFINE_PROP_END_OF_LIST(),
1642     }
1643 };
1644
1645 static void pci_register_devices(void)
1646 {
1647     pci_qdev_register(&bridge_info);
1648 }
1649
1650 device_init(pci_register_devices)
This page took 0.122474 seconds and 4 git commands to generate.