Statistics
| Branch: | Revision:

root / hw / pci.c @ 81b1008d

History | View | Annotate | Download (66.5 kB)

1
/*
2
 * QEMU PCI bus manager
3
 *
4
 * Copyright (c) 2004 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "hw.h"
25
#include "pci.h"
26
#include "pci_bridge.h"
27
#include "pci_internals.h"
28
#include "monitor.h"
29
#include "net.h"
30
#include "sysemu.h"
31
#include "loader.h"
32
#include "qemu-objects.h"
33
#include "range.h"
34

    
35
//#define DEBUG_PCI
36
#ifdef DEBUG_PCI
37
# define PCI_DPRINTF(format, ...)       printf(format, ## __VA_ARGS__)
38
#else
39
# define PCI_DPRINTF(format, ...)       do { } while (0)
40
#endif
41

    
42
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
43
static char *pcibus_get_dev_path(DeviceState *dev);
44
static char *pcibus_get_fw_dev_path(DeviceState *dev);
45
static int pcibus_reset(BusState *qbus);
46

    
47
struct BusInfo pci_bus_info = {
48
    .name       = "PCI",
49
    .size       = sizeof(PCIBus),
50
    .print_dev  = pcibus_dev_print,
51
    .get_dev_path = pcibus_get_dev_path,
52
    .get_fw_dev_path = pcibus_get_fw_dev_path,
53
    .reset      = pcibus_reset,
54
    .props      = (Property[]) {
55
        DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
56
        DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
57
        DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
58
        DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
59
                        QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
60
        DEFINE_PROP_BIT("command_serr_enable", PCIDevice, cap_present,
61
                        QEMU_PCI_CAP_SERR_BITNR, true),
62
        DEFINE_PROP_END_OF_LIST()
63
    }
64
};
65

    
66
static void pci_update_mappings(PCIDevice *d);
67
static void pci_set_irq(void *opaque, int irq_num, int level);
68
static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom);
69
static void pci_del_option_rom(PCIDevice *pdev);
70

    
71
static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
72
static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
73

    
74
struct PCIHostBus {
75
    int domain;
76
    struct PCIBus *bus;
77
    QLIST_ENTRY(PCIHostBus) next;
78
};
79
static QLIST_HEAD(, PCIHostBus) host_buses;
80

    
81
static const VMStateDescription vmstate_pcibus = {
82
    .name = "PCIBUS",
83
    .version_id = 1,
84
    .minimum_version_id = 1,
85
    .minimum_version_id_old = 1,
86
    .fields      = (VMStateField []) {
87
        VMSTATE_INT32_EQUAL(nirq, PCIBus),
88
        VMSTATE_VARRAY_INT32(irq_count, PCIBus, nirq, 0, vmstate_info_int32, int32_t),
89
        VMSTATE_END_OF_LIST()
90
    }
91
};
92

    
93
static int pci_bar(PCIDevice *d, int reg)
94
{
95
    uint8_t type;
96

    
97
    if (reg != PCI_ROM_SLOT)
98
        return PCI_BASE_ADDRESS_0 + reg * 4;
99

    
100
    type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
101
    return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
102
}
103

    
104
static inline int pci_irq_state(PCIDevice *d, int irq_num)
105
{
106
        return (d->irq_state >> irq_num) & 0x1;
107
}
108

    
109
static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
110
{
111
        d->irq_state &= ~(0x1 << irq_num);
112
        d->irq_state |= level << irq_num;
113
}
114

    
115
static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
116
{
117
    PCIBus *bus;
118
    for (;;) {
119
        bus = pci_dev->bus;
120
        irq_num = bus->map_irq(pci_dev, irq_num);
121
        if (bus->set_irq)
122
            break;
123
        pci_dev = bus->parent_dev;
124
    }
125
    bus->irq_count[irq_num] += change;
126
    bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
127
}
128

    
129
int pci_bus_get_irq_level(PCIBus *bus, int irq_num)
130
{
131
    assert(irq_num >= 0);
132
    assert(irq_num < bus->nirq);
133
    return !!bus->irq_count[irq_num];
134
}
135

    
136
/* Update interrupt status bit in config space on interrupt
137
 * state change. */
138
static void pci_update_irq_status(PCIDevice *dev)
139
{
140
    if (dev->irq_state) {
141
        dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
142
    } else {
143
        dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
144
    }
145
}
146

    
147
void pci_device_deassert_intx(PCIDevice *dev)
148
{
149
    int i;
150
    for (i = 0; i < PCI_NUM_PINS; ++i) {
151
        qemu_set_irq(dev->irq[i], 0);
152
    }
153
}
154

    
155
/*
156
 * This function is called on #RST and FLR.
157
 * FLR if PCI_EXP_DEVCTL_BCR_FLR is set
158
 */
159
void pci_device_reset(PCIDevice *dev)
160
{
161
    int r;
162
    /* TODO: call the below unconditionally once all pci devices
163
     * are qdevified */
164
    if (dev->qdev.info) {
165
        qdev_reset_all(&dev->qdev);
166
    }
167

    
168
    dev->irq_state = 0;
169
    pci_update_irq_status(dev);
170
    pci_device_deassert_intx(dev);
171
    /* Clear all writable bits */
172
    pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
173
                                 pci_get_word(dev->wmask + PCI_COMMAND) |
174
                                 pci_get_word(dev->w1cmask + PCI_COMMAND));
175
    pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
176
                                 pci_get_word(dev->wmask + PCI_STATUS) |
177
                                 pci_get_word(dev->w1cmask + PCI_STATUS));
178
    dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
179
    dev->config[PCI_INTERRUPT_LINE] = 0x0;
180
    for (r = 0; r < PCI_NUM_REGIONS; ++r) {
181
        PCIIORegion *region = &dev->io_regions[r];
182
        if (!region->size) {
183
            continue;
184
        }
185

    
186
        if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
187
            region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
188
            pci_set_quad(dev->config + pci_bar(dev, r), region->type);
189
        } else {
190
            pci_set_long(dev->config + pci_bar(dev, r), region->type);
191
        }
192
    }
193
    pci_update_mappings(dev);
194
}
195

    
196
/*
197
 * Trigger pci bus reset under a given bus.
198
 * To be called on RST# assert.
199
 */
200
void pci_bus_reset(PCIBus *bus)
201
{
202
    int i;
203

    
204
    for (i = 0; i < bus->nirq; i++) {
205
        bus->irq_count[i] = 0;
206
    }
207
    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
208
        if (bus->devices[i]) {
209
            pci_device_reset(bus->devices[i]);
210
        }
211
    }
212
}
213

    
214
static int pcibus_reset(BusState *qbus)
215
{
216
    pci_bus_reset(DO_UPCAST(PCIBus, qbus, qbus));
217

    
218
    /* topology traverse is done by pci_bus_reset().
219
       Tell qbus/qdev walker not to traverse the tree */
220
    return 1;
221
}
222

    
223
static void pci_host_bus_register(int domain, PCIBus *bus)
224
{
225
    struct PCIHostBus *host;
226
    host = g_malloc0(sizeof(*host));
227
    host->domain = domain;
228
    host->bus = bus;
229
    QLIST_INSERT_HEAD(&host_buses, host, next);
230
}
231

    
232
PCIBus *pci_find_root_bus(int domain)
233
{
234
    struct PCIHostBus *host;
235

    
236
    QLIST_FOREACH(host, &host_buses, next) {
237
        if (host->domain == domain) {
238
            return host->bus;
239
        }
240
    }
241

    
242
    return NULL;
243
}
244

    
245
int pci_find_domain(const PCIBus *bus)
246
{
247
    PCIDevice *d;
248
    struct PCIHostBus *host;
249

    
250
    /* obtain root bus */
251
    while ((d = bus->parent_dev) != NULL) {
252
        bus = d->bus;
253
    }
254

    
255
    QLIST_FOREACH(host, &host_buses, next) {
256
        if (host->bus == bus) {
257
            return host->domain;
258
        }
259
    }
260

    
261
    abort();    /* should not be reached */
262
    return -1;
263
}
264

    
265
void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
266
                         const char *name,
267
                         MemoryRegion *address_space_mem,
268
                         MemoryRegion *address_space_io,
269
                         uint8_t devfn_min)
270
{
271
    qbus_create_inplace(&bus->qbus, &pci_bus_info, parent, name);
272
    assert(PCI_FUNC(devfn_min) == 0);
273
    bus->devfn_min = devfn_min;
274
    bus->address_space_mem = address_space_mem;
275
    bus->address_space_io = address_space_io;
276

    
277
    /* host bridge */
278
    QLIST_INIT(&bus->child);
279
    pci_host_bus_register(0, bus); /* for now only pci domain 0 is supported */
280

    
281
    vmstate_register(NULL, -1, &vmstate_pcibus, bus);
282
}
283

    
284
PCIBus *pci_bus_new(DeviceState *parent, const char *name,
285
                    MemoryRegion *address_space_mem,
286
                    MemoryRegion *address_space_io,
287
                    uint8_t devfn_min)
288
{
289
    PCIBus *bus;
290

    
291
    bus = g_malloc0(sizeof(*bus));
292
    bus->qbus.qdev_allocated = 1;
293
    pci_bus_new_inplace(bus, parent, name, address_space_mem,
294
                        address_space_io, devfn_min);
295
    return bus;
296
}
297

    
298
void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
299
                  void *irq_opaque, int nirq)
