Add qemu 2.4.0
[kvmfornfv.git] / qemu / hw / pci / 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/hw.h"
25 #include "hw/pci/pci.h"
26 #include "hw/pci/pci_bridge.h"
27 #include "hw/pci/pci_bus.h"
28 #include "hw/pci/pci_host.h"
29 #include "monitor/monitor.h"
30 #include "net/net.h"
31 #include "sysemu/sysemu.h"
32 #include "hw/loader.h"
33 #include "qemu/error-report.h"
34 #include "qemu/range.h"
35 #include "qmp-commands.h"
36 #include "trace.h"
37 #include "hw/pci/msi.h"
38 #include "hw/pci/msix.h"
39 #include "exec/address-spaces.h"
40 #include "hw/hotplug.h"
41
42 //#define DEBUG_PCI
43 #ifdef DEBUG_PCI
44 # define PCI_DPRINTF(format, ...)       printf(format, ## __VA_ARGS__)
45 #else
46 # define PCI_DPRINTF(format, ...)       do { } while (0)
47 #endif
48
49 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
50 static char *pcibus_get_dev_path(DeviceState *dev);
51 static char *pcibus_get_fw_dev_path(DeviceState *dev);
52 static void pcibus_reset(BusState *qbus);
53
54 static Property pci_props[] = {
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 static const VMStateDescription vmstate_pcibus = {
66     .name = "PCIBUS",
67     .version_id = 1,
68     .minimum_version_id = 1,
69     .fields = (VMStateField[]) {
70         VMSTATE_INT32_EQUAL(nirq, PCIBus),
71         VMSTATE_VARRAY_INT32(irq_count, PCIBus,
72                              nirq, 0, vmstate_info_int32,
73                              int32_t),
74         VMSTATE_END_OF_LIST()
75     }
76 };
77
78 static void pci_bus_realize(BusState *qbus, Error **errp)
79 {
80     PCIBus *bus = PCI_BUS(qbus);
81
82     vmstate_register(NULL, -1, &vmstate_pcibus, bus);
83 }
84
85 static void pci_bus_unrealize(BusState *qbus, Error **errp)
86 {
87     PCIBus *bus = PCI_BUS(qbus);
88
89     vmstate_unregister(NULL, &vmstate_pcibus, bus);
90 }
91
92 static bool pcibus_is_root(PCIBus *bus)
93 {
94     return !bus->parent_dev;
95 }
96
97 static int pcibus_num(PCIBus *bus)
98 {
99     if (pcibus_is_root(bus)) {
100         return 0; /* pci host bridge */
101     }
102     return bus->parent_dev->config[PCI_SECONDARY_BUS];
103 }
104
105 static uint16_t pcibus_numa_node(PCIBus *bus)
106 {
107     return NUMA_NODE_UNASSIGNED;
108 }
109
110 static void pci_bus_class_init(ObjectClass *klass, void *data)
111 {
112     BusClass *k = BUS_CLASS(klass);
113     PCIBusClass *pbc = PCI_BUS_CLASS(klass);
114
115     k->print_dev = pcibus_dev_print;
116     k->get_dev_path = pcibus_get_dev_path;
117     k->get_fw_dev_path = pcibus_get_fw_dev_path;
118     k->realize = pci_bus_realize;
119     k->unrealize = pci_bus_unrealize;
120     k->reset = pcibus_reset;
121
122     pbc->is_root = pcibus_is_root;
123     pbc->bus_num = pcibus_num;
124     pbc->numa_node = pcibus_numa_node;
125 }
126
127 static const TypeInfo pci_bus_info = {
128     .name = TYPE_PCI_BUS,
129     .parent = TYPE_BUS,
130     .instance_size = sizeof(PCIBus),
131     .class_size = sizeof(PCIBusClass),
132     .class_init = pci_bus_class_init,
133 };
134
135 static const TypeInfo pcie_bus_info = {
136     .name = TYPE_PCIE_BUS,
137     .parent = TYPE_PCI_BUS,
138 };
139
140 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num);
141 static void pci_update_mappings(PCIDevice *d);
142 static void pci_irq_handler(void *opaque, int irq_num, int level);
143 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom, Error **);
144 static void pci_del_option_rom(PCIDevice *pdev);
145
146 static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
147 static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
148
149 static QLIST_HEAD(, PCIHostState) pci_host_bridges;
150
151 int pci_bar(PCIDevice *d, int reg)
152 {
153     uint8_t type;
154
155     if (reg != PCI_ROM_SLOT)
156         return PCI_BASE_ADDRESS_0 + reg * 4;
157
158     type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
159     return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
160 }
161
162 static inline int pci_irq_state(PCIDevice *d, int irq_num)
163 {
164         return (d->irq_state >> irq_num) & 0x1;
165 }
166
167 static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
168 {
169         d->irq_state &= ~(0x1 << irq_num);
170         d->irq_state |= level << irq_num;
171 }
172
173 static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
174 {
175     PCIBus *bus;
176     for (;;) {
177         bus = pci_dev->bus;
178         irq_num = bus->map_irq(pci_dev, irq_num);
179         if (bus->set_irq)
180             break;
181         pci_dev = bus->parent_dev;
182     }
183     bus->irq_count[irq_num] += change;
184     bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
185 }
186
187 int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
188 {
189     assert(irq_num >= 0);
190     assert(irq_num < bus->nirq);
191     return !!bus->irq_count[irq_num];
192 }
193
194 /* Update interrupt status bit in config space on interrupt
195  * state change. */
196 static void pci_update_irq_status(PCIDevice *dev)
197 {
198     if (dev->irq_state) {
199         dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
200     } else {
201         dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
202     }
203 }
204
205 void pci_device_deassert_intx(PCIDevice *dev)
206 {
207     int i;
208     for (i = 0; i < PCI_NUM_PINS; ++i) {
209         pci_irq_handler(dev, i, 0);
210     }
211 }
212
213 static void pci_do_device_reset(PCIDevice *dev)
214 {
215     int r;
216
217     pci_device_deassert_intx(dev);
218     assert(dev->irq_state == 0);
219
220     /* Clear all writable bits */
221     pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
222                                  pci_get_word(dev->wmask + PCI_COMMAND) |
223                                  pci_get_word(dev->w1cmask + PCI_COMMAND));
224     pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
225                                  pci_get_word(dev->wmask + PCI_STATUS) |
226                                  pci_get_word(dev->w1cmask + PCI_STATUS));
227     dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
228     dev->config[PCI_INTERRUPT_LINE] = 0x0;
229     for (r = 0; r < PCI_NUM_REGIONS; ++r) {
230         PCIIORegion *region = &dev->io_regions[r];
231         if (!region->size) {
232             continue;
233         }
234
235         if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
236             region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
237             pci_set_quad(dev->config + pci_bar(dev, r), region->type);
238         } else {
239             pci_set_long(dev->config + pci_bar(dev, r), region->type);
240         }
241     }
242     pci_update_mappings(dev);
243
244     msi_reset(dev);
245     msix_reset(dev);
246 }
247
248 /*
249  * This function is called on #RST and FLR.
250  * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
251  */
252 void pci_device_reset(PCIDevice *dev)
253 {
254     qdev_reset_all(&dev->qdev);
255     pci_do_device_reset(dev);
256 }
257
258 /*
259  * Trigger pci bus reset under a given bus.
260  * Called via qbus_reset_all on RST# assert, after the devices
261  * have been reset qdev_reset_all-ed already.
262  */
263 static void pcibus_reset(BusState *qbus)
264 {
265     PCIBus *bus = DO_UPCAST(PCIBus, qbus, qbus);
266     int i;
267
268     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
269         if (bus->devices[i]) {
270             pci_do_device_reset(bus->devices[i]);
271         }
272     }
273
274     for (i = 0; i < bus->nirq; i++) {
275         assert(bus->irq_count[i] == 0);
276     }
277 }
278
279 static void pci_host_bus_register(PCIBus *bus, DeviceState *parent)
280 {
281     PCIHostState *host_bridge = PCI_HOST_BRIDGE(parent);
282
283     QLIST_INSERT_HEAD(&pci_host_bridges, host_bridge, next);
284 }
285
286 PCIBus *pci_find_primary_bus(void)
287 {
288     PCIBus *primary_bus = NULL;
289     PCIHostState *host;
290
291     QLIST_FOREACH(host, &pci_host_bridges, next) {
292         if (primary_bus) {
293             /* We have multiple root buses, refuse to select a primary */
294             return NULL;
295         }
296         primary_bus = host->bus;
297     }
298
299     return primary_bus;
300 }
301
302 PCIBus *pci_device_root_bus(const PCIDevice *d)
303 {
304     PCIBus *bus = d->bus;
305
306     while (!pci_bus_is_root(bus)) {
307         d = bus->parent_dev;
308         assert(d != NULL);
309
310         bus = d->bus;
311     }
312
313     return bus;
314 }
315
316 const char *pci_root_bus_path(PCIDevice *dev)
317 {
318     PCIBus *rootbus = pci_device_root_bus(dev);
319     PCIHostState *host_bridge = PCI_HOST_BRIDGE(rootbus->qbus.parent);
320     PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_GET_CLASS(host_bridge);
321
322     assert(host_bridge->bus == rootbus);
323
324     if (hc->root_bus_path) {
325         return (*hc->root_bus_path)(host_bridge, rootbus);
326     }
327
328     return rootbus->qbus.name;
329 }
330
331 static void pci_bus_init(PCIBus *bus, DeviceState *parent,
332                          const char *name,
333                          MemoryRegion *address_space_mem,
334                          MemoryRegion *address_space_io,
335                          uint8_t devfn_min)
336 {
337     assert(PCI_FUNC(devfn_min) == 0);
338     bus->devfn_min = devfn_min;
339     bus->address_space_mem = address_space_mem;
340     bus->address_space_io = address_space_io;
341
342     /* host bridge */
343     QLIST_INIT(&bus->child);
344
345     pci_host_bus_register(bus, parent);
346 }
347
348 bool pci_bus_is_express(PCIBus *bus)
349 {
350     return object_dynamic_cast(OBJECT(bus), TYPE_PCIE_BUS);
351 }
352
353 bool pci_bus_is_root(PCIBus *bus)
354 {
355     return PCI_BUS_GET_CLASS(bus)->is_root(bus);
356 }
357
358 void pci_bus_new_inplace(PCIBus *bus, size_t bus_size, DeviceState *parent,
359                          const char *name,
360                          MemoryRegion *address_space_mem,
361                          MemoryRegion *address_space_io,
362                          uint8_t devfn_min, const char *typename)
363 {
364     qbus_create_inplace(bus, bus_size, typename, parent, name);
365     pci_bus_init(bus, parent, name, address_space_mem,
366                  address_space_io, devfn_min);
367 }
368
369 PCIBus *pci_bus_new(DeviceState *parent, const char *name,
370                     MemoryRegion *address_space_mem,
371                     MemoryRegion *address_space_io,
372                     uint8_t devfn_min, const char *typename)
373 {
374     PCIBus *bus;
375
376     bus = PCI_BUS(qbus_create(typename, parent, name));
377     pci_bus_init(bus, parent, name, address_space_mem,
378                  address_space_io, devfn_min);
379     return bus;
380 }
381
382 void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
383                   void *irq_opaque, int nirq)
384 {
385     bus->set_irq = set_irq;
386     bus->map_irq = map_irq;
387     bus->irq_opaque = irq_opaque;
388     bus->nirq = nirq;
389     bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
390 }
391
392 PCIBus *pci_register_bus(DeviceState *parent, const char *name,
393                          pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
394                          void *irq_opaque,
395                          MemoryRegion *address_space_mem,
396                          MemoryRegion *address_space_io,
397                          uint8_t devfn_min, int nirq, const char *typename)
398 {
399     PCIBus *bus;
400
401     bus = pci_bus_new(parent, name, address_space_mem,
402                       address_space_io, devfn_min, typename);
403     pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
404     return bus;
405 }
406
407 int pci_bus_num(PCIBus *s)
408 {
409     return PCI_BUS_GET_CLASS(s)->bus_num(s);
410 }
411
412 int pci_bus_numa_node(PCIBus *bus)
413 {
414     return PCI_BUS_GET_CLASS(bus)->numa_node(bus);
415 }
416
417 static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
418 {
419     PCIDevice *s = container_of(pv, PCIDevice, config);
420     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(s);
421     uint8_t *config;
422     int i;
423
424     assert(size == pci_config_size(s));
425     config = g_malloc(size);
426
427     qemu_get_buffer(f, config, size);
428     for (i = 0; i < size; ++i) {
429         if ((config[i] ^ s->config[i]) &
430             s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
431             error_report("%s: Bad config data: i=0x%x read: %x device: %x "
432                          "cmask: %x wmask: %x w1cmask:%x", __func__,
433                          i, config[i], s->config[i],
434                          s->cmask[i], s->wmask[i], s->w1cmask[i]);
435             g_free(config);
436             return -EINVAL;
437         }
438     }
439     memcpy(s->config, config, size);
440
441     pci_update_mappings(s);
442     if (pc->is_bridge) {
443         PCIBridge *b = PCI_BRIDGE(s);
444         pci_bridge_update_mappings(b);
445     }
446
447     memory_region_set_enabled(&s->bus_master_enable_region,
448                               pci_get_word(s->config + PCI_COMMAND)
449                               & PCI_COMMAND_MASTER);
450
451     g_free(config);
452     return 0;
453 }
454
455 /* just put buffer */
456 static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
457 {
458     const uint8_t **v = pv;
459     assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
460     qemu_put_buffer(f, *v, size);
461 }
462
463 static VMStateInfo vmstate_info_pci_config = {
464     .name = "pci config",
465     .get  = get_pci_config_device,
466     .put  = put_pci_config_device,
467 };
468
469 static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
470 {
471     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
472     uint32_t irq_state[PCI_NUM_PINS];
473     int i;
474     for (i = 0; i < PCI_NUM_PINS; ++i) {
475         irq_state[i] = qemu_get_be32(f);
476         if (irq_state[i] != 0x1 && irq_state[i] != 0) {
477             fprintf(stderr, "irq state %d: must be 0 or 1.\n",
478                     irq_state[i]);
479             return -EINVAL;
480         }
481     }
482
483     for (i = 0; i < PCI_NUM_PINS; ++i) {
484         pci_set_irq_state(s, i, irq_state[i]);
485     }
486
487     return 0;
488 }
489
490 static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
491 {
492     int i;
493     PCIDevice *s = container_of(pv, PCIDevice, irq_state);
494
495     for (i = 0; i < PCI_NUM_PINS; ++i) {
496         qemu_put_be32(f, pci_irq_state(s, i));
497     }
498 }
499
500 static VMStateInfo vmstate_info_pci_irq_state = {
501     .name = "pci irq state",
502     .get  = get_pci_irq_state,
503     .put  = put_pci_irq_state,
504 };
505
506 const VMStateDescription vmstate_pci_device = {
507     .name = "PCIDevice",
508     .version_id = 2,
509     .minimum_version_id = 1,
510     .fields = (VMStateField[]) {
511         VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
512         VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
513                                    vmstate_info_pci_config,
514                                    PCI_CONFIG_SPACE_SIZE),
515         VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
516                                    vmstate_info_pci_irq_state,
517                                    PCI_NUM_PINS * sizeof(int32_t)),
518         VMSTATE_END_OF_LIST()
519     }
520 };
521
522 const VMStateDescription vmstate_pcie_device = {
523     .name = "PCIEDevice",
524     .version_id = 2,
525     .minimum_version_id = 1,
526     .fields = (VMStateField[]) {
527         VMSTATE_INT32_POSITIVE_LE(version_id, PCIDevice),
528         VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
529                                    vmstate_info_pci_config,
530                                    PCIE_CONFIG_SPACE_SIZE),
531         VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
532                                    vmstate_info_pci_irq_state,
533                                    PCI_NUM_PINS * sizeof(int32_t)),
534         VMSTATE_END_OF_LIST()
535     }
536 };
537
538 static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
539 {
540     return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
541 }
542
543 void pci_device_save(PCIDevice *s, QEMUFile *f)
544 {
545     /* Clear interrupt status bit: it is implicit
546      * in irq_state which we are saving.
547      * This makes us compatible with old devices
548      * which never set or clear this bit. */
549     s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
550     vmstate_save_state(f, pci_get_vmstate(s), s, NULL);
551     /* Restore the interrupt status bit. */
552     pci_update_irq_status(s);
553 }
554
555 int pci_device_load(PCIDevice *s, QEMUFile *f)
556 {
557     int ret;
558     ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
559     /* Restore the interrupt status bit. */
560     pci_update_irq_status(s);
561     return ret;
562 }
563
564 static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
565 {
566     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
567                  pci_default_sub_vendor_id);
568     pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
569                  pci_default_sub_device_id);
570 }
571
572 /*
573  * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
574  *       [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
575  */
576 static int pci_parse_devaddr(const char *addr, int *domp, int *busp,
577                              unsigned int *slotp, unsigned int *funcp)
578 {
579     const char *p;
580     char *e;
581     unsigned long val;
582     unsigned long dom = 0, bus = 0;
583     unsigned int slot = 0;
584     unsigned int func = 0;
585
586     p = addr;
587     val = strtoul(p, &e, 16);
588     if (e == p)
589         return -1;
590     if (*e == ':') {
591         bus = val;
592         p = e + 1;
593         val = strtoul(p, &e, 16);
594         if (e == p)
595             return -1;
596         if (*e == ':') {
597             dom = bus;
598             bus = val;
599             p = e + 1;
600             val = strtoul(p, &e, 16);
601             if (e == p)
602                 return -1;
603         }
604     }
605
606     slot = val;
607
608     if (funcp != NULL) {
609         if (*e != '.')
610             return -1;
611
612         p = e + 1;
613         val = strtoul(p, &e, 16);
614         if (e == p)
615             return -1;
616
617         func = val;
618     }
619
620     /* if funcp == NULL func is 0 */
621     if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
622         return -1;
623
624     if (*e)
625         return -1;
626
627     *domp = dom;
628     *busp = bus;
629     *slotp = slot;
630     if (funcp != NULL)
631         *funcp = func;
632     return 0;
633 }
634
635 static PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root,
636                                  const char *devaddr)
637 {
638     int dom, bus;
639     unsigned slot;
640
641     if (!root) {
642         fprintf(stderr, "No primary PCI bus\n");
643         return NULL;
644     }
645
646     assert(!root->parent_dev);
647
648     if (!devaddr) {
649         *devfnp = -1;
650         return pci_find_bus_nr(root, 0);
651     }
652
653     if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
654         return NULL;
655     }
656
657     if (dom != 0) {
658         fprintf(stderr, "No support for non-zero PCI domains\n");
659         return NULL;
660     }
661
662     *devfnp = PCI_DEVFN(slot, 0);
663     return pci_find_bus_nr(root, bus);
664 }
665
666 static void pci_init_cmask(PCIDevice *dev)
667 {
668     pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
669     pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
670     dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
671     dev->cmask[PCI_REVISION_ID] = 0xff;
672     dev->cmask[PCI_CLASS_PROG] = 0xff;
673     pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
674     dev->cmask[PCI_HEADER_TYPE] = 0xff;
675     dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
676 }
677
678 static void pci_init_wmask(PCIDevice *dev)
679 {
680     int config_size = pci_config_size(dev);
681
682     dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
683     dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
684     pci_set_word(dev->wmask + PCI_COMMAND,
685                  PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
686                  PCI_COMMAND_INTX_DISABLE);
687     if (dev->cap_present & QEMU_PCI_CAP_SERR) {
688         pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
689     }
690
691     memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
692            config_size - PCI_CONFIG_HEADER_SIZE);
693 }
694
695 static void pci_init_w1cmask(PCIDevice *dev)
696 {
697     /*
698      * Note: It's okay to set w1cmask even for readonly bits as
699      * long as their value is hardwired to 0.
700      */
701     pci_set_word(dev->w1cmask + PCI_STATUS,
702                  PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
703                  PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
704                  PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
705 }
706
707 static void pci_init_mask_bridge(PCIDevice *d)
708 {
709     /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
710        PCI_SEC_LETENCY_TIMER */
711     memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
712
713     /* base and limit */
714     d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
715     d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
716     pci_set_word(d->wmask + PCI_MEMORY_BASE,
717                  PCI_MEMORY_RANGE_MASK & 0xffff);
718     pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
719                  PCI_MEMORY_RANGE_MASK & 0xffff);
720     pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
721                  PCI_PREF_RANGE_MASK & 0xffff);
722     pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
723                  PCI_PREF_RANGE_MASK & 0xffff);
724
725     /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
726     memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
727
728     /* Supported memory and i/o types */
729     d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;
730     d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;
731     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,
732                                PCI_PREF_RANGE_TYPE_64);
733     pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,
734                                PCI_PREF_RANGE_TYPE_64);
735
736     /*
737      * TODO: Bridges default to 10-bit VGA decoding but we currently only
738      * implement 16-bit decoding (no alias support).
739      */
740     pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
741                  PCI_BRIDGE_CTL_PARITY |
742                  PCI_BRIDGE_CTL_SERR |
743                  PCI_BRIDGE_CTL_ISA |
744                  PCI_BRIDGE_CTL_VGA |
745                  PCI_BRIDGE_CTL_VGA_16BIT |
746                  PCI_BRIDGE_CTL_MASTER_ABORT |
747                  PCI_BRIDGE_CTL_BUS_RESET |
748                  PCI_BRIDGE_CTL_FAST_BACK |
749                  PCI_BRIDGE_CTL_DISCARD |
750                  PCI_BRIDGE_CTL_SEC_DISCARD |
751                  PCI_BRIDGE_CTL_DISCARD_SERR);
752     /* Below does not do anything as we never set this bit, put here for
753      * completeness. */
754     pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
755                  PCI_BRIDGE_CTL_DISCARD_STATUS);
756     d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;
757     d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;
758     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,
759                                PCI_PREF_RANGE_TYPE_MASK);
760     pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,
761                                PCI_PREF_RANGE_TYPE_MASK);
762 }
763
764 static void pci_init_multifunction(PCIBus *bus, PCIDevice *dev, Error **errp)
765 {
766     uint8_t slot = PCI_SLOT(dev->devfn);
767     uint8_t func;
768
769     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
770         dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
771     }
772
773     /*
774      * multifunction bit is interpreted in two ways as follows.
775      *   - all functions must set the bit to 1.
776      *     Example: Intel X53
777      *   - function 0 must set the bit, but the rest function (> 0)
778      *     is allowed to leave the bit to 0.
779      *     Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
780      *
781      * So OS (at least Linux) checks the bit of only function 0,
782      * and doesn't see the bit of function > 0.
783      *
784      * The below check allows both interpretation.
785      */
786     if (PCI_FUNC(dev->devfn)) {
787         PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
788         if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
789             /* function 0 should set multifunction bit */
790             error_setg(errp, "PCI: single function device can't be populated "
791                        "in function %x.%x", slot, PCI_FUNC(dev->devfn));
792             return;
793         }
794         return;
795     }
796
797     if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
798         return;
799     }
800     /* function 0 indicates single function, so function > 0 must be NULL */
801     for (func = 1; func < PCI_FUNC_MAX; ++func) {
802         if (bus->devices[PCI_DEVFN(slot, func)]) {
803             error_setg(errp, "PCI: %x.0 indicates single function, "
804                        "but %x.%x is already populated.",
805                        slot, slot, func);
806             return;
807         }
808     }
809 }
810
811 static void pci_config_alloc(PCIDevice *pci_dev)
812 {
813     int config_size = pci_config_size(pci_dev);
814
815     pci_dev->config = g_malloc0(config_size);
816     pci_dev->cmask = g_malloc0(config_size);
817     pci_dev->wmask = g_malloc0(config_size);
818     pci_dev->w1cmask = g_malloc0(config_size);
819     pci_dev->used = g_malloc0(config_size);
820 }
821
822 static void pci_config_free(PCIDevice *pci_dev)
823 {
824     g_free(pci_dev->config);
825     g_free(pci_dev->cmask);
826     g_free(pci_dev->wmask);
827     g_free(pci_dev->w1cmask);
828     g_free(pci_dev->used);
829 }
830
831 static void do_pci_unregister_device(PCIDevice *pci_dev)
832 {
833     pci_dev->bus->devices[pci_dev->devfn] = NULL;
834     pci_config_free(pci_dev);
835
836     address_space_destroy(&pci_dev->bus_master_as);
837 }
838
839 /* -1 for devfn means auto assign */
840 static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
841                                          const char *name, int devfn,
842                                          Error **errp)
843 {
844     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
845     PCIConfigReadFunc *config_read = pc->config_read;
846     PCIConfigWriteFunc *config_write = pc->config_write;
847     Error *local_err = NULL;
848     AddressSpace *dma_as;
849
850     if (devfn < 0) {
851         for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
852             devfn += PCI_FUNC_MAX) {
853             if (!bus->devices[devfn])
854                 goto found;
855         }
856         error_setg(errp, "PCI: no slot/function available for %s, all in use",
857                    name);
858         return NULL;
859     found: ;
860     } else if (bus->devices[devfn]) {
861         error_setg(errp, "PCI: slot %d function %d not available for %s,"
862                    " in use by %s",
863                    PCI_SLOT(devfn), PCI_FUNC(devfn), name,
864                    bus->devices[devfn]->name);
865         return NULL;
866     }
867
868     pci_dev->bus = bus;
869     pci_dev->devfn = devfn;
870     dma_as = pci_device_iommu_address_space(pci_dev);
871
872     memory_region_init_alias(&pci_dev->bus_master_enable_region,
873                              OBJECT(pci_dev), "bus master",
874                              dma_as->root, 0, memory_region_size(dma_as->root));
875     memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);
876     address_space_init(&pci_dev->bus_master_as, &pci_dev->bus_master_enable_region,
877                        name);
878
879     pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
880     pci_dev->irq_state = 0;
881     pci_config_alloc(pci_dev);
882
883     pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);
884     pci_config_set_device_id(pci_dev->config, pc->device_id);
885     pci_config_set_revision(pci_dev->config, pc->revision);
886     pci_config_set_class(pci_dev->config, pc->class_id);
887
888     if (!pc->is_bridge) {
889         if (pc->subsystem_vendor_id || pc->subsystem_id) {
890             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
891                          pc->subsystem_vendor_id);
892             pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
893                          pc->subsystem_id);
894         } else {
895             pci_set_default_subsystem_id(pci_dev);
896         }
897     } else {
898         /* subsystem_vendor_id/subsystem_id are only for header type 0 */
899         assert(!pc->subsystem_vendor_id);
900         assert(!pc->subsystem_id);
901     }
902     pci_init_cmask(pci_dev);
903     pci_init_wmask(pci_dev);
904     pci_init_w1cmask(pci_dev);
905     if (pc->is_bridge) {
906         pci_init_mask_bridge(pci_dev);
907     }
908     pci_init_multifunction(bus, pci_dev, &local_err);
909     if (local_err) {
910         error_propagate(errp, local_err);
911         do_pci_unregister_device(pci_dev);
912         return NULL;
913     }
914
915     if (!config_read)
916         config_read = pci_default_read_config;
917     if (!config_write)
918         config_write = pci_default_write_config;
919     pci_dev->config_read = config_read;
920     pci_dev->config_write = config_write;
921     bus->devices[devfn] = pci_dev;
922     pci_dev->version_id = 2; /* Current pci device vmstate version */
923     return pci_dev;
924 }
925
926 static void pci_unregister_io_regions(PCIDevice *pci_dev)
927 {
928     PCIIORegion *r;
929     int i;
930
931     for(i = 0; i < PCI_NUM_REGIONS; i++) {
932         r = &pci_dev->io_regions[i];
933         if (!r->size || r->addr == PCI_BAR_UNMAPPED)
934             continue;
935         memory_region_del_subregion(r->address_space, r->memory);
936     }
937
938     pci_unregister_vga(pci_dev);
939 }
940
941 static void pci_qdev_unrealize(DeviceState *dev, Error **errp)
942 {
943     PCIDevice *pci_dev = PCI_DEVICE(dev);
944     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
945
946     pci_unregister_io_regions(pci_dev);
947     pci_del_option_rom(pci_dev);
948
949     if (pc->exit) {
950         pc->exit(pci_dev);
951     }
952
953     do_pci_unregister_device(pci_dev);
954 }
955
956 void pci_register_bar(PCIDevice *pci_dev, int region_num,
957                       uint8_t type, MemoryRegion *memory)
958 {
959     PCIIORegion *r;
960     uint32_t addr;
961     uint64_t wmask;
962     pcibus_t size = memory_region_size(memory);
963
964     assert(region_num >= 0);
965     assert(region_num < PCI_NUM_REGIONS);
966     if (size & (size-1)) {
967         fprintf(stderr, "ERROR: PCI region size must be pow2 "
968                     "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
969         exit(1);
970     }
971
972     r = &pci_dev->io_regions[region_num];
973     r->addr = PCI_BAR_UNMAPPED;
974     r->size = size;
975     r->type = type;
976     r->memory = NULL;
977
978     wmask = ~(size - 1);
979     addr = pci_bar(pci_dev, region_num);
980     if (region_num == PCI_ROM_SLOT) {
981         /* ROM enable bit is writable */
982         wmask |= PCI_ROM_ADDRESS_ENABLE;
983     }
984     pci_set_long(pci_dev->config + addr, type);
985     if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
986         r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
987         pci_set_quad(pci_dev->wmask + addr, wmask);
988         pci_set_quad(pci_dev->cmask + addr, ~0ULL);
989     } else {
990         pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
991         pci_set_long(pci_dev->cmask + addr, 0xffffffff);
992     }
993     pci_dev->io_regions[region_num].memory = memory;
994     pci_dev->io_regions[region_num].address_space
995         = type & PCI_BASE_ADDRESS_SPACE_IO
996         ? pci_dev->bus->address_space_io
997         : pci_dev->bus->address_space_mem;
998 }
999
1000 static void pci_update_vga(PCIDevice *pci_dev)
1001 {
1002     uint16_t cmd;
1003
1004     if (!pci_dev->has_vga) {
1005         return;
1006     }
1007
1008     cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1009
1010     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_MEM],
1011                               cmd & PCI_COMMAND_MEMORY);
1012     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO],
1013                               cmd & PCI_COMMAND_IO);
1014     memory_region_set_enabled(pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI],
1015                               cmd & PCI_COMMAND_IO);
1016 }
1017
1018 void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,
1019                       MemoryRegion *io_lo, MemoryRegion *io_hi)
1020 {
1021     assert(!pci_dev->has_vga);
1022
1023     assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);
1024     pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;
1025     memory_region_add_subregion_overlap(pci_dev->bus->address_space_mem,
1026                                         QEMU_PCI_VGA_MEM_BASE, mem, 1);
1027
1028     assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);
1029     pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;
1030     memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1031                                         QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);
1032
1033     assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);
1034     pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;
1035     memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,
1036                                         QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);
1037     pci_dev->has_vga = true;
1038
1039     pci_update_vga(pci_dev);
1040 }
1041
1042 void pci_unregister_vga(PCIDevice *pci_dev)
1043 {
1044     if (!pci_dev->has_vga) {
1045         return;
1046     }
1047
1048     memory_region_del_subregion(pci_dev->bus->address_space_mem,
1049                                 pci_dev->vga_regions[QEMU_PCI_VGA_MEM]);
1050     memory_region_del_subregion(pci_dev->bus->address_space_io,
1051                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO]);
1052     memory_region_del_subregion(pci_dev->bus->address_space_io,
1053                                 pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI]);
1054     pci_dev->has_vga = false;
1055 }
1056
1057 pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
1058 {
1059     return pci_dev->io_regions[region_num].addr;
1060 }
1061
1062 static pcibus_t pci_bar_address(PCIDevice *d,
1063                                 int reg, uint8_t type, pcibus_t size)
1064 {
1065     pcibus_t new_addr, last_addr;
1066     int bar = pci_bar(d, reg);
1067     uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
1068
1069     if (type & PCI_BASE_ADDRESS_SPACE_IO) {
1070         if (!(cmd & PCI_COMMAND_IO)) {
1071             return PCI_BAR_UNMAPPED;
1072         }
1073         new_addr = pci_get_long(d->config + bar) & ~(size - 1);
1074         last_addr = new_addr + size - 1;
1075         /* Check if 32 bit BAR wraps around explicitly.
1076          * TODO: make priorities correct and remove this work around.
1077          */
1078         if (last_addr <= new_addr || new_addr == 0 || last_addr >= UINT32_MAX) {
1079             return PCI_BAR_UNMAPPED;
1080         }
1081         return new_addr;
1082     }
1083
1084     if (!(cmd & PCI_COMMAND_MEMORY)) {
1085         return PCI_BAR_UNMAPPED;
1086     }
1087     if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
1088         new_addr = pci_get_quad(d->config + bar);
1089     } else {
1090         new_addr = pci_get_long(d->config + bar);
1091     }
1092     /* the ROM slot has a specific enable bit */
1093     if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
1094         return PCI_BAR_UNMAPPED;
1095     }
1096     new_addr &= ~(size - 1);
1097     last_addr = new_addr + size - 1;
1098     /* NOTE: we do not support wrapping */
1099     /* XXX: as we cannot support really dynamic
1100        mappings, we handle specific values as invalid
1101        mappings. */
1102     if (last_addr <= new_addr || new_addr == 0 ||
1103         last_addr == PCI_BAR_UNMAPPED) {
1104         return PCI_BAR_UNMAPPED;
1105     }
1106
1107     /* Now pcibus_t is 64bit.
1108      * Check if 32 bit BAR wraps around explicitly.
1109      * Without this, PC ide doesn't work well.
1110      * TODO: remove this work around.
1111      */
1112     if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
1113         return PCI_BAR_UNMAPPED;
1114     }
1115
1116     /*
1117      * OS is allowed to set BAR beyond its addressable
1118      * bits. For example, 32 bit OS can set 64bit bar
1119      * to >4G. Check it. TODO: we might need to support
1120      * it in the future for e.g. PAE.
1121      */
1122     if (last_addr >= HWADDR_MAX) {
1123         return PCI_BAR_UNMAPPED;
1124     }
1125
1126     return new_addr;
1127 }
1128
1129 static void pci_update_mappings(PCIDevice *d)
1130 {
1131     PCIIORegion *r;
1132     int i;
1133     pcibus_t new_addr;
1134
1135     for(i = 0; i < PCI_NUM_REGIONS; i++) {
1136         r = &d->io_regions[i];
1137
1138         /* this region isn't registered */
1139         if (!r->size)
1140             continue;
1141
1142         new_addr = pci_bar_address(d, i, r->type, r->size);
1143
1144         /* This bar isn't changed */
1145         if (new_addr == r->addr)
1146             continue;
1147
1148         /* now do the real mapping */
1149         if (r->addr != PCI_BAR_UNMAPPED) {
1150             trace_pci_update_mappings_del(d, pci_bus_num(d->bus),
1151                                           PCI_FUNC(d->devfn),
1152                                           PCI_SLOT(d->devfn),
1153                                           i, r->addr, r->size);
1154             memory_region_del_subregion(r->address_space, r->memory);
1155         }
1156         r->addr = new_addr;
1157         if (r->addr != PCI_BAR_UNMAPPED) {
1158             trace_pci_update_mappings_add(d, pci_bus_num(d->bus),
1159                                           PCI_FUNC(d->devfn),
1160                                           PCI_SLOT(d->devfn),
1161                                           i, r->addr, r->size);
1162             memory_region_add_subregion_overlap(r->address_space,
1163                                                 r->addr, r->memory, 1);
1164         }
1165     }
1166
1167     pci_update_vga(d);
1168 }
1169
1170 static inline int pci_irq_disabled(PCIDevice *d)
1171 {
1172     return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1173 }
1174
1175 /* Called after interrupt disabled field update in config space,
1176  * assert/deassert interrupts if necessary.
1177  * Gets original interrupt disable bit value (before update). */
1178 static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1179 {
1180     int i, disabled = pci_irq_disabled(d);
1181     if (disabled == was_irq_disabled)
1182         return;
1183     for (i = 0; i < PCI_NUM_PINS; ++i) {
1184         int state = pci_irq_state(d, i);
1185         pci_change_irq_level(d, i, disabled ? -state : state);
1186     }
1187 }
1188
1189 uint32_t pci_default_read_config(PCIDevice *d,
1190                                  uint32_t address, int len)
1191 {
1192     uint32_t val = 0;
1193
1194     memcpy(&val, d->config + address, len);
1195     return le32_to_cpu(val);
1196 }
1197
1198 void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val_in, int l)
1199 {
1200     int i, was_irq_disabled = pci_irq_disabled(d);
1201     uint32_t val = val_in;
1202
1203     for (i = 0; i < l; val >>= 8, ++i) {
1204         uint8_t wmask = d->wmask[addr + i];
1205         uint8_t w1cmask = d->w1cmask[addr + i];
1206         assert(!(wmask & w1cmask));
1207         d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1208         d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1209     }
1210     if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1211         ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1212         ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1213         range_covers_byte(addr, l, PCI_COMMAND))
1214         pci_update_mappings(d);
1215
1216     if (range_covers_byte(addr, l, PCI_COMMAND)) {
1217         pci_update_irq_disabled(d, was_irq_disabled);
1218         memory_region_set_enabled(&d->bus_master_enable_region,
1219                                   pci_get_word(d->config + PCI_COMMAND)
1220                                     & PCI_COMMAND_MASTER);
1221     }
1222
1223     msi_write_config(d, addr, val_in, l);
1224     msix_write_config(d, addr, val_in, l);
1225 }
1226
1227 /***********************************************************/
1228 /* generic PCI irq support */
1229
1230 /* 0 <= irq_num <= 3. level must be 0 or 1 */
1231 static void pci_irq_handler(void *opaque, int irq_num, int level)
1232 {
1233     PCIDevice *pci_dev = opaque;
1234     int change;
1235
1236     change = level - pci_irq_state(pci_dev, irq_num);
1237     if (!change)
1238         return;
1239
1240     pci_set_irq_state(pci_dev, irq_num, level);
1241     pci_update_irq_status(pci_dev);
1242     if (pci_irq_disabled(pci_dev))
1243         return;
1244     pci_change_irq_level(pci_dev, irq_num, change);
1245 }
1246
1247 static inline int pci_intx(PCIDevice *pci_dev)
1248 {
1249     return pci_get_byte(pci_dev->config + PCI_INTERRUPT_PIN) - 1;
1250 }
1251
1252 qemu_irq pci_allocate_irq(PCIDevice *pci_dev)
1253 {
1254     int intx = pci_intx(pci_dev);
1255
1256     return qemu_allocate_irq(pci_irq_handler, pci_dev, intx);
1257 }
1258
1259 void pci_set_irq(PCIDevice *pci_dev, int level)
1260 {
1261     int intx = pci_intx(pci_dev);
1262     pci_irq_handler(pci_dev, intx, level);
1263 }
1264
1265 /* Special hooks used by device assignment */
1266 void pci_bus_set_route_irq_fn(PCIBus *bus, pci_route_irq_fn route_intx_to_irq)
1267 {
1268     assert(pci_bus_is_root(bus));
1269     bus->route_intx_to_irq = route_intx_to_irq;
1270 }
1271
1272 PCIINTxRoute pci_device_route_intx_to_irq(PCIDevice *dev, int pin)
1273 {
1274     PCIBus *bus;
1275
1276     do {
1277          bus = dev->bus;
1278          pin = bus->map_irq(dev, pin);
1279          dev = bus->parent_dev;
1280     } while (dev);
1281
1282     if (!bus->route_intx_to_irq) {
1283         error_report("PCI: Bug - unimplemented PCI INTx routing (%s)",
1284                      object_get_typename(OBJECT(bus->qbus.parent)));
1285         return (PCIINTxRoute) { PCI_INTX_DISABLED, -1 };
1286     }
1287
1288     return bus->route_intx_to_irq(bus->irq_opaque, pin);
1289 }
1290
1291 bool pci_intx_route_changed(PCIINTxRoute *old, PCIINTxRoute *new)
1292 {
1293     return old->mode != new->mode || old->irq != new->irq;
1294 }
1295
1296 void pci_bus_fire_intx_routing_notifier(PCIBus *bus)
1297 {
1298     PCIDevice *dev;
1299     PCIBus *sec;
1300     int i;
1301
1302     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1303         dev = bus->devices[i];
1304         if (dev && dev->intx_routing_notifier) {
1305             dev->intx_routing_notifier(dev);
1306         }
1307     }
1308
1309     QLIST_FOREACH(sec, &bus->child, sibling) {
1310         pci_bus_fire_intx_routing_notifier(sec);
1311     }
1312 }
1313
1314 void pci_device_set_intx_routing_notifier(PCIDevice *dev,
1315                                           PCIINTxRoutingNotifier notifier)
1316 {
1317     dev->intx_routing_notifier = notifier;
1318 }
1319
1320 /*
1321  * PCI-to-PCI bridge specification
1322  * 9.1: Interrupt routing. Table 9-1
1323  *
1324  * the PCI Express Base Specification, Revision 2.1
1325  * 2.2.8.1: INTx interrutp signaling - Rules
1326  *          the Implementation Note
1327  *          Table 2-20
1328  */
1329 /*
1330  * 0 <= pin <= 3 0 = INTA, 1 = INTB, 2 = INTC, 3 = INTD
1331  * 0-origin unlike PCI interrupt pin register.
1332  */
1333 int pci_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
1334 {
1335     return (pin + PCI_SLOT(pci_dev->devfn)) % PCI_NUM_PINS;
1336 }
1337
1338 /***********************************************************/
1339 /* monitor info on PCI */
1340
1341 typedef struct {
1342     uint16_t class;
1343     const char *desc;
1344     const char *fw_name;
1345     uint16_t fw_ign_bits;
1346 } pci_class_desc;
1347
1348 static const pci_class_desc pci_class_descriptions[] =
1349 {
1350     { 0x0001, "VGA controller", "display"},
1351     { 0x0100, "SCSI controller", "scsi"},
1352     { 0x0101, "IDE controller", "ide"},
1353     { 0x0102, "Floppy controller", "fdc"},
1354     { 0x0103, "IPI controller", "ipi"},
1355     { 0x0104, "RAID controller", "raid"},
1356     { 0x0106, "SATA controller"},
1357     { 0x0107, "SAS controller"},
1358     { 0x0180, "Storage controller"},
1359     { 0x0200, "Ethernet controller", "ethernet"},
1360     { 0x0201, "Token Ring controller", "token-ring"},
1361     { 0x0202, "FDDI controller", "fddi"},
1362     { 0x0203, "ATM controller", "atm"},
1363     { 0x0280, "Network controller"},
1364     { 0x0300, "VGA controller", "display", 0x00ff},
1365     { 0x0301, "XGA controller"},
1366     { 0x0302, "3D controller"},
1367     { 0x0380, "Display controller"},
1368     { 0x0400, "Video controller", "video"},
1369     { 0x0401, "Audio controller", "sound"},
1370     { 0x0402, "Phone"},
1371     { 0x0403, "Audio controller", "sound"},
1372     { 0x0480, "Multimedia controller"},
1373     { 0x0500, "RAM controller", "memory"},
1374     { 0x0501, "Flash controller", "flash"},
1375     { 0x0580, "Memory controller"},
1376     { 0x0600, "Host bridge", "host"},
1377     { 0x0601, "ISA bridge", "isa"},
1378     { 0x0602, "EISA bridge", "eisa"},
1379     { 0x0603, "MC bridge", "mca"},
1380     { 0x0604, "PCI bridge", "pci-bridge"},
1381     { 0x0605, "PCMCIA bridge", "pcmcia"},
1382     { 0x0606, "NUBUS bridge", "nubus"},
1383     { 0x0607, "CARDBUS bridge", "cardbus"},
1384     { 0x0608, "RACEWAY bridge"},
1385     { 0x0680, "Bridge"},
1386     { 0x0700, "Serial port", "serial"},
1387     { 0x0701, "Parallel port", "parallel"},
1388     { 0x0800, "Interrupt controller", "interrupt-controller"},
1389     { 0x0801, "DMA controller", "dma-controller"},
1390     { 0x0802, "Timer", "timer"},
1391     { 0x0803, "RTC", "rtc"},
1392     { 0x0900, "Keyboard", "keyboard"},
1393     { 0x0901, "Pen", "pen"},
1394     { 0x0902, "Mouse", "mouse"},
1395     { 0x0A00, "Dock station", "dock", 0x00ff},
1396     { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1397     { 0x0c00, "Fireware contorller", "fireware"},
1398     { 0x0c01, "Access bus controller", "access-bus"},
1399     { 0x0c02, "SSA controller", "ssa"},
1400     { 0x0c03, "USB controller", "usb"},
1401     { 0x0c04, "Fibre channel controller", "fibre-channel"},
1402     { 0x0c05, "SMBus"},
1403     { 0, NULL}
1404 };
1405
1406 static void pci_for_each_device_under_bus(PCIBus *bus,
1407                                           void (*fn)(PCIBus *b, PCIDevice *d,
1408                                                      void *opaque),
1409                                           void *opaque)
1410 {
1411     PCIDevice *d;
1412     int devfn;
1413
1414     for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1415         d = bus->devices[devfn];
1416         if (d) {
1417             fn(bus, d, opaque);
1418         }
1419     }
1420 }
1421
1422 void pci_for_each_device(PCIBus *bus, int bus_num,
1423                          void (*fn)(PCIBus *b, PCIDevice *d, void *opaque),
1424                          void *opaque)
1425 {
1426     bus = pci_find_bus_nr(bus, bus_num);
1427
1428     if (bus) {
1429         pci_for_each_device_under_bus(bus, fn, opaque);
1430     }
1431 }
1432
1433 static const pci_class_desc *get_class_desc(int class)
1434 {
1435     const pci_class_desc *desc;
1436
1437     desc = pci_class_descriptions;
1438     while (desc->desc && class != desc->class) {
1439         desc++;
1440     }
1441
1442     return desc;
1443 }
1444
1445 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num);
1446
1447 static PciMemoryRegionList *qmp_query_pci_regions(const PCIDevice *dev)
1448 {
1449     PciMemoryRegionList *head = NULL, *cur_item = NULL;
1450     int i;
1451
1452     for (i = 0; i < PCI_NUM_REGIONS; i++) {
1453         const PCIIORegion *r = &dev->io_regions[i];
1454         PciMemoryRegionList *region;
1455
1456         if (!r->size) {
1457             continue;
1458         }
1459
1460         region = g_malloc0(sizeof(*region));
1461         region->value = g_malloc0(sizeof(*region->value));
1462
1463         if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1464             region->value->type = g_strdup("io");
1465         } else {
1466             region->value->type = g_strdup("memory");
1467             region->value->has_prefetch = true;
1468             region->value->prefetch = !!(r->type & PCI_BASE_ADDRESS_MEM_PREFETCH);
1469             region->value->has_mem_type_64 = true;
1470             region->value->mem_type_64 = !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
1471         }
1472
1473         region->value->bar = i;
1474         region->value->address = r->addr;
1475         region->value->size = r->size;
1476
1477         /* XXX: waiting for the qapi to support GSList */
1478         if (!cur_item) {
1479             head = cur_item = region;
1480         } else {
1481             cur_item->next = region;
1482             cur_item = region;
1483         }
1484     }
1485
1486     return head;
1487 }
1488
1489 static PciBridgeInfo *qmp_query_pci_bridge(PCIDevice *dev, PCIBus *bus,
1490                                            int bus_num)
1491 {
1492     PciBridgeInfo *info;
1493     PciMemoryRange *range;
1494
1495     info = g_new0(PciBridgeInfo, 1);
1496
1497     info->bus = g_new0(PciBusInfo, 1);
1498     info->bus->number = dev->config[PCI_PRIMARY_BUS];
1499     info->bus->secondary = dev->config[PCI_SECONDARY_BUS];
1500     info->bus->subordinate = dev->config[PCI_SUBORDINATE_BUS];
1501
1502     range = info->bus->io_range = g_new0(PciMemoryRange, 1);
1503     range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO);
1504     range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO);
1505
1506     range = info->bus->memory_range = g_new0(PciMemoryRange, 1);
1507     range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1508     range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY);
1509
1510     range = info->bus->prefetchable_range = g_new0(PciMemoryRange, 1);
1511     range->base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1512     range->limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
1513
1514     if (dev->config[PCI_SECONDARY_BUS] != 0) {
1515         PCIBus *child_bus = pci_find_bus_nr(bus, dev->config[PCI_SECONDARY_BUS]);
1516         if (child_bus) {
1517             info->has_devices = true;
1518             info->devices = qmp_query_pci_devices(child_bus, dev->config[PCI_SECONDARY_BUS]);
1519         }
1520     }
1521
1522     return info;
1523 }
1524
1525 static PciDeviceInfo *qmp_query_pci_device(PCIDevice *dev, PCIBus *bus,
1526                                            int bus_num)
1527 {
1528     const pci_class_desc *desc;
1529     PciDeviceInfo *info;
1530     uint8_t type;
1531     int class;
1532
1533     info = g_new0(PciDeviceInfo, 1);
1534     info->bus = bus_num;
1535     info->slot = PCI_SLOT(dev->devfn);
1536     info->function = PCI_FUNC(dev->devfn);
1537
1538     info->class_info = g_new0(PciDeviceClass, 1);
1539     class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1540     info->class_info->q_class = class;
1541     desc = get_class_desc(class);
1542     if (desc->desc) {
1543         info->class_info->has_desc = true;
1544         info->class_info->desc = g_strdup(desc->desc);
1545     }
1546
1547     info->id = g_new0(PciDeviceId, 1);
1548     info->id->vendor = pci_get_word(dev->config + PCI_VENDOR_ID);
1549     info->id->device = pci_get_word(dev->config + PCI_DEVICE_ID);
1550     info->regions = qmp_query_pci_regions(dev);
1551     info->qdev_id = g_strdup(dev->qdev.id ? dev->qdev.id : "");
1552
1553     if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1554         info->has_irq = true;
1555         info->irq = dev->config[PCI_INTERRUPT_LINE];
1556     }
1557
1558     type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1559     if (type == PCI_HEADER_TYPE_BRIDGE) {
1560         info->has_pci_bridge = true;
1561         info->pci_bridge = qmp_query_pci_bridge(dev, bus, bus_num);
1562     }
1563
1564     return info;
1565 }
1566
1567 static PciDeviceInfoList *qmp_query_pci_devices(PCIBus *bus, int bus_num)
1568 {
1569     PciDeviceInfoList *info, *head = NULL, *cur_item = NULL;
1570     PCIDevice *dev;
1571     int devfn;
1572
1573     for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1574         dev = bus->devices[devfn];
1575         if (dev) {
1576             info = g_malloc0(sizeof(*info));
1577             info->value = qmp_query_pci_device(dev, bus, bus_num);
1578
1579             /* XXX: waiting for the qapi to support GSList */
1580             if (!cur_item) {
1581                 head = cur_item = info;
1582             } else {
1583                 cur_item->next = info;
1584                 cur_item = info;
1585             }
1586         }
1587     }
1588
1589     return head;
1590 }
1591
1592 static PciInfo *qmp_query_pci_bus(PCIBus *bus, int bus_num)
1593 {
1594     PciInfo *info = NULL;
1595
1596     bus = pci_find_bus_nr(bus, bus_num);
1597     if (bus) {
1598         info = g_malloc0(sizeof(*info));
1599         info->bus = bus_num;
1600         info->devices = qmp_query_pci_devices(bus, bus_num);
1601     }
1602
1603     return info;
1604 }
1605
1606 PciInfoList *qmp_query_pci(Error **errp)
1607 {
1608     PciInfoList *info, *head = NULL, *cur_item = NULL;
1609     PCIHostState *host_bridge;
1610
1611     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
1612         info = g_malloc0(sizeof(*info));
1613         info->value = qmp_query_pci_bus(host_bridge->bus,
1614                                         pci_bus_num(host_bridge->bus));
1615
1616         /* XXX: waiting for the qapi to support GSList */
1617         if (!cur_item) {
1618             head = cur_item = info;
1619         } else {
1620             cur_item->next = info;
1621             cur_item = info;
1622         }
1623     }
1624
1625     return head;
1626 }
1627
1628 static const char * const pci_nic_models[] = {
1629     "ne2k_pci",
1630     "i82551",
1631     "i82557b",
1632     "i82559er",
1633     "rtl8139",
1634     "e1000",
1635     "pcnet",
1636     "virtio",
1637     NULL
1638 };
1639
1640 static const char * const pci_nic_names[] = {
1641     "ne2k_pci",
1642     "i82551",
1643     "i82557b",
1644     "i82559er",
1645     "rtl8139",
1646     "e1000",
1647     "pcnet",
1648     "virtio-net-pci",
1649     NULL
1650 };
1651
1652 /* Initialize a PCI NIC.  */
1653 PCIDevice *pci_nic_init_nofail(NICInfo *nd, PCIBus *rootbus,
1654                                const char *default_model,
1655                                const char *default_devaddr)
1656 {
1657     const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1658     Error *err = NULL;
1659     PCIBus *bus;
1660     PCIDevice *pci_dev;
1661     DeviceState *dev;
1662     int devfn;
1663     int i;
1664
1665     if (qemu_show_nic_models(nd->model, pci_nic_models)) {
1666         exit(0);
1667     }
1668
1669     i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1670     if (i < 0) {
1671         exit(1);
1672     }
1673
1674     bus = pci_get_bus_devfn(&devfn, rootbus, devaddr);
1675     if (!bus) {
1676         error_report("Invalid PCI device address %s for device %s",
1677                      devaddr, pci_nic_names[i]);
1678         exit(1);
1679     }
1680
1681     pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1682     dev = &pci_dev->qdev;
1683     qdev_set_nic_properties(dev, nd);
1684
1685     object_property_set_bool(OBJECT(dev), true, "realized", &err);
1686     if (err) {
1687         error_report_err(err);
1688         object_unparent(OBJECT(dev));
1689         exit(1);
1690     }
1691
1692     return pci_dev;
1693 }
1694
1695 PCIDevice *pci_vga_init(PCIBus *bus)
1696 {
1697     switch (vga_interface_type) {
1698     case VGA_CIRRUS:
1699         return pci_create_simple(bus, -1, "cirrus-vga");
1700     case VGA_QXL:
1701         return pci_create_simple(bus, -1, "qxl-vga");
1702     case VGA_STD:
1703         return pci_create_simple(bus, -1, "VGA");
1704     case VGA_VMWARE:
1705         return pci_create_simple(bus, -1, "vmware-svga");
1706     case VGA_VIRTIO:
1707         return pci_create_simple(bus, -1, "virtio-vga");
1708     case VGA_NONE:
1709     default: /* Other non-PCI types. Checking for unsupported types is already
1710                 done in vl.c. */
1711         return NULL;
1712     }
1713 }
1714
1715 /* Whether a given bus number is in range of the secondary
1716  * bus of the given bridge device. */
1717 static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1718 {
1719     return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1720              PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1721         dev->config[PCI_SECONDARY_BUS] <= bus_num &&
1722         bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1723 }
1724
1725 /* Whether a given bus number is in a range of a root bus */
1726 static bool pci_root_bus_in_range(PCIBus *bus, int bus_num)
1727 {
1728     int i;
1729
1730     for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
1731         PCIDevice *dev = bus->devices[i];
1732
1733         if (dev && PCI_DEVICE_GET_CLASS(dev)->is_bridge) {
1734             if (pci_secondary_bus_in_range(dev, bus_num)) {
1735                 return true;
1736             }
1737         }
1738     }
1739
1740     return false;
1741 }
1742
1743 static PCIBus *pci_find_bus_nr(PCIBus *bus, int bus_num)
1744 {
1745     PCIBus *sec;
1746
1747     if (!bus) {
1748         return NULL;
1749     }
1750
1751     if (pci_bus_num(bus) == bus_num) {
1752         return bus;
1753     }
1754
1755     /* Consider all bus numbers in range for the host pci bridge. */
1756     if (!pci_bus_is_root(bus) &&
1757         !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1758         return NULL;
1759     }
1760
1761     /* try child bus */
1762     for (; bus; bus = sec) {
1763         QLIST_FOREACH(sec, &bus->child, sibling) {
1764             if (pci_bus_num(sec) == bus_num) {
1765                 return sec;
1766             }
1767             /* PXB buses assumed to be children of bus 0 */
1768             if (pci_bus_is_root(sec)) {
1769                 if (pci_root_bus_in_range(sec, bus_num)) {
1770                     break;
1771                 }
1772             } else {
1773                 if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1774                     break;
1775                 }
1776             }
1777         }
1778     }
1779
1780     return NULL;
1781 }
1782
1783 void pci_for_each_bus_depth_first(PCIBus *bus,
1784                                   void *(*begin)(PCIBus *bus, void *parent_state),
1785                                   void (*end)(PCIBus *bus, void *state),
1786                                   void *parent_state)
1787 {
1788     PCIBus *sec;
1789     void *state;
1790
1791     if (!bus) {
1792         return;
1793     }
1794
1795     if (begin) {
1796         state = begin(bus, parent_state);
1797     } else {
1798         state = parent_state;
1799     }
1800
1801     QLIST_FOREACH(sec, &bus->child, sibling) {
1802         pci_for_each_bus_depth_first(sec, begin, end, state);
1803     }
1804
1805     if (end) {
1806         end(bus, state);
1807     }
1808 }
1809
1810
1811 PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1812 {
1813     bus = pci_find_bus_nr(bus, bus_num);
1814
1815     if (!bus)
1816         return NULL;
1817
1818     return bus->devices[devfn];
1819 }
1820
1821 static void pci_qdev_realize(DeviceState *qdev, Error **errp)
1822 {
1823     PCIDevice *pci_dev = (PCIDevice *)qdev;
1824     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);
1825     Error *local_err = NULL;
1826     PCIBus *bus;
1827     bool is_default_rom;
1828
1829     /* initialize cap_present for pci_is_express() and pci_config_size() */
1830     if (pc->is_express) {
1831         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1832     }
1833
1834     bus = PCI_BUS(qdev_get_parent_bus(qdev));
1835     pci_dev = do_pci_register_device(pci_dev, bus,
1836                                      object_get_typename(OBJECT(qdev)),
1837                                      pci_dev->devfn, errp);
1838     if (pci_dev == NULL)
1839         return;
1840
1841     if (pc->realize) {
1842         pc->realize(pci_dev, &local_err);
1843         if (local_err) {
1844             error_propagate(errp, local_err);
1845             do_pci_unregister_device(pci_dev);
1846             return;
1847         }
1848     }
1849
1850     /* rom loading */
1851     is_default_rom = false;
1852     if (pci_dev->romfile == NULL && pc->romfile != NULL) {
1853         pci_dev->romfile = g_strdup(pc->romfile);
1854         is_default_rom = true;
1855     }
1856
1857     pci_add_option_rom(pci_dev, is_default_rom, &local_err);
1858     if (local_err) {
1859         error_propagate(errp, local_err);
1860         pci_qdev_unrealize(DEVICE(pci_dev), NULL);
1861         return;
1862     }
1863 }
1864
1865 static void pci_default_realize(PCIDevice *dev, Error **errp)
1866 {
1867     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
1868
1869     if (pc->init) {
1870         if (pc->init(dev) < 0) {
1871             error_setg(errp, "Device initialization failed");
1872             return;
1873         }
1874     }
1875 }
1876
1877 PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1878                                     const char *name)
1879 {
1880     DeviceState *dev;
1881
1882     dev = qdev_create(&bus->qbus, name);
1883     qdev_prop_set_int32(dev, "addr", devfn);
1884     qdev_prop_set_bit(dev, "multifunction", multifunction);
1885     return PCI_DEVICE(dev);
1886 }
1887
1888 PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1889                                            bool multifunction,
1890                                            const char *name)
1891 {
1892     PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1893     qdev_init_nofail(&dev->qdev);
1894     return dev;
1895 }
1896
1897 PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1898 {
1899     return pci_create_multifunction(bus, devfn, false, name);
1900 }
1901
1902 PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1903 {
1904     return pci_create_simple_multifunction(bus, devfn, false, name);
1905 }
1906
1907 static uint8_t pci_find_space(PCIDevice *pdev, uint8_t size)
1908 {
1909     int offset = PCI_CONFIG_HEADER_SIZE;
1910     int i;
1911     for (i = PCI_CONFIG_HEADER_SIZE; i < PCI_CONFIG_SPACE_SIZE; ++i) {
1912         if (pdev->used[i])
1913             offset = i + 1;
1914         else if (i - offset + 1 == size)
1915             return offset;
1916     }
1917     return 0;
1918 }
1919
1920 static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1921                                         uint8_t *prev_p)
1922 {
1923     uint8_t next, prev;
1924
1925     if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1926         return 0;
1927
1928     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1929          prev = next + PCI_CAP_LIST_NEXT)
1930         if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1931             break;
1932
1933     if (prev_p)
1934         *prev_p = prev;
1935     return next;
1936 }
1937
1938 static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
1939 {
1940     uint8_t next, prev, found = 0;
1941
1942     if (!(pdev->used[offset])) {
1943         return 0;
1944     }
1945
1946     assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
1947
1948     for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1949          prev = next + PCI_CAP_LIST_NEXT) {
1950         if (next <= offset && next > found) {
1951             found = next;
1952         }
1953     }
1954     return found;
1955 }
1956
1957 /* Patch the PCI vendor and device ids in a PCI rom image if necessary.
1958    This is needed for an option rom which is used for more than one device. */
1959 static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
1960 {
1961     uint16_t vendor_id;
1962     uint16_t device_id;
1963     uint16_t rom_vendor_id;
1964     uint16_t rom_device_id;
1965     uint16_t rom_magic;
1966     uint16_t pcir_offset;
1967     uint8_t checksum;
1968
1969     /* Words in rom data are little endian (like in PCI configuration),
1970        so they can be read / written with pci_get_word / pci_set_word. */
1971
1972     /* Only a valid rom will be patched. */
1973     rom_magic = pci_get_word(ptr);
1974     if (rom_magic != 0xaa55) {
1975         PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
1976         return;
1977     }
1978     pcir_offset = pci_get_word(ptr + 0x18);
1979     if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
1980         PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
1981         return;
1982     }
1983
1984     vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
1985     device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
1986     rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
1987     rom_device_id = pci_get_word(ptr + pcir_offset + 6);
1988
1989     PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
1990                 vendor_id, device_id, rom_vendor_id, rom_device_id);
1991
1992     checksum = ptr[6];
1993
1994     if (vendor_id != rom_vendor_id) {
1995         /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
1996         checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
1997         checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
1998         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1999         ptr[6] = checksum;
2000         pci_set_word(ptr + pcir_offset + 4, vendor_id);
2001     }
2002
2003     if (device_id != rom_device_id) {
2004         /* Patch device id and checksum (at offset 6 for etherboot roms). */
2005         checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
2006         checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
2007         PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
2008         ptr[6] = checksum;
2009         pci_set_word(ptr + pcir_offset + 6, device_id);
2010     }
2011 }
2012
2013 /* Add an option rom for the device */
2014 static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,
2015                                Error **errp)
2016 {
2017     int size;
2018     char *path;
2019     void *ptr;
2020     char name[32];
2021     const VMStateDescription *vmsd;
2022
2023     if (!pdev->romfile)
2024         return;
2025     if (strlen(pdev->romfile) == 0)
2026         return;
2027
2028     if (!pdev->rom_bar) {
2029         /*
2030          * Load rom via fw_cfg instead of creating a rom bar,
2031          * for 0.11 compatibility.
2032          */
2033         int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
2034
2035         /*
2036          * Hot-plugged devices can't use the option ROM
2037          * if the rom bar is disabled.
2038          */
2039         if (DEVICE(pdev)->hotplugged) {
2040             error_setg(errp, "Hot-plugged device without ROM bar"
2041                        " can't have an option ROM");
2042             return;
2043         }
2044
2045         if (class == 0x0300) {
2046             rom_add_vga(pdev->romfile);
2047         } else {
2048             rom_add_option(pdev->romfile, -1);
2049         }
2050         return;
2051     }
2052
2053     path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
2054     if (path == NULL) {
2055         path = g_strdup(pdev->romfile);
2056     }
2057
2058     size = get_image_size(path);
2059     if (size < 0) {
2060         error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);
2061         g_free(path);
2062         return;
2063     } else if (size == 0) {
2064         error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);
2065         g_free(path);
2066         return;
2067     }
2068     if (size & (size - 1)) {
2069         size = 1 << qemu_fls(size);
2070     }
2071
2072     vmsd = qdev_get_vmsd(DEVICE(pdev));
2073
2074     if (vmsd) {
2075         snprintf(name, sizeof(name), "%s.rom", vmsd->name);
2076     } else {
2077         snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));
2078     }
2079     pdev->has_rom = true;
2080     memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_abort);
2081     vmstate_register_ram(&pdev->rom, &pdev->qdev);
2082     ptr = memory_region_get_ram_ptr(&pdev->rom);
2083     load_image(path, ptr);
2084     g_free(path);
2085
2086     if (is_default_rom) {
2087         /* Only the default rom images will be patched (if needed). */
2088         pci_patch_ids(pdev, ptr, size);
2089     }
2090
2091     pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
2092 }
2093
2094 static void pci_del_option_rom(PCIDevice *pdev)
2095 {
2096     if (!pdev->has_rom)
2097         return;
2098
2099     vmstate_unregister_ram(&pdev->rom, &pdev->qdev);
2100     pdev->has_rom = false;
2101 }
2102
2103 /*
2104  * if offset = 0,
2105  * Find and reserve space and add capability to the linked list
2106  * in pci config space
2107  */
2108 int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
2109                        uint8_t offset, uint8_t size)
2110 {
2111     int ret;
2112     Error *local_err = NULL;
2113
2114     ret = pci_add_capability2(pdev, cap_id, offset, size, &local_err);
2115     if (local_err) {
2116         assert(ret < 0);
2117         error_report_err(local_err);
2118     } else {
2119         /* success implies a positive offset in config space */
2120         assert(ret > 0);
2121     }
2122     return ret;
2123 }
2124
2125 int pci_add_capability2(PCIDevice *pdev, uint8_t cap_id,
2126                        uint8_t offset, uint8_t size,
2127                        Error **errp)
2128 {
2129     uint8_t *config;
2130     int i, overlapping_cap;
2131
2132     if (!offset) {
2133         offset = pci_find_space(pdev, size);
2134         if (!offset) {
2135             error_setg(errp, "out of PCI config space");
2136             return -ENOSPC;
2137         }
2138     } else {
2139         /* Verify that capabilities don't overlap.  Note: device assignment
2140          * depends on this check to verify that the device is not broken.
2141          * Should never trigger for emulated devices, but it's helpful
2142          * for debugging these. */
2143         for (i = offset; i < offset + size; i++) {
2144             overlapping_cap = pci_find_capability_at_offset(pdev, i);
2145             if (overlapping_cap) {
2146                 error_setg(errp, "%s:%02x:%02x.%x "
2147                            "Attempt to add PCI capability %x at offset "
2148                            "%x overlaps existing capability %x at offset %x",
2149                            pci_root_bus_path(pdev), pci_bus_num(pdev->bus),
2150                            PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
2151                            cap_id, offset, overlapping_cap, i);
2152                 return -EINVAL;
2153             }
2154         }
2155     }
2156
2157     config = pdev->config + offset;
2158     config[PCI_CAP_LIST_ID] = cap_id;
2159     config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
2160     pdev->config[PCI_CAPABILITY_LIST] = offset;
2161     pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2162     memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));
2163     /* Make capability read-only by default */
2164     memset(pdev->wmask + offset, 0, size);
2165     /* Check capability by default */
2166     memset(pdev->cmask + offset, 0xFF, size);
2167     return offset;
2168 }
2169
2170 /* Unlink capability from the pci config space. */
2171 void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2172 {
2173     uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2174     if (!offset)
2175         return;
2176     pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2177     /* Make capability writable again */
2178     memset(pdev->wmask + offset, 0xff, size);
2179     memset(pdev->w1cmask + offset, 0, size);
2180     /* Clear cmask as device-specific registers can't be checked */
2181     memset(pdev->cmask + offset, 0, size);
2182     memset(pdev->used + offset, 0, QEMU_ALIGN_UP(size, 4));
2183
2184     if (!pdev->config[PCI_CAPABILITY_LIST])
2185         pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2186 }
2187
2188 uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2189 {
2190     return pci_find_capability_list(pdev, cap_id, NULL);
2191 }
2192
2193 static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2194 {
2195     PCIDevice *d = (PCIDevice *)dev;
2196     const pci_class_desc *desc;
2197     char ctxt[64];
2198     PCIIORegion *r;
2199     int i, class;
2200
2201     class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2202     desc = pci_class_descriptions;
2203     while (desc->desc && class != desc->class)
2204         desc++;
2205     if (desc->desc) {
2206         snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2207     } else {
2208         snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2209     }
2210
2211     monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2212                    "pci id %04x:%04x (sub %04x:%04x)\n",
2213                    indent, "", ctxt, pci_bus_num(d->bus),
2214                    PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2215                    pci_get_word(d->config + PCI_VENDOR_ID),
2216                    pci_get_word(d->config + PCI_DEVICE_ID),
2217                    pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2218                    pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2219     for (i = 0; i < PCI_NUM_REGIONS; i++) {
2220         r = &d->io_regions[i];
2221         if (!r->size)
2222             continue;
2223         monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2224                        " [0x%"FMT_PCIBUS"]\n",
2225                        indent, "",
2226                        i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2227                        r->addr, r->addr + r->size - 1);
2228     }
2229 }
2230
2231 static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2232 {
2233     PCIDevice *d = (PCIDevice *)dev;
2234     const char *name = NULL;
2235     const pci_class_desc *desc =  pci_class_descriptions;
2236     int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2237
2238     while (desc->desc &&
2239           (class & ~desc->fw_ign_bits) !=
2240           (desc->class & ~desc->fw_ign_bits)) {
2241         desc++;
2242     }
2243
2244     if (desc->desc) {
2245         name = desc->fw_name;
2246     }
2247
2248     if (name) {
2249         pstrcpy(buf, len, name);
2250     } else {
2251         snprintf(buf, len, "pci%04x,%04x",
2252                  pci_get_word(d->config + PCI_VENDOR_ID),
2253                  pci_get_word(d->config + PCI_DEVICE_ID));
2254     }
2255
2256     return buf;
2257 }
2258
2259 static char *pcibus_get_fw_dev_path(DeviceState *dev)
2260 {
2261     PCIDevice *d = (PCIDevice *)dev;
2262     char path[50], name[33];
2263     int off;
2264
2265     off = snprintf(path, sizeof(path), "%s@%x",
2266                    pci_dev_fw_name(dev, name, sizeof name),
2267                    PCI_SLOT(d->devfn));
2268     if (PCI_FUNC(d->devfn))
2269         snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2270     return g_strdup(path);
2271 }
2272
2273 static char *pcibus_get_dev_path(DeviceState *dev)
2274 {
2275     PCIDevice *d = container_of(dev, PCIDevice, qdev);
2276     PCIDevice *t;
2277     int slot_depth;
2278     /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2279      * 00 is added here to make this format compatible with
2280      * domain:Bus:Slot.Func for systems without nested PCI bridges.
2281      * Slot.Function list specifies the slot and function numbers for all
2282      * devices on the path from root to the specific device. */
2283     const char *root_bus_path;
2284     int root_bus_len;
2285     char slot[] = ":SS.F";
2286     int slot_len = sizeof slot - 1 /* For '\0' */;
2287     int path_len;
2288     char *path, *p;
2289     int s;
2290
2291     root_bus_path = pci_root_bus_path(d);
2292     root_bus_len = strlen(root_bus_path);
2293
2294     /* Calculate # of slots on path between device and root. */;
2295     slot_depth = 0;
2296     for (t = d; t; t = t->bus->parent_dev) {
2297         ++slot_depth;
2298     }
2299
2300     path_len = root_bus_len + slot_len * slot_depth;
2301
2302     /* Allocate memory, fill in the terminating null byte. */
2303     path = g_malloc(path_len + 1 /* For '\0' */);
2304     path[path_len] = '\0';
2305
2306     memcpy(path, root_bus_path, root_bus_len);
2307
2308     /* Fill in slot numbers. We walk up from device to root, so need to print
2309      * them in the reverse order, last to first. */
2310     p = path + path_len;
2311     for (t = d; t; t = t->bus->parent_dev) {
2312         p -= slot_len;
2313         s = snprintf(slot, sizeof slot, ":%02x.%x",
2314                      PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2315         assert(s == slot_len);
2316         memcpy(p, slot, slot_len);
2317     }
2318
2319     return path;
2320 }
2321
2322 static int pci_qdev_find_recursive(PCIBus *bus,
2323                                    const char *id, PCIDevice **pdev)
2324 {
2325     DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2326     if (!qdev) {
2327         return -ENODEV;
2328     }
2329
2330     /* roughly check if given qdev is pci device */
2331     if (object_dynamic_cast(OBJECT(qdev), TYPE_PCI_DEVICE)) {
2332         *pdev = PCI_DEVICE(qdev);
2333         return 0;
2334     }
2335     return -EINVAL;
2336 }
2337
2338 int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2339 {
2340     PCIHostState *host_bridge;
2341     int rc = -ENODEV;
2342
2343     QLIST_FOREACH(host_bridge, &pci_host_bridges, next) {
2344         int tmp = pci_qdev_find_recursive(host_bridge->bus, id, pdev);
2345         if (!tmp) {
2346             rc = 0;
2347             break;
2348         }
2349         if (tmp != -ENODEV) {
2350             rc = tmp;
2351         }
2352     }
2353
2354     return rc;
2355 }
2356
2357 MemoryRegion *pci_address_space(PCIDevice *dev)
2358 {
2359     return dev->bus->address_space_mem;
2360 }
2361
2362 MemoryRegion *pci_address_space_io(PCIDevice *dev)
2363 {
2364     return dev->bus->address_space_io;
2365 }
2366
2367 static void pci_device_class_init(ObjectClass *klass, void *data)
2368 {
2369     DeviceClass *k = DEVICE_CLASS(klass);
2370     PCIDeviceClass *pc = PCI_DEVICE_CLASS(klass);
2371
2372     k->realize = pci_qdev_realize;
2373     k->unrealize = pci_qdev_unrealize;
2374     k->bus_type = TYPE_PCI_BUS;
2375     k->props = pci_props;
2376     pc->realize = pci_default_realize;
2377 }
2378
2379 AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)
2380 {
2381     PCIBus *bus = PCI_BUS(dev->bus);
2382
2383     if (bus->iommu_fn) {
2384         return bus->iommu_fn(bus, bus->iommu_opaque, dev->devfn);
2385     }
2386
2387     if (bus->parent_dev) {
2388         /** We are ignoring the bus master DMA bit of the bridge
2389          *  as it would complicate things such as VFIO for no good reason */
2390         return pci_device_iommu_address_space(bus->parent_dev);
2391     }
2392
2393     return &address_space_memory;
2394 }
2395
2396 void pci_setup_iommu(PCIBus *bus, PCIIOMMUFunc fn, void *opaque)
2397 {
2398     bus->iommu_fn = fn;
2399     bus->iommu_opaque = opaque;
2400 }
2401
2402 static void pci_dev_get_w64(PCIBus *b, PCIDevice *dev, void *opaque)
2403 {
2404     Range *range = opaque;
2405     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);
2406     uint16_t cmd = pci_get_word(dev->config + PCI_COMMAND);
2407     int i;
2408
2409     if (!(cmd & PCI_COMMAND_MEMORY)) {
2410         return;
2411     }
2412
2413     if (pc->is_bridge) {
2414         pcibus_t base = pci_bridge_get_base(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2415         pcibus_t limit = pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_MEM_PREFETCH);
2416
2417         base = MAX(base, 0x1ULL << 32);
2418
2419         if (limit >= base) {
2420             Range pref_range;
2421             pref_range.begin = base;
2422             pref_range.end = limit + 1;
2423             range_extend(range, &pref_range);
2424         }
2425     }
2426     for (i = 0; i < PCI_NUM_REGIONS; ++i) {
2427         PCIIORegion *r = &dev->io_regions[i];
2428         Range region_range;
2429
2430         if (!r->size ||
2431             (r->type & PCI_BASE_ADDRESS_SPACE_IO) ||
2432             !(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64)) {
2433             continue;
2434         }
2435         region_range.begin = pci_bar_address(dev, i, r->type, r->size);
2436         region_range.end = region_range.begin + r->size;
2437
2438         if (region_range.begin == PCI_BAR_UNMAPPED) {
2439             continue;
2440         }
2441
2442         region_range.begin = MAX(region_range.begin, 0x1ULL << 32);
2443
2444         if (region_range.end - 1 >= region_range.begin) {
2445             range_extend(range, &region_range);
2446         }
2447     }
2448 }
2449
2450 void pci_bus_get_w64_range(PCIBus *bus, Range *range)
2451 {
2452     range->begin = range->end = 0;
2453     pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);
2454 }
2455
2456 static const TypeInfo pci_device_type_info = {
2457     .name = TYPE_PCI_DEVICE,
2458     .parent = TYPE_DEVICE,
2459     .instance_size = sizeof(PCIDevice),
2460     .abstract = true,
2461     .class_size = sizeof(PCIDeviceClass),
2462     .class_init = pci_device_class_init,
2463 };
2464
2465 static void pci_register_types(void)
2466 {
2467     type_register_static(&pci_bus_info);
2468     type_register_static(&pcie_bus_info);
2469     type_register_static(&pci_device_type_info);
2470 }
2471
2472 type_init(pci_register_types)