300
{
301
    bus->set_irq = set_irq;
302
    bus->map_irq = map_irq;
303
    bus->irq_opaque = irq_opaque;
304
    bus->nirq = nirq;
305
    bus->irq_count = g_malloc0(nirq * sizeof(bus->irq_count[0]));
306
}
307

    
308
void pci_bus_hotplug(PCIBus *bus, pci_hotplug_fn hotplug, DeviceState *qdev)
309
{
310
    bus->qbus.allow_hotplug = 1;
311
    bus->hotplug = hotplug;
312
    bus->hotplug_qdev = qdev;
313
}
314

    
315
PCIBus *pci_register_bus(DeviceState *parent, const char *name,
316
                         pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
317
                         void *irq_opaque,
318
                         MemoryRegion *address_space_mem,
319
                         MemoryRegion *address_space_io,
320
                         uint8_t devfn_min, int nirq)
321
{
322
    PCIBus *bus;
323

    
324
    bus = pci_bus_new(parent, name, address_space_mem,
325
                      address_space_io, devfn_min);
326
    pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
327
    return bus;
328
}
329

    
330
int pci_bus_num(PCIBus *s)
331
{
332
    if (!s->parent_dev)
333
        return 0;       /* pci host bridge */
334
    return s->parent_dev->config[PCI_SECONDARY_BUS];
335
}
336

    
337
static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
338
{
339
    PCIDevice *s = container_of(pv, PCIDevice, config);
340
    uint8_t *config;
341
    int i;
342

    
343
    assert(size == pci_config_size(s));
344
    config = g_malloc(size);
345

    
346
    qemu_get_buffer(f, config, size);
347
    for (i = 0; i < size; ++i) {
348
        if ((config[i] ^ s->config[i]) &
349
            s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
350
            g_free(config);
351
            return -EINVAL;
352
        }
353
    }
354
    memcpy(s->config, config, size);
355

    
356
    pci_update_mappings(s);
357

    
358
    g_free(config);
359
    return 0;
360
}
361

    
362
/* just put buffer */
363
static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
364
{
365
    const uint8_t **v = pv;
366
    assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
367
    qemu_put_buffer(f, *v, size);
368
}
369

    
370
static VMStateInfo vmstate_info_pci_config = {
371
    .name = "pci config",
372
    .get  = get_pci_config_device,
373
    .put  = put_pci_config_device,
374
};
375

    
376
static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
377
{
378
    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
379
    uint32_t irq_state[PCI_NUM_PINS];
380
    int i;
381
    for (i = 0; i < PCI_NUM_PINS; ++i) {
382
        irq_state[i] = qemu_get_be32(f);
383
        if (irq_state[i] != 0x1 && irq_state[i] != 0) {
384
            fprintf(stderr, "irq state %d: must be 0 or 1.\n",
385
                    irq_state[i]);
386
            return -EINVAL;
387
        }
388
    }
389

    
390
    for (i = 0; i < PCI_NUM_PINS; ++i) {
391
        pci_set_irq_state(s, i, irq_state[i]);
392
    }
393

    
394
    return 0;
395
}
396

    
397
static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
398
{
399
    int i;
400
    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
401

    
402
    for (i = 0; i < PCI_NUM_PINS; ++i) {
403
        qemu_put_be32(f, pci_irq_state(s, i));
404
    }
405
}
406

    
407
static VMStateInfo vmstate_info_pci_irq_state = {
408
    .name = "pci irq state",
409
    .get  = get_pci_irq_state,
410
    .put  = put_pci_irq_state,
411
};
412

    
413
const VMStateDescription vmstate_pci_device = {
414
    .name = "PCIDevice",
415
    .version_id = 2,
416
    .minimum_version_id = 1,
417
    .minimum_version_id_old = 1,
418
    .fields      = (VMStateField []) {
419
        VMSTATE_INT32_LE(version_id, PCIDevice),
420
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
421
                                   vmstate_info_pci_config,
422
                                   PCI_CONFIG_SPACE_SIZE),
423
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
424
                                   vmstate_info_pci_irq_state,
425
                                   PCI_NUM_PINS * sizeof(int32_t)),
426
        VMSTATE_END_OF_LIST()
427
    }
428
};
429

    
430
const VMStateDescription vmstate_pcie_device = {
431
    .name = "PCIDevice",
432
    .version_id = 2,
433
    .minimum_version_id = 1,
434
    .minimum_version_id_old = 1,
435
    .fields      = (VMStateField []) {
436
        VMSTATE_INT32_LE(version_id, PCIDevice),
437
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
438
                                   vmstate_info_pci_config,
439
                                   PCIE_CONFIG_SPACE_SIZE),
440
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
441
                                   vmstate_info_pci_irq_state,
442
                                   PCI_NUM_PINS * sizeof(int32_t)),
443
        VMSTATE_END_OF_LIST()
444
    }
445
};
446

    
447
static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
448
{
449
    return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
450
}
451

    
452
void pci_device_save(PCIDevice *s, QEMUFile *f)
453
{
454
    /* Clear interrupt status bit: it is implicit
455
     * in irq_state which we are saving.
456
     * This makes us compatible with old devices
457
     * which never set or clear this bit. */
458
    s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
459
    vmstate_save_state(f, pci_get_vmstate(s), s);
460
    /* Restore the interrupt status bit. */
461
    pci_update_irq_status(s);
462
}
463

    
464
int pci_device_load(PCIDevice *s, QEMUFile *f)
465
{
466
    int ret;
467
    ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
468
    /* Restore the interrupt status bit. */
469
    pci_update_irq_status(s);
470
    return ret;
471
}
472

    
473
static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
474
{
475
    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
476
                 pci_default_sub_vendor_id);
477
    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
478
                 pci_default_sub_device_id);
479
}
480

    
481
/*
482
 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
483
 *       [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
484
 */
485
int pci_parse_devaddr(const char *addr, int *domp, int *busp,
486
                      unsigned int *slotp, unsigned int *funcp)
487
{
488
    const char *p;
489
    char *e;
490
    unsigned long val;
491
    unsigned long dom = 0, bus = 0;
492
    unsigned int slot = 0;
493
    unsigned int func = 0;
494

    
495
    p = addr;
496
    val = strtoul(p, &e, 16);
497
    if (e == p)
498
        return -1;
499
    if (*e == ':') {
500
        bus = val;
501
        p = e + 1;
502
        val = strtoul(p, &e, 16);
503
        if (e == p)
504
            return -1;
505
        if (*e == ':') {
506
            dom = bus;
507
            bus = val;
508
            p = e + 1;
509
            val = strtoul(p, &e, 16);
510
            if (e == p)
511
                return -1;
512
        }
513
    }
514

    
515
    slot = val;
516

    
517
    if (funcp != NULL) {
518
        if (*e != '.')
519
            return -1;
520

    
521
        p = e + 1;
522
        val = strtoul(p, &e, 16);
523
        if (e == p)
524
            return -1;
525

    
526
        func = val;
527
    }
528

    
529
    /* if funcp == NULL func is 0 */
530
    if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
531
        return -1;
532

    
533
    if (*e)
534
        return -1;
535

    
536
    /* Note: QEMU doesn't implement domains other than 0 */
537
    if (!pci_find_bus(pci_find_root_bus(dom), bus))
538
        return -1;
539

    
540
    *domp = dom;
541
    *busp = bus;
542
    *slotp = slot;
543
    if (funcp != NULL)
544
        *funcp = func;
545
    return 0;
546
}
547

    
548
int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
549
                     unsigned *slotp)
550
{
551
    /* strip legacy tag */
552
    if (!strncmp(addr, "pci_addr=", 9)) {
553
        addr += 9;
554
    }
555
    if (pci_parse_devaddr(addr, domp, busp, slotp, NULL)) {
556
        monitor_printf(mon, "Invalid pci address\n");
557
        return -1;
558
    }
559
    return 0;
560
}
561

    
562
PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
563
{
564
    int dom, bus;
565
    unsigned slot;
566

    
567
    if (!devaddr) {
568
        *devfnp = -1;
569
        return pci_find_bus(pci_find_root_bus(0), 0);
570
    }
571

    
572
    if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
573
        return NULL;
574
    }
575

    
576
    *devfnp = PCI_DEVFN(slot, 0);
577
    return pci_find_bus(pci_find_root_bus(dom), bus);
578
}
579

    
580
static void pci_init_cmask(PCIDevice *dev)
581
{
582
    pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
583
    pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
584
    dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
585
    dev->cmask[PCI_REVISION_ID] = 0xff;
586
    dev->cmask[PCI_CLASS_PROG] = 0xff;
587
    pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
588
    dev->cmask[PCI_HEADER_TYPE] = 0xff;
589
    dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
590
}
591

    
592
static void pci_init_wmask(PCIDevice *dev)
593
{
594
    int config_size = pci_config_size(dev);
595

    
596
    dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
597
    dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
598
    pci_set_word(dev->wmask + PCI_COMMAND,
599
                 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
600
                 PCI_COMMAND_INTX_DISABLE);
601
    if (dev->cap_present & QEMU_PCI_CAP_SERR) {
602
        pci_word_test_and_set_mask(dev->wmask + PCI_COMMAND, PCI_COMMAND_SERR);
603
    }
604

    
605
    memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
606
           config_size - PCI_CONFIG_HEADER_SIZE);
607
}
608

    
609
static void pci_init_w1cmask(PCIDevice *dev)
610
{
611
    /*
612
     * Note: It's okay to set w1cmask even for readonly bits as
613
     * long as their value is hardwired to 0.
614
     */
615
    pci_set_word(dev->w1cmask + PCI_STATUS,
616
                 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
617
                 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
618
                 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
619
}
620

    
621
static void pci_init_wmask_bridge(PCIDevice *d)
622
{
623
    /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
624
       PCI_SEC_LETENCY_TIMER */
625
    memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
626

    
627
    /* base and limit */
628
    d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
629
    d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
630
    pci_set_word(d->wmask + PCI_MEMORY_BASE,
631
                 PCI_MEMORY_RANGE_MASK & 0xffff);
632
    pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
633
                 PCI_MEMORY_RANGE_MASK & 0xffff);
634
    pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
635
                 PCI_PREF_RANGE_MASK & 0xffff);
636
    pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
637
                 PCI_PREF_RANGE_MASK & 0xffff);
638

    
639
    /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
640
    memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
641

    
642
/* TODO: add this define to pci_regs.h in linux and then in qemu. */
643
#define  PCI_BRIDGE_CTL_VGA_16BIT        0x10        /* VGA 16-bit decode */
644
#define  PCI_BRIDGE_CTL_DISCARD                0x100        /* Primary discard timer */
645
#define  PCI_BRIDGE_CTL_SEC_DISCARD        0x200        /* Secondary discard timer */
646
#define  PCI_BRIDGE_CTL_DISCARD_STATUS        0x400        /* Discard timer status */
647
#define  PCI_BRIDGE_CTL_DISCARD_SERR        0x800        /* Discard timer SERR# enable */
648
    pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
649
                 PCI_BRIDGE_CTL_PARITY |
650
                 PCI_BRIDGE_CTL_SERR |
651
                 PCI_BRIDGE_CTL_ISA |
652
                 PCI_BRIDGE_CTL_VGA |
653
                 PCI_BRIDGE_CTL_VGA_16BIT |
654
                 PCI_BRIDGE_CTL_MASTER_ABORT |
655
                 PCI_BRIDGE_CTL_BUS_RESET |
656
                 PCI_BRIDGE_CTL_FAST_BACK |
657
                 PCI_BRIDGE_CTL_DISCARD |
658
                 PCI_BRIDGE_CTL_SEC_DISCARD |
659
                 PCI_BRIDGE_CTL_DISCARD_SERR);
660
    /* Below does not do anything as we never set this bit, put here for
661
     * completeness. */
662
    pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
663
                 PCI_BRIDGE_CTL_DISCARD_STATUS);
664
}
665

    
666
static int pci_init_multifunction(PCIBus *bus, PCIDevice *dev)
667
{
668
    uint8_t slot = PCI_SLOT(dev->devfn);
669
    uint8_t func;
670

    
671
    if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
672
        dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
673
    }
674

    
675
    /*
676
     * multifunction bit is interpreted in two ways as follows.
677
     *   - all functions must set the bit to 1.
678
     *     Example: Intel X53
679
     *   - function 0 must set the bit, but the rest function (> 0)
680
     *     is allowed to leave the bit to 0.
681
     *     Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
682
     *
683
     * So OS (at least Linux) checks the bit of only function 0,
684
     * and doesn't see the bit of function > 0.
685
     *
686
     * The below check allows both interpretation.
687
     */
688
    if (PCI_FUNC(dev->devfn)) {
689
        PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
690
        if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
691
            /* function 0 should set multifunction bit */
692
            error_report("PCI: single function device can't be populated "
693
                         "in function %x.%x", slot, PCI_FUNC(dev->devfn));
694
            return -1;
695
        }
696
        return 0;
697
    }
698

    
699
    if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
700
        return 0;
701
    }
702
    /* function 0 indicates single function, so function > 0 must be NULL */
703
    for (func = 1; func < PCI_FUNC_MAX; ++func) {
704
        if (bus->devices[PCI_DEVFN(slot, func)]) {
705
            error_report("PCI: %x.0 indicates single function, "
706
                         "but %x.%x is already populated.",
707
                         slot, slot, func);
708
            return -1;
709
        }
710
    }
711
    return 0;
712
}
713

    
714
static void pci_config_alloc(PCIDevice *pci_dev)
715
{
716
    int config_size = pci_config_size(pci_dev);
717

    
718
    pci_dev->config = g_malloc0(config_size);
719
    pci_dev->cmask = g_malloc0(config_size);
720
    pci_dev->wmask = g_malloc0(config_size);
721
    pci_dev->w1cmask = g_malloc0(config_size);
722
    pci_dev->used = g_malloc0(config_size);
723
}
724

    
725
static void pci_config_free(PCIDevice *pci_dev)
726
{
727
    g_free(pci_dev->config);
728
    g_free(pci_dev->cmask);
729
    g_free(pci_dev->wmask);
730
    g_free(pci_dev->w1cmask);
731
    g_free(pci_dev->used);
732
}
733

    
734
/* -1 for devfn means auto assign */
735
static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
736
                                         const char *name, int devfn,
737
                                         const PCIDeviceInfo *info)
738
{
739
    PCIConfigReadFunc *config_read = info->config_read;
740
    PCIConfigWriteFunc *config_write = info->config_write;
741

    
742
    if (devfn < 0) {
743
        for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
744
            devfn += PCI_FUNC_MAX) {
745
            if (!bus->devices[devfn])
746
                goto found;
747
        }
748
        error_report("PCI: no slot/function available for %s, all in use", name);
749
        return NULL;
750
    found: ;
751
    } else if (bus->devices[devfn]) {
752
        error_report("PCI: slot %d function %d not available for %s, in use by %s",
753
                     PCI_SLOT(devfn), PCI_FUNC(devfn), name, bus->devices[devfn]->name);
754
        return NULL;
755
    }
756
    pci_dev->bus = bus;
757
    pci_dev->devfn = devfn;
758
    pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
759
    pci_dev->irq_state = 0;
760
    pci_config_alloc(pci_dev);
761

    
762
    pci_config_set_vendor_id(pci_dev->config, info->vendor_id);
763
    pci_config_set_device_id(pci_dev->config, info->device_id);
764
    pci_config_set_revision(pci_dev->config, info->revision);
765
    pci_config_set_class(pci_dev->config, info->class_id);
766

    
767
    if (!info->is_bridge) {
768
        if (info->subsystem_vendor_id || info->subsystem_id) {
769
            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
770
                         info->subsystem_vendor_id);
771
            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
772
                         info->subsystem_id);
773
        } else {
774
            pci_set_default_subsystem_id(pci_dev);
775
        }
776
    } else {
777
        /* subsystem_vendor_id/subsystem_id are only for header type 0 */
778
        assert(!info->subsystem_vendor_id);
779
        assert(!info->subsystem_id);
780
    }
781
    pci_init_cmask(pci_dev);
782
    pci_init_wmask(pci_dev);
783
    pci_init_w1cmask(pci_dev);
784
    if (info->is_bridge) {
785
        pci_init_wmask_bridge(pci_dev);
786
    }
787
    if (pci_init_multifunction(bus, pci_dev)) {
788
        pci_config_free(pci_dev);
789
        return NULL;
790
    }
791

    
792
    if (!config_read)
793
        config_read = pci_default_read_config;
794
    if (!config_write)
795
        config_write = pci_default_write_config;
796
    pci_dev->config_read = config_read;
797
    pci_dev->config_write = config_write;
798
    bus->devices[devfn] = pci_dev;
799
    pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
800
    pci_dev->version_id = 2; /* Current pci device vmstate version */
801
    return pci_dev;
802
}
803

    
804
static void do_pci_unregister_device(PCIDevice *pci_dev)
805
{
806
    qemu_free_irqs(pci_dev->irq);
807
    pci_dev->bus->devices[pci_dev->devfn] = NULL;
808
    pci_config_free(pci_dev);
809
}
810

    
811
/* TODO: obsolete. eliminate this once all pci devices are qdevifed. */
812
PCIDevice *pci_register_device(PCIBus *bus, const char *name,
813
                               int instance_size, int devfn,
814
                               PCIConfigReadFunc *config_read,
815
                               PCIConfigWriteFunc *config_write)
816
{
817
    PCIDevice *pci_dev;
818
    PCIDeviceInfo info = {
819
        .config_read = config_read,
820
        .config_write = config_write,
821
    };
822

    
823
    pci_dev = g_malloc0(instance_size);
824
    pci_dev = do_pci_register_device(pci_dev, bus, name, devfn, &info);
825
    if (pci_dev == NULL) {
826
        hw_error("PCI: can't register device\n");
827
    }
828
    return pci_dev;
829
}
830

    
831
static void pci_unregister_io_regions(PCIDevice *pci_dev)
832
{
833
    PCIIORegion *r;
834
    int i;
835

    
836
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
837
        r = &pci_dev->io_regions[i];
838
        if (!r->size || r->addr == PCI_BAR_UNMAPPED)
839
            continue;
840
        memory_region_del_subregion(r->address_space, r->memory);
841
    }
842
}
843

    
844
static int pci_unregister_device(DeviceState *dev)
845
{
846
    PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
847
    PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
848
    int ret = 0;
849

    
850
    if (info->exit)
851
        ret = info->exit(pci_dev);
852
    if (ret)
853
        return ret;
854

    
855
    pci_unregister_io_regions(pci_dev);
856
    pci_del_option_rom(pci_dev);
857
    g_free(pci_dev->romfile);
858
    do_pci_unregister_device(pci_dev);
859
    return 0;
860
}
861

    
862
void pci_register_bar(PCIDevice *pci_dev, int region_num,
863
                      uint8_t type, MemoryRegion *memory)
864
{
865
    PCIIORegion *r;
866
    uint32_t addr;
867
    uint64_t wmask;
868
    pcibus_t size = memory_region_size(memory);
869

    
870
    assert(region_num >= 0);
871
    assert(region_num < PCI_NUM_REGIONS);
872
    if (size & (size-1)) {
873
        fprintf(stderr, "ERROR: PCI region size must be pow2 "
874
                    "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
875
        exit(1);
876
    }
877

    
878
    r = &pci_dev->io_regions[region_num];
879
    r->addr = PCI_BAR_UNMAPPED;
880
    r->size = size;
881
    r->filtered_size = size;
882
    r->type = type;
883
    r->memory = NULL;
884

    
885
    wmask = ~(size - 1);
886
    addr = pci_bar(pci_dev, region_num);
887
    if (region_num == PCI_ROM_SLOT) {
888
        /* ROM enable bit is writable */
889
        wmask |= PCI_ROM_ADDRESS_ENABLE;
890
    }
891
    pci_set_long(pci_dev->config + addr, type);
892
    if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
893
        r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
894
        pci_set_quad(pci_dev->wmask + addr, wmask);
895
        pci_set_quad(pci_dev->cmask + addr, ~0ULL);
896
    } else {
897
        pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
898
        pci_set_long(pci_dev->cmask + addr, 0xffffffff);
899
    }
900
    pci_dev->io_regions[region_num].memory = memory;
901
    pci_dev->io_regions[region_num].address_space
902
        = type & PCI_BASE_ADDRESS_SPACE_IO
903
        ? pci_dev->bus->address_space_io
904
        : pci_dev->bus->address_space_mem;
905
}
906

    
907
pcibus_t pci_get_bar_addr(PCIDevice *pci_dev, int region_num)
908
{
909
    return pci_dev->io_regions[region_num].addr;
910
}
911

    
912
static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
913
                              uint8_t type)
914
{
915
    pcibus_t base = *addr;
916
    pcibus_t limit = *addr + *size - 1;
917
    PCIDevice *br;
918

    
919
    for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
920
        uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
921

    
922
        if (type & PCI_BASE_ADDRESS_SPACE_IO) {
923
            if (!(cmd & PCI_COMMAND_IO)) {
924
                goto no_map;
925
            }
926
        } else {
927
            if (!(cmd & PCI_COMMAND_MEMORY)) {
928
                goto no_map;
929
            }
930
        }
931

    
932
        base = MAX(base, pci_bridge_get_base(br, type));
933
        limit = MIN(limit, pci_bridge_get_limit(br, type));
934
    }
935

    
936
    if (base > limit) {
937
        goto no_map;
938
    }
939
    *addr = base;
940
    *size = limit - base + 1;
941
    return;
942
no_map:
943
    *addr = PCI_BAR_UNMAPPED;
944
    *size = 0;
945
}
946

    
947
static pcibus_t pci_bar_address(PCIDevice *d,
948
                                int reg, uint8_t type, pcibus_t size)
949
{
950
    pcibus_t new_addr, last_addr;
951
    int bar = pci_bar(d, reg);
952
    uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
953

    
954
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
955
        if (!(cmd & PCI_COMMAND_IO)) {
956
            return PCI_BAR_UNMAPPED;
957
        }
958
        new_addr = pci_get_long(d->config + bar) & ~(size - 1);
959
        last_addr = new_addr + size - 1;
960
        /* NOTE: we have only 64K ioports on PC */
961
        if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
962
            return PCI_BAR_UNMAPPED;
963
        }
964
        return new_addr;
965
    }
966

    
967
    if (!(cmd & PCI_COMMAND_MEMORY)) {
968
        return PCI_BAR_UNMAPPED;
969
    }
970
    if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
971
        new_addr = pci_get_quad(d->config + bar);
972
    } else {
973
        new_addr = pci_get_long(d->config + bar);
974
    }
975
    /* the ROM slot has a specific enable bit */
976
    if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
977
        return PCI_BAR_UNMAPPED;
978
    }
979
    new_addr &= ~(size - 1);
980
    last_addr = new_addr + size - 1;
981
    /* NOTE: we do not support wrapping */
982
    /* XXX: as we cannot support really dynamic
983
       mappings, we handle specific values as invalid
984
       mappings. */
985
    if (last_addr <= new_addr || new_addr == 0 ||
986
        last_addr == PCI_BAR_UNMAPPED) {
987
        return PCI_BAR_UNMAPPED;
988
    }
989

    
990
    /* Now pcibus_t is 64bit.
991
     * Check if 32 bit BAR wraps around explicitly.
992
     * Without this, PC ide doesn't work well.
993
     * TODO: remove this work around.
994
     */
995
    if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
996
        return PCI_BAR_UNMAPPED;
997
    }
998

    
999
    /*
1000
     * OS is allowed to set BAR beyond its addressable
1001
     * bits. For example, 32 bit OS can set 64bit bar
1002
     * to >4G. Check it. TODO: we might need to support
1003
     * it in the future for e.g. PAE.
1004
     */
1005
    if (last_addr >= TARGET_PHYS_ADDR_MAX) {
1006
        return PCI_BAR_UNMAPPED;
1007
    }
1008

    
1009
    return new_addr;
1010
}
1011

    
1012
static void pci_update_mappings(PCIDevice *d)
1013
{
1014
    PCIIORegion *r;
1015
    int i;
1016
    pcibus_t new_addr, filtered_size;
1017

    
1018
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
1019
        r = &d->io_regions[i];
1020

    
1021
        /* this region isn't registered */
1022
        if (!r->size)
1023
            continue;
1024

    
1025
        new_addr = pci_bar_address(d, i, r->type, r->size);
1026

    
1027
        /* bridge filtering */
1028
        filtered_size = r->size;
1029
        if (new_addr != PCI_BAR_UNMAPPED) {
1030
            pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
1031
        }
1032

    
1033
        /* This bar isn't changed */
1034
        if (new_addr == r->addr && filtered_size == r->filtered_size)
1035
            continue;
1036

    
1037
        /* now do the real mapping */
1038
        if (r->addr != PCI_BAR_UNMAPPED) {
1039
            memory_region_del_subregion(r->address_space, r->memory);
1040
        }
1041
        r->addr = new_addr;
1042
        r->filtered_size = filtered_size;
1043
        if (r->addr != PCI_BAR_UNMAPPED) {
1044
            /*
1045
             * TODO: currently almost all the map funcions assumes
1046
             * filtered_size == size and addr & ~(size - 1) == addr.
1047
             * However with bridge filtering, they aren't always true.
1048
             * Teach them such cases, such that filtered_size < size and
1049
             * addr & (size - 1) != 0.
1050
             */
1051
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1052
                memory_region_add_subregion_overlap(r->address_space,
1053
                                                    r->addr,
1054
                                                    r->memory,
1055
                                                    1);
1056
            } else {
1057
                memory_region_add_subregion_overlap(r->address_space,
1058
                                                    r->addr,
1059
                                                    r->memory,
1060
                                                    1);
1061
            }
1062
        }
1063
    }
1064
}
1065

    
1066
static inline int pci_irq_disabled(PCIDevice *d)
1067
{
1068
    return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1069
}
1070

    
1071
/* Called after interrupt disabled field update in config space,
1072
 * assert/deassert interrupts if necessary.
1073
 * Gets original interrupt disable bit value (before update). */
1074
static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1075
{
1076
    int i, disabled = pci_irq_disabled(d);
1077
    if (disabled == was_irq_disabled)
1078
        return;
1079
    for (i = 0; i < PCI_NUM_PINS; ++i) {
1080
        int state = pci_irq_state(d, i);
1081
        pci_change_irq_level(d, i, disabled ? -state : state);
1082
    }
1083
}
1084

    
1085
uint32_t pci_default_read_config(PCIDevice *d,
1086
                                 uint32_t address, int len)
1087
{
1088
    uint32_t val = 0;
1089

    
1090
    memcpy(&val, d->config + address, len);
1091
    return le32_to_cpu(val);
1092
}
1093

    
1094
void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
1095
{
1096
    int i, was_irq_disabled = pci_irq_disabled(d);
1097

    
1098
    for (i = 0; i < l; val >>= 8, ++i) {
1099
        uint8_t wmask = d->wmask[addr + i];
1100
        uint8_t w1cmask = d->w1cmask[addr + i];
1101
        assert(!(wmask & w1cmask));
1102
        d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1103
        d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1104
    }
1105
    if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1106
        ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1107
        ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1108
        range_covers_byte(addr, l, PCI_COMMAND))
1109
        pci_update_mappings(d);
1110

    
1111
    if (range_covers_byte(addr, l, PCI_COMMAND))
1112
        pci_update_irq_disabled(d, was_irq_disabled);
1113
}
1114

    
1115
/***********************************************************/
1116
/* generic PCI irq support */
1117

    
1118
/* 0 <= irq_num <= 3. level must be 0 or 1 */
1119
static void pci_set_irq(void *opaque, int irq_num, int level)
1120
{
1121
    PCIDevice *pci_dev = opaque;
1122
    int change;
1123

    
1124
    change = level - pci_irq_state(pci_dev, irq_num);
1125
    if (!change)
1126
        return;
1127

    
1128
    pci_set_irq_state(pci_dev, irq_num, level);
1129
    pci_update_irq_status(pci_dev);
1130
    if (pci_irq_disabled(pci_dev))
1131
        return;
1132
    pci_change_irq_level(pci_dev, irq_num, change);
1133
}
1134

    
1135
/***********************************************************/
1136
/* monitor info on PCI */
1137

    
1138
typedef struct {
1139
    uint16_t class;
1140
    const char *desc;
1141
    const char *fw_name;
1142
    uint16_t fw_ign_bits;
1143
} pci_class_desc;
1144

    
1145
static const pci_class_desc pci_class_descriptions[] =
1146
{
1147
    { 0x0001, "VGA controller", "display"},
1148
    { 0x0100, "SCSI controller", "scsi"},
1149
    { 0x0101, "IDE controller", "ide"},
1150
    { 0x0102, "Floppy controller", "fdc"},
1151
    { 0x0103, "IPI controller", "ipi"},
1152
    { 0x0104, "RAID controller", "raid"},
1153
    { 0x0106, "SATA controller"},
1154
    { 0x0107, "SAS controller"},
1155
    { 0x0180, "Storage controller"},
1156
    { 0x0200, "Ethernet controller", "ethernet"},
1157
    { 0x0201, "Token Ring controller", "token-ring"},
1158
    { 0x0202, "FDDI controller", "fddi"},
1159
    { 0x0203, "ATM controller", "atm"},
1160
    { 0x0280, "Network controller"},
1161
    { 0x0300, "VGA controller", "display", 0x00ff},
1162
    { 0x0301, "XGA controller"},
1163
    { 0x0302, "3D controller"},
1164
    { 0x0380, "Display controller"},
1165
    { 0x0400, "Video controller", "video"},
1166
    { 0x0401, "Audio controller", "sound"},
1167
    { 0x0402, "Phone"},
1168
    { 0x0403, "Audio controller", "sound"},
1169
    { 0x0480, "Multimedia controller"},
1170
    { 0x0500, "RAM controller", "memory"},
1171
    { 0x0501, "Flash controller", "flash"},
1172
    { 0x0580, "Memory controller"},
1173
    { 0x0600, "Host bridge", "host"},
1174
    { 0x0601, "ISA bridge", "isa"},
1175
    { 0x0602, "EISA bridge", "eisa"},
1176
    { 0x0603, "MC bridge", "mca"},
1177
    { 0x0604, "PCI bridge", "pci"},
1178
    { 0x0605, "PCMCIA bridge", "pcmcia"},
1179
    { 0x0606, "NUBUS bridge", "nubus"},
1180
    { 0x0607, "CARDBUS bridge", "cardbus"},
1181
    { 0x0608, "RACEWAY bridge"},
1182
    { 0x0680, "Bridge"},
1183
    { 0x0700, "Serial port", "serial"},
1184
    { 0x0701, "Parallel port", "parallel"},
1185
    { 0x0800, "Interrupt controller", "interrupt-controller"},
1186
    { 0x0801, "DMA controller", "dma-controller"},
1187
    { 0x0802, "Timer", "timer"},
1188
    { 0x0803, "RTC", "rtc"},
1189
    { 0x0900, "Keyboard", "keyboard"},
1190
    { 0x0901, "Pen", "pen"},
1191
    { 0x0902, "Mouse", "mouse"},
1192
    { 0x0A00, "Dock station", "dock", 0x00ff},
1193
    { 0x0B00, "i386 cpu", "cpu", 0x00ff},
1194
    { 0x0c00, "Fireware contorller", "fireware"},
1195
    { 0x0c01, "Access bus controller", "access-bus"},
1196
    { 0x0c02, "SSA controller", "ssa"},
1197
    { 0x0c03, "USB controller", "usb"},
1198
    { 0x0c04, "Fibre channel controller", "fibre-channel"},
1199
    { 0, NULL}
1200
};
1201

    
1202
static void pci_for_each_device_under_bus(PCIBus *bus,
1203
                                          void (*fn)(PCIBus *b, PCIDevice *d))
1204
{
1205
    PCIDevice *d;
1206
    int devfn;
1207

    
1208
    for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1209
        d = bus->devices[devfn];
1210
        if (d) {
1211
            fn(bus, d);
1212
        }
1213
    }
1214
}
1215

    
1216
void pci_for_each_device(PCIBus *bus, int bus_num,
1217
                         void (*fn)(PCIBus *b, PCIDevice *d))
1218
{
1219
    bus = pci_find_bus(bus, bus_num);
1220

    
1221
    if (bus) {
1222
        pci_for_each_device_under_bus(bus, fn);
1223
    }
1224
}
1225

    
1226
static void pci_device_print(Monitor *mon, QDict *device)
1227
{
1228
    QDict *qdict;
1229
    QListEntry *entry;
1230
    uint64_t addr, size;
1231

    
1232
    monitor_printf(mon, "  Bus %2" PRId64 ", ", qdict_get_int(device, "bus"));
1233
    monitor_printf(mon, "device %3" PRId64 ", function %" PRId64 ":\n",
1234
                        qdict_get_int(device, "slot"),
1235
                        qdict_get_int(device, "function"));
1236
    monitor_printf(mon, "    ");
1237

    
1238
    qdict = qdict_get_qdict(device, "class_info");
1239
    if (qdict_haskey(qdict, "desc")) {
1240
        monitor_printf(mon, "%s", qdict_get_str(qdict, "desc"));
1241
    } else {
1242
        monitor_printf(mon, "Class %04" PRId64, qdict_get_int(qdict, "class"));
1243
    }
1244

    
1245
    qdict = qdict_get_qdict(device, "id");
1246
    monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
1247
                        qdict_get_int(qdict, "device"),
1248
                        qdict_get_int(qdict, "vendor"));
1249

    
1250
    if (qdict_haskey(device, "irq")) {
1251
        monitor_printf(mon, "      IRQ %" PRId64 ".\n",
1252
                            qdict_get_int(device, "irq"));
1253
    }
1254

    
1255
    if (qdict_haskey(device, "pci_bridge")) {
1256
        QDict *info;
1257

    
1258
        qdict = qdict_get_qdict(device, "pci_bridge");
1259

    
1260
        info = qdict_get_qdict(qdict, "bus");
1261
        monitor_printf(mon, "      BUS %" PRId64 ".\n",
1262
                            qdict_get_int(info, "number"));
1263
        monitor_printf(mon, "      secondary bus %" PRId64 ".\n",
1264
                            qdict_get_int(info, "secondary"));
1265
        monitor_printf(mon, "      subordinate bus %" PRId64 ".\n",
1266
                            qdict_get_int(info, "subordinate"));
1267

    
1268
        info = qdict_get_qdict(qdict, "io_range");
1269
        monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1270
                       qdict_get_int(info, "base"),
1271
                       qdict_get_int(info, "limit"));
1272

    
1273
        info = qdict_get_qdict(qdict, "memory_range");
1274
        monitor_printf(mon,
1275
                       "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1276
                       qdict_get_int(info, "base"),
1277
                       qdict_get_int(info, "limit"));
1278

    
1279
        info = qdict_get_qdict(qdict, "prefetchable_range");
1280
        monitor_printf(mon, "      prefetchable memory range "
1281
                       "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
1282
                       qdict_get_int(info, "base"),
1283
        qdict_get_int(info, "limit"));
1284
    }
1285

    
1286
    QLIST_FOREACH_ENTRY(qdict_get_qlist(device, "regions"), entry) {
1287
        qdict = qobject_to_qdict(qlist_entry_obj(entry));
1288
        monitor_printf(mon, "      BAR%d: ", (int) qdict_get_int(qdict, "bar"));
1289

    
1290
        addr = qdict_get_int(qdict, "address");
1291
        size = qdict_get_int(qdict, "size");
1292

    
1293
        if (!strcmp(qdict_get_str(qdict, "type"), "io")) {
1294
            monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1295
                                " [0x%04"FMT_PCIBUS"].\n",
1296
                                addr, addr + size - 1);
1297
        } else {
1298
            monitor_printf(mon, "%d bit%s memory at 0x%08"FMT_PCIBUS
1299
                               " [0x%08"FMT_PCIBUS"].\n",
1300
                                qdict_get_bool(qdict, "mem_type_64") ? 64 : 32,
1301
                                qdict_get_bool(qdict, "prefetch") ?
1302
                                " prefetchable" : "", addr, addr + size - 1);
1303
        }
1304
    }
1305

    
1306
    monitor_printf(mon, "      id \"%s\"\n", qdict_get_str(device, "qdev_id"));
1307

    
1308
    if (qdict_haskey(device, "pci_bridge")) {
1309
        qdict = qdict_get_qdict(device, "pci_bridge");
1310
        if (qdict_haskey(qdict, "devices")) {
1311
            QListEntry *dev;
1312
            QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1313
                pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1314
            }
1315
        }
1316
    }
1317
}
1318

    
1319
void do_pci_info_print(Monitor *mon, const QObject *data)
1320
{
1321
    QListEntry *bus, *dev;
1322

    
1323
    QLIST_FOREACH_ENTRY(qobject_to_qlist(data), bus) {
1324
        QDict *qdict = qobject_to_qdict(qlist_entry_obj(bus));
1325
        QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1326
            pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1327
        }
1328
    }
1329
}
1330

    
1331
static QObject *pci_get_dev_class(const PCIDevice *dev)
1332
{
1333
    int class;
1334
    const pci_class_desc *desc;
1335

    
1336
    class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1337
    desc = pci_class_descriptions;
1338
    while (desc->desc && class != desc->class)
1339
        desc++;
1340

    
1341
    if (desc->desc) {
1342
        return qobject_from_jsonf("{ 'desc': %s, 'class': %d }",
1343
                                  desc->desc, class);
1344
    } else {
1345
        return qobject_from_jsonf("{ 'class': %d }", class);
1346
    }
1347
}
1348

    
1349
static QObject *pci_get_dev_id(const PCIDevice *dev)
1350
{
1351
    return qobject_from_jsonf("{ 'device': %d, 'vendor': %d }",
1352
                              pci_get_word(dev->config + PCI_VENDOR_ID),
1353
                              pci_get_word(dev->config + PCI_DEVICE_ID));
1354
}
1355

    
1356
static QObject *pci_get_regions_list(const PCIDevice *dev)
1357
{
1358
    int i;
1359
    QList *regions_list;
1360

    
1361
    regions_list = qlist_new();
1362

    
1363
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
1364
        QObject *obj;
1365
        const PCIIORegion *r = &dev->io_regions[i];
1366

    
1367
        if (!r->size) {
1368
            continue;
1369
        }
1370

    
1371
        if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1372
            obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'io', "
1373
                                     "'address': %" PRId64 ", "
1374
                                     "'size': %" PRId64 " }",
1375
                                     i, r->addr, r->size);
1376
        } else {
1377
            int mem_type_64 = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64;
1378

    
1379
            obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'memory', "
1380
                                     "'mem_type_64': %i, 'prefetch': %i, "
1381
                                     "'address': %" PRId64 ", "
1382
                                     "'size': %" PRId64 " }",
1383
                                     i, mem_type_64,
1384
                                     r->type & PCI_BASE_ADDRESS_MEM_PREFETCH,
1385
                                     r->addr, r->size);
1386
        }
1387

    
1388
        qlist_append_obj(regions_list, obj);
1389
    }
1390

    
1391
    return QOBJECT(regions_list);
1392
}
1393

    
1394
static QObject *pci_get_devices_list(PCIBus *bus, int bus_num);
1395

    
1396
static QObject *pci_get_dev_dict(PCIDevice *dev, PCIBus *bus, int bus_num)
1397
{
1398
    uint8_t type;
1399
    QObject *obj;
1400

    
1401
    obj = qobject_from_jsonf("{ 'bus': %d, 'slot': %d, 'function': %d,"                                       "'class_info': %p, 'id': %p, 'regions': %p,"
1402
                              " 'qdev_id': %s }",
1403
                              bus_num,
1404
                              PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
1405
                              pci_get_dev_class(dev), pci_get_dev_id(dev),
1406
                              pci_get_regions_list(dev),
1407
                              dev->qdev.id ? dev->qdev.id : "");
1408

    
1409
    if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1410
        QDict *qdict = qobject_to_qdict(obj);
1411
        qdict_put(qdict, "irq", qint_from_int(dev->config[PCI_INTERRUPT_LINE]));
1412
    }
1413

    
1414
    type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1415
    if (type == PCI_HEADER_TYPE_BRIDGE) {
1416
        QDict *qdict;
1417
        QObject *pci_bridge;
1418

    
1419
        pci_bridge = qobject_from_jsonf("{ 'bus': "
1420
        "{ 'number': %d, 'secondary': %d, 'subordinate': %d }, "
1421
        "'io_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1422
        "'memory_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1423
        "'prefetchable_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "} }",
1424
        dev->config[PCI_PRIMARY_BUS], dev->config[PCI_SECONDARY_BUS],
1425
        dev->config[PCI_SUBORDINATE_BUS],
1426
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO),
1427
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO),
1428
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1429
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1430
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1431
                               PCI_BASE_ADDRESS_MEM_PREFETCH),
1432
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1433
                                PCI_BASE_ADDRESS_MEM_PREFETCH));
1434

    
1435
        if (dev->config[PCI_SECONDARY_BUS] != 0) {
1436
            PCIBus *child_bus = pci_find_bus(bus, dev->config[PCI_SECONDARY_BUS]);
1437

    
1438
            if (child_bus) {
1439
                qdict = qobject_to_qdict(pci_bridge);
1440
                qdict_put_obj(qdict, "devices",
1441
                              pci_get_devices_list(child_bus,
1442
                                                   dev->config[PCI_SECONDARY_BUS]));
1443
            }
1444
        }
1445
        qdict = qobject_to_qdict(obj);
1446
        qdict_put_obj(qdict, "pci_bridge", pci_bridge);
1447
    }
1448

    
1449
    return obj;
1450
}
1451

    
1452
static QObject *pci_get_devices_list(PCIBus *bus, int bus_num)
1453
{
1454
    int devfn;
1455
    PCIDevice *dev;
1456
    QList *dev_list;
1457

    
1458
    dev_list = qlist_new();
1459

    
1460
    for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1461
        dev = bus->devices[devfn];
1462
        if (dev) {
1463
            qlist_append_obj(dev_list, pci_get_dev_dict(dev, bus, bus_num));
1464
        }
1465
    }
1466

    
1467
    return QOBJECT(dev_list);
1468
}
1469

    
1470
static QObject *pci_get_bus_dict(PCIBus *bus, int bus_num)
1471
{
1472
    bus = pci_find_bus(bus, bus_num);
1473
    if (bus) {
1474
        return qobject_from_jsonf("{ 'bus': %d, 'devices': %p }",
1475
                                  bus_num, pci_get_devices_list(bus, bus_num));
1476
    }
1477

    
1478
    return NULL;
1479
}
1480

    
1481
void do_pci_info(Monitor *mon, QObject **ret_data)
1482
{
1483
    QList *bus_list;
1484
    struct PCIHostBus *host;
1485

    
1486
    bus_list = qlist_new();
1487

    
1488
    QLIST_FOREACH(host, &host_buses, next) {
1489
        QObject *obj = pci_get_bus_dict(host->bus, 0);
1490
        if (obj) {
1491
            qlist_append_obj(bus_list, obj);
1492
        }
1493
    }
1494

    
1495
    *ret_data = QOBJECT(bus_list);
1496
}
1497

    
1498
static const char * const pci_nic_models[] = {
1499
    "ne2k_pci",
1500
    "i82551",
1501
    "i82557b",
1502
    "i82559er",
1503
    "rtl8139",
1504
    "e1000",
1505
    "pcnet",
1506
    "virtio",
1507
    NULL
1508
};
1509

    
1510
static const char * const pci_nic_names[] = {
1511
    "ne2k_pci",
1512
    "i82551",
1513
    "i82557b",
1514
    "i82559er",
1515
    "rtl8139",
1516
    "e1000",
1517
    "pcnet",
1518
    "virtio-net-pci",
1519
    NULL
1520
};
1521

    
1522
/* Initialize a PCI NIC.  */
1523
/* FIXME callers should check for failure, but don't */
1524
PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1525
                        const char *default_devaddr)
1526
{
1527
    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1528
    PCIBus *bus;
1529
    int devfn;
1530
    PCIDevice *pci_dev;
1531
    DeviceState *dev;
1532
    int i;
1533

    
1534
    i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1535
    if (i < 0)
1536
        return NULL;
1537

    
1538
    bus = pci_get_bus_devfn(&devfn, devaddr);
1539
    if (!bus) {
1540
        error_report("Invalid PCI device address %s for device %s",
1541
                     devaddr, pci_nic_names[i]);
1542
        return NULL;
1543
    }
1544

    
1545
    pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1546
    dev = &pci_dev->qdev;
1547
    qdev_set_nic_properties(dev, nd);
1548
    if (qdev_init(dev) < 0)
1549
        return NULL;
1550
    return pci_dev;
1551
}
1552

    
1553
PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1554
                               const char *default_devaddr)
1555
{
1556
    PCIDevice *res;
1557

    
1558
    if (qemu_show_nic_models(nd->model, pci_nic_models))
1559
        exit(0);
1560

    
1561
    res = pci_nic_init(nd, default_model, default_devaddr);
1562
    if (!res)
1563
        exit(1);
1564
    return res;
1565
}
1566

    
1567
static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1568
{
1569
    pci_update_mappings(d);
1570
}
1571

    
1572
void pci_bridge_update_mappings(PCIBus *b)
1573
{
1574
    PCIBus *child;
1575

    
1576
    pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1577

    
1578
    QLIST_FOREACH(child, &b->child, sibling) {
1579
        pci_bridge_update_mappings(child);
1580
    }
1581
}
1582

    
1583
/* Whether a given bus number is in range of the secondary
1584
 * bus of the given bridge device. */
1585
static bool pci_secondary_bus_in_range(PCIDevice *dev, int bus_num)
1586
{
1587
    return !(pci_get_word(dev->config + PCI_BRIDGE_CONTROL) &
1588
             PCI_BRIDGE_CTL_BUS_RESET) /* Don't walk the bus if it's reset. */ &&
1589
        dev->config[PCI_SECONDARY_BUS] < bus_num &&
1590
        bus_num <= dev->config[PCI_SUBORDINATE_BUS];
1591
}
1592

    
1593
PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1594
{
1595
    PCIBus *sec;
1596

    
1597
    if (!bus) {
1598
        return NULL;
1599
    }
1600

    
1601
    if (pci_bus_num(bus) == bus_num) {
1602
        return bus;
1603
    }
1604

    
1605
    /* Consider all bus numbers in range for the host pci bridge. */
1606
    if (bus->parent_dev &&
1607
        !pci_secondary_bus_in_range(bus->parent_dev, bus_num)) {
1608
        return NULL;
1609
    }
1610

    
1611
    /* try child bus */
1612
    for (; bus; bus = sec) {
1613
        QLIST_FOREACH(sec, &bus->child, sibling) {
1614
            assert(sec->parent_dev);
1615
            if (sec->parent_dev->config[PCI_SECONDARY_BUS] == bus_num) {
1616
                return sec;
1617
            }
1618
            if (pci_secondary_bus_in_range(sec->parent_dev, bus_num)) {
1619
                break;
1620
            }
1621
        }
1622
    }
1623

    
1624
    return NULL;
1625
}
1626

    
1627
PCIDevice *pci_find_device(PCIBus *bus, int bus_num, uint8_t devfn)
1628
{
1629
    bus = pci_find_bus(bus, bus_num);
1630

    
1631
    if (!bus)
1632
        return NULL;
1633

    
1634
    return bus->devices[devfn];
1635
}
1636

    
1637
static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1638
{
1639
    PCIDevice *pci_dev = (PCIDevice *)qdev;
1640
    PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1641
    PCIBus *bus;
1642
    int rc;
1643
    bool is_default_rom;
1644

    
1645
    /* initialize cap_present for pci_is_express() and pci_config_size() */
1646
    if (info->is_express) {
1647
        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1648
    }
1649

    
1650
    bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1651
    pci_dev = do_pci_register_device(pci_dev, bus, base->name,
1652
                                     pci_dev->devfn, info);
1653
    if (pci_dev == NULL)
1654
        return -1;
1655
    if (qdev->hotplugged && info->no_hotplug) {
1656
        qerror_report(QERR_DEVICE_NO_HOTPLUG, info->qdev.name);
1657
        do_pci_unregister_device(pci_dev);
1658
        return -1;
1659
    }
1660
    if (info->init) {
1661
        rc = info->init(pci_dev);
1662
        if (rc != 0) {
1663
            do_pci_unregister_device(pci_dev);
1664
            return rc;
1665
        }
1666
    }
1667

    
1668
    /* rom loading */
1669
    is_default_rom = false;
1670
    if (pci_dev->romfile == NULL && info->romfile != NULL) {
1671
        pci_dev->romfile = g_strdup(info->romfile);
1672
        is_default_rom = true;
1673
    }
1674
    pci_add_option_rom(pci_dev, is_default_rom);
1675

    
1676
    if (bus->hotplug) {
1677
        /* Let buses differentiate between hotplug and when device is
1678
         * enabled during qemu machine creation. */
1679
        rc = bus->hotplug(bus->hotplug_qdev, pci_dev,
1680
                          qdev->hotplugged ? PCI_HOTPLUG_ENABLED:
1681
                          PCI_COLDPLUG_ENABLED);
1682
        if (rc != 0) {
1683
            int r = pci_unregister_device(&pci_dev->qdev);
1684
            assert(!r);
1685
            return rc;
1686
        }
1687
    }
1688
    return 0;
1689
}
1690

    
1691
static int pci_unplug_device(DeviceState *qdev)
1692
{
1693
    PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1694
    PCIDeviceInfo *info = container_of(qdev->info, PCIDeviceInfo, qdev);
1695

    
1696
    if (info->no_hotplug) {
1697
        qerror_report(QERR_DEVICE_NO_HOTPLUG, info->qdev.name);
1698
        return -1;
1699
    }
1700
    return dev->bus->hotplug(dev->bus->hotplug_qdev, dev,
1701
                             PCI_HOTPLUG_DISABLED);
1702
}
1703

    
1704
void pci_qdev_register(PCIDeviceInfo *info)
1705
{
1706
    info->qdev.init = pci_qdev_init;
1707
    info->qdev.unplug = pci_unplug_device;
1708
    info->qdev.exit = pci_unregister_device;
1709
    info->qdev.bus_info = &pci_bus_info;
1710
    qdev_register(&info->qdev);
1711
}
1712

    
1713
void pci_qdev_register_many(PCIDeviceInfo *info)
1714
{
1715
    while (info->qdev.name) {
1716
        pci_qdev_register(info);
1717
        info++;
1718
    }
1719
}
1720

    
1721
PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1722
                                    const char *name)
1723
{
1724
    DeviceState *dev;
1725

    
1726
    dev = qdev_create(&bus->qbus, name);
1727
    qdev_prop_set_uint32(dev, "addr", devfn);
1728
    qdev_prop_set_bit(dev, "multifunction", multifunction);
1729
    return DO_UPCAST(PCIDevice, qdev, dev);
1730
}
1731

    
1732
PCIDevice *pci_try_create_multifunction(PCIBus *bus, int devfn,
1733
                                        bool multifunction,
1734
                                        const char *name)
1735
{
1736
    DeviceState *dev;
1737

    
1738
    dev = qdev_try_create(&bus->qbus, name);
1739
    if (!dev) {
1740
        return NULL;
1741
    }
1742
    qdev_prop_set_uint32(dev, "addr", devfn);
1743
    qdev_prop_set_bit(dev, "multifunction", multifunction);
1744
    return DO_UPCAST(PCIDevice, qdev, dev);
1745
}
1746

    
1747
PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1748
                                           bool multifunction,
1749
                                           const char *name)
1750
{
1751
    PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1752
    qdev_init_nofail(&dev->qdev);
1753
    return dev;
1754
}
1755

    
1756
PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1757
{
1758
    return pci_create_multifunction(bus, devfn, false, name);
1759
}
1760

    
1761
PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1762
{
1763
    return pci_create_simple_multifunction(bus, devfn, false, name);
1764
}
1765

    
1766
PCIDevice *pci_try_create(PCIBus *bus, int devfn, const char *name)
1767
{
1768
    return pci_try_create_multifunction(bus, devfn, false, name);
1769
}
1770

    
1771
static int pci_find_space(PCIDevice *pdev, uint8_t size)
1772
{
1773
    int config_size = pci_config_size(pdev);
1774
    int offset = PCI_CONFIG_HEADER_SIZE;
1775
    int i;
1776
    for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1777
        if (pdev->used[i])
1778
            offset = i + 1;
1779
        else if (i - offset + 1 == size)
1780
            return offset;
1781
    return 0;
1782
}
1783

    
1784
static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1785
                                        uint8_t *prev_p)
1786
{
1787
    uint8_t next, prev;
1788

    
1789
    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1790
        return 0;
1791

    
1792
    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1793
         prev = next + PCI_CAP_LIST_NEXT)
1794
        if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1795
            break;
1796

    
1797
    if (prev_p)
1798
        *prev_p = prev;
1799
    return next;
1800
}
1801

    
1802
static uint8_t pci_find_capability_at_offset(PCIDevice *pdev, uint8_t offset)
1803
{
1804
    uint8_t next, prev, found = 0;
1805

    
1806
    if (!(pdev->used[offset])) {
1807
        return 0;
1808
    }
1809

    
1810
    assert(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST);
1811

    
1812
    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1813
         prev = next + PCI_CAP_LIST_NEXT) {
1814
        if (next <= offset && next > found) {
1815
            found = next;
1816
        }
1817
    }
1818
    return found;
1819
}
1820

    
1821
/* Patch the PCI vendor and device ids in a PCI rom image if necessary.
1822
   This is needed for an option rom which is used for more than one device. */
1823
static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
1824
{
1825
    uint16_t vendor_id;
1826
    uint16_t device_id;
1827
    uint16_t rom_vendor_id;
1828
    uint16_t rom_device_id;
1829
    uint16_t rom_magic;
1830
    uint16_t pcir_offset;
1831
    uint8_t checksum;
1832

    
1833
    /* Words in rom data are little endian (like in PCI configuration),
1834
       so they can be read / written with pci_get_word / pci_set_word. */
1835

    
1836
    /* Only a valid rom will be patched. */
1837
    rom_magic = pci_get_word(ptr);
1838
    if (rom_magic != 0xaa55) {
1839
        PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
1840
        return;
1841
    }
1842
    pcir_offset = pci_get_word(ptr + 0x18);
1843
    if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
1844
        PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
1845
        return;
1846
    }
1847

    
1848
    vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
1849
    device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
1850
    rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
1851
    rom_device_id = pci_get_word(ptr + pcir_offset + 6);
1852

    
1853
    PCI_DPRINTF("%s: ROM id %04x%04x / PCI id %04x%04x\n", pdev->romfile,
1854
                vendor_id, device_id, rom_vendor_id, rom_device_id);
1855

    
1856
    checksum = ptr[6];
1857

    
1858
    if (vendor_id != rom_vendor_id) {
1859
        /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
1860
        checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
1861
        checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
1862
        PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1863
        ptr[6] = checksum;
1864
        pci_set_word(ptr + pcir_offset + 4, vendor_id);
1865
    }
1866

    
1867
    if (device_id != rom_device_id) {
1868
        /* Patch device id and checksum (at offset 6 for etherboot roms). */
1869
        checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
1870
        checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
1871
        PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1872
        ptr[6] = checksum;
1873
        pci_set_word(ptr + pcir_offset + 6, device_id);
1874
    }
1875
}
1876

    
1877
/* Add an option rom for the device */
1878
static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom)
1879
{
1880
    int size;
1881
    char *path;
1882
    void *ptr;
1883
    char name[32];
1884

    
1885
    if (!pdev->romfile)
1886
        return 0;
1887
    if (strlen(pdev->romfile) == 0)
1888
        return 0;
1889

    
1890
    if (!pdev->rom_bar) {
1891
        /*
1892
         * Load rom via fw_cfg instead of creating a rom bar,
1893
         * for 0.11 compatibility.
1894
         */
1895
        int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
1896
        if (class == 0x0300) {
1897
            rom_add_vga(pdev->romfile);
1898
        } else {
1899
            rom_add_option(pdev->romfile, -1);
1900
        }
1901
        return 0;
1902
    }
1903

    
1904
    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1905
    if (path == NULL) {
1906
        path = g_strdup(pdev->romfile);
1907
    }
1908

    
1909
    size = get_image_size(path);
1910
    if (size < 0) {
1911
        error_report("%s: failed to find romfile \"%s\"",
1912
                     __FUNCTION__, pdev->romfile);
1913
        g_free(path);
1914
        return -1;
1915
    }
1916
    if (size & (size - 1)) {
1917
        size = 1 << qemu_fls(size);
1918
    }
1919

    
1920
    if (pdev->qdev.info->vmsd)
1921
        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);
1922
    else
1923
        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);
1924
    pdev->has_rom = true;
1925
    memory_region_init_ram(&pdev->rom, &pdev->qdev, name, size);
1926
    ptr = memory_region_get_ram_ptr(&pdev->rom);
1927
    load_image(path, ptr);
1928
    g_free(path);
1929

    
1930
    if (is_default_rom) {
1931
        /* Only the default rom images will be patched (if needed). */
1932
        pci_patch_ids(pdev, ptr, size);
1933
    }
1934

    
1935
    qemu_put_ram_ptr(ptr);
1936

    
1937
    pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);
1938

    
1939
    return 0;
1940
}
1941

    
1942
static void pci_del_option_rom(PCIDevice *pdev)
1943
{
1944
    if (!pdev->has_rom)
1945
        return;
1946

    
1947
    memory_region_destroy(&pdev->rom);
1948
    pdev->has_rom = false;
1949
}
1950

    
1951
/*
1952
 * if !offset
1953
 * Reserve space and add capability to the linked list in pci config space
1954
 *
1955
 * if offset = 0,
1956
 * Find and reserve space and add capability to the linked list
1957
 * in pci config space */
1958
int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
1959
                       uint8_t offset, uint8_t size)
1960
{
1961
    uint8_t *config;
1962
    int i, overlapping_cap;
1963

    
1964
    if (!offset) {
1965
        offset = pci_find_space(pdev, size);
1966
        if (!offset) {
1967
            return -ENOSPC;
1968
        }
1969
    } else {
1970
        /* Verify that capabilities don't overlap.  Note: device assignment
1971
         * depends on this check to verify that the device is not broken.
1972
         * Should never trigger for emulated devices, but it's helpful
1973
         * for debugging these. */
1974
        for (i = offset; i < offset + size; i++) {
1975
            overlapping_cap = pci_find_capability_at_offset(pdev, i);
1976
            if (overlapping_cap) {
1977
                fprintf(stderr, "ERROR: %04x:%02x:%02x.%x "
1978
                        "Attempt to add PCI capability %x at offset "
1979
                        "%x overlaps existing capability %x at offset %x\n",
1980
                        pci_find_domain(pdev->bus), pci_bus_num(pdev->bus),
1981
                        PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),
1982
                        cap_id, offset, overlapping_cap, i);
1983
                return -EINVAL;
1984
            }
1985
        }
1986
    }
1987

    
1988
    config = pdev->config + offset;
1989
    config[PCI_CAP_LIST_ID] = cap_id;
1990
    config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1991
    pdev->config[PCI_CAPABILITY_LIST] = offset;
1992
    pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1993
    memset(pdev->used + offset, 0xFF, size);
1994
    /* Make capability read-only by default */
1995
    memset(pdev->wmask + offset, 0, size);
1996
    /* Check capability by default */
1997
    memset(pdev->cmask + offset, 0xFF, size);
1998
    return offset;
1999
}
2000

    
2001
/* Unlink capability from the pci config space. */
2002
void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
2003
{
2004
    uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
2005
    if (!offset)
2006
        return;
2007
    pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
2008
    /* Make capability writable again */
2009
    memset(pdev->wmask + offset, 0xff, size);
2010
    memset(pdev->w1cmask + offset, 0, size);
2011
    /* Clear cmask as device-specific registers can't be checked */
2012
    memset(pdev->cmask + offset, 0, size);
2013
    memset(pdev->used + offset, 0, size);
2014

    
2015
    if (!pdev->config[PCI_CAPABILITY_LIST])
2016
        pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
2017
}
2018

    
2019
/* Reserve space for capability at a known offset (to call after load). */
2020
void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
2021
{
2022
    memset(pdev->used + offset, 0xff, size);
2023
}
2024

    
2025
uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
2026
{
2027
    return pci_find_capability_list(pdev, cap_id, NULL);
2028
}
2029

    
2030
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
2031
{
2032
    PCIDevice *d = (PCIDevice *)dev;
2033
    const pci_class_desc *desc;
2034
    char ctxt[64];
2035
    PCIIORegion *r;
2036
    int i, class;
2037

    
2038
    class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2039
    desc = pci_class_descriptions;
2040
    while (desc->desc && class != desc->class)
2041
        desc++;
2042
    if (desc->desc) {
2043
        snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
2044
    } else {
2045
        snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
2046
    }
2047

    
2048
    monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
2049
                   "pci id %04x:%04x (sub %04x:%04x)\n",
2050
                   indent, "", ctxt, pci_bus_num(d->bus),
2051
                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
2052
                   pci_get_word(d->config + PCI_VENDOR_ID),
2053
                   pci_get_word(d->config + PCI_DEVICE_ID),
2054
                   pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
2055
                   pci_get_word(d->config + PCI_SUBSYSTEM_ID));
2056
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
2057
        r = &d->io_regions[i];
2058
        if (!r->size)
2059
            continue;
2060
        monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
2061
                       " [0x%"FMT_PCIBUS"]\n",
2062
                       indent, "",
2063
                       i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
2064
                       r->addr, r->addr + r->size - 1);
2065
    }
2066
}
2067

    
2068
static char *pci_dev_fw_name(DeviceState *dev, char *buf, int len)
2069
{
2070
    PCIDevice *d = (PCIDevice *)dev;
2071
    const char *name = NULL;
2072
    const pci_class_desc *desc =  pci_class_descriptions;
2073
    int class = pci_get_word(d->config + PCI_CLASS_DEVICE);
2074

    
2075
    while (desc->desc &&
2076
          (class & ~desc->fw_ign_bits) !=
2077
          (desc->class & ~desc->fw_ign_bits)) {
2078
        desc++;
2079
    }
2080

    
2081
    if (desc->desc) {
2082
        name = desc->fw_name;
2083
    }
2084

    
2085
    if (name) {
2086
        pstrcpy(buf, len, name);
2087
    } else {
2088
        snprintf(buf, len, "pci%04x,%04x",
2089
                 pci_get_word(d->config + PCI_VENDOR_ID),
2090
                 pci_get_word(d->config + PCI_DEVICE_ID));
2091
    }
2092

    
2093
    return buf;
2094
}
2095

    
2096
static char *pcibus_get_fw_dev_path(DeviceState *dev)
2097
{
2098
    PCIDevice *d = (PCIDevice *)dev;
2099
    char path[50], name[33];
2100
    int off;
2101

    
2102
    off = snprintf(path, sizeof(path), "%s@%x",
2103
                   pci_dev_fw_name(dev, name, sizeof name),
2104
                   PCI_SLOT(d->devfn));
2105
    if (PCI_FUNC(d->devfn))
2106
        snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));
2107
    return strdup(path);
2108
}
2109

    
2110
static char *pcibus_get_dev_path(DeviceState *dev)
2111
{
2112
    PCIDevice *d = container_of(dev, PCIDevice, qdev);
2113
    PCIDevice *t;
2114
    int slot_depth;
2115
    /* Path format: Domain:00:Slot.Function:Slot.Function....:Slot.Function.
2116
     * 00 is added here to make this format compatible with
2117
     * domain:Bus:Slot.Func for systems without nested PCI bridges.
2118
     * Slot.Function list specifies the slot and function numbers for all
2119
     * devices on the path from root to the specific device. */
2120
    char domain[] = "DDDD:00";
2121
    char slot[] = ":SS.F";
2122
    int domain_len = sizeof domain - 1 /* For '\0' */;
2123
    int slot_len = sizeof slot - 1 /* For '\0' */;
2124
    int path_len;
2125
    char *path, *p;
2126
    int s;
2127

    
2128
    /* Calculate # of slots on path between device and root. */;
2129
    slot_depth = 0;
2130
    for (t = d; t; t = t->bus->parent_dev) {
2131
        ++slot_depth;
2132
    }
2133

    
2134
    path_len = domain_len + slot_len * slot_depth;
2135

    
2136
    /* Allocate memory, fill in the terminating null byte. */
2137
    path = g_malloc(path_len + 1 /* For '\0' */);
2138
    path[path_len] = '\0';
2139

    
2140
    /* First field is the domain. */
2141
    s = snprintf(domain, sizeof domain, "%04x:00", pci_find_domain(d->bus));
2142
    assert(s == domain_len);
2143
    memcpy(path, domain, domain_len);
2144

    
2145
    /* Fill in slot numbers. We walk up from device to root, so need to print
2146
     * them in the reverse order, last to first. */
2147
    p = path + path_len;
2148
    for (t = d; t; t = t->bus->parent_dev) {
2149
        p -= slot_len;
2150
        s = snprintf(slot, sizeof slot, ":%02x.%x",
2151
                     PCI_SLOT(t->devfn), PCI_FUNC(t->devfn));
2152
        assert(s == slot_len);
2153
        memcpy(p, slot, slot_len);
2154
    }
2155

    
2156
    return path;
2157
}
2158

    
2159
static int pci_qdev_find_recursive(PCIBus *bus,
2160
                                   const char *id, PCIDevice **pdev)
2161
{
2162
    DeviceState *qdev = qdev_find_recursive(&bus->qbus, id);
2163
    if (!qdev) {
2164
        return -ENODEV;
2165
    }
2166

    
2167
    /* roughly check if given qdev is pci device */
2168
    if (qdev->info->init == &pci_qdev_init &&
2169
        qdev->parent_bus->info == &pci_bus_info) {
2170
        *pdev = DO_UPCAST(PCIDevice, qdev, qdev);
2171
        return 0;
2172
    }
2173
    return -EINVAL;
2174
}
2175

    
2176
int pci_qdev_find_device(const char *id, PCIDevice **pdev)
2177
{
2178
    struct PCIHostBus *host;
2179
    int rc = -ENODEV;
2180

    
2181
    QLIST_FOREACH(host, &host_buses, next) {
2182
        int tmp = pci_qdev_find_recursive(host->bus, id, pdev);
2183
        if (!tmp) {
2184
            rc = 0;
2185
            break;
2186
        }
2187
        if (tmp != -ENODEV) {
2188
            rc = tmp;
2189
        }
2190
    }
2191

    
2192
    return rc;
2193
}
2194

    
2195
MemoryRegion *pci_address_space(PCIDevice *dev)
2196
{
2197
    return dev->bus->address_space_mem;
2198
}