Statistics
| Branch: | Revision:

root / hw / pci.c @ ab85ceb1

History | View | Annotate | Download (58.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 "msix.h"
29
#include "msi.h"
30
#include "monitor.h"
31
#include "net.h"
32
#include "sysemu.h"
33
#include "loader.h"
34
#include "qemu-objects.h"
35
#include "range.h"
36

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

    
44
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
45
static char *pcibus_get_dev_path(DeviceState *dev);
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
    .props      = (Property[]) {
53
        DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
54
        DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
55
        DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
56
        DEFINE_PROP_BIT("multifunction", PCIDevice, cap_present,
57
                        QEMU_PCI_CAP_MULTIFUNCTION_BITNR, false),
58
        DEFINE_PROP_END_OF_LIST()
59
    }
60
};
61

    
62
static void pci_update_mappings(PCIDevice *d);
63
static void pci_set_irq(void *opaque, int irq_num, int level);
64
static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom);
65
static void pci_del_option_rom(PCIDevice *pdev);
66

    
67
static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
68
static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
69

    
70
struct PCIHostBus {
71
    int domain;
72
    struct PCIBus *bus;
73
    QLIST_ENTRY(PCIHostBus) next;
74
};
75
static QLIST_HEAD(, PCIHostBus) host_buses;
76

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

    
89
static int pci_bar(PCIDevice *d, int reg)
90
{
91
    uint8_t type;
92

    
93
    if (reg != PCI_ROM_SLOT)
94
        return PCI_BASE_ADDRESS_0 + reg * 4;
95

    
96
    type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
97
    return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
98
}
99

    
100
static inline int pci_irq_state(PCIDevice *d, int irq_num)
101
{
102
        return (d->irq_state >> irq_num) & 0x1;
103
}
104

    
105
static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
106
{
107
        d->irq_state &= ~(0x1 << irq_num);
108
        d->irq_state |= level << irq_num;
109
}
110

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

    
125
/* Update interrupt status bit in config space on interrupt
126
 * state change. */
127
static void pci_update_irq_status(PCIDevice *dev)
128
{
129
    if (dev->irq_state) {
130
        dev->config[PCI_STATUS] |= PCI_STATUS_INTERRUPT;
131
    } else {
132
        dev->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
133
    }
134
}
135

    
136
static void pci_device_reset(PCIDevice *dev)
137
{
138
    int r;
139

    
140
    dev->irq_state = 0;
141
    pci_update_irq_status(dev);
142
    /* Clear all writeable bits */
143
    pci_word_test_and_clear_mask(dev->config + PCI_COMMAND,
144
                                 pci_get_word(dev->wmask + PCI_COMMAND) |
145
                                 pci_get_word(dev->w1cmask + PCI_COMMAND));
146
    pci_word_test_and_clear_mask(dev->config + PCI_STATUS,
147
                                 pci_get_word(dev->wmask + PCI_STATUS) |
148
                                 pci_get_word(dev->w1cmask + PCI_STATUS));
149
    dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
150
    dev->config[PCI_INTERRUPT_LINE] = 0x0;
151
    for (r = 0; r < PCI_NUM_REGIONS; ++r) {
152
        PCIIORegion *region = &dev->io_regions[r];
153
        if (!region->size) {
154
            continue;
155
        }
156

    
157
        if (!(region->type & PCI_BASE_ADDRESS_SPACE_IO) &&
158
            region->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
159
            pci_set_quad(dev->config + pci_bar(dev, r), region->type);
160
        } else {
161
            pci_set_long(dev->config + pci_bar(dev, r), region->type);
162
        }
163
    }
164
    pci_update_mappings(dev);
165
}
166

    
167
static void pci_bus_reset(void *opaque)
168
{
169
    PCIBus *bus = opaque;
170
    int i;
171

    
172
    for (i = 0; i < bus->nirq; i++) {
173
        bus->irq_count[i] = 0;
174
    }
175
    for (i = 0; i < ARRAY_SIZE(bus->devices); ++i) {
176
        if (bus->devices[i]) {
177
            pci_device_reset(bus->devices[i]);
178
        }
179
    }
180
}
181

    
182
static void pci_host_bus_register(int domain, PCIBus *bus)
183
{
184
    struct PCIHostBus *host;
185
    host = qemu_mallocz(sizeof(*host));
186
    host->domain = domain;
187
    host->bus = bus;
188
    QLIST_INSERT_HEAD(&host_buses, host, next);
189
}
190

    
191
PCIBus *pci_find_root_bus(int domain)
192
{
193
    struct PCIHostBus *host;
194

    
195
    QLIST_FOREACH(host, &host_buses, next) {
196
        if (host->domain == domain) {
197
            return host->bus;
198
        }
199
    }
200

    
201
    return NULL;
202
}
203

    
204
int pci_find_domain(const PCIBus *bus)
205
{
206
    PCIDevice *d;
207
    struct PCIHostBus *host;
208

    
209
    /* obtain root bus */
210
    while ((d = bus->parent_dev) != NULL) {
211
        bus = d->bus;
212
    }
213

    
214
    QLIST_FOREACH(host, &host_buses, next) {
215
        if (host->bus == bus) {
216
            return host->domain;
217
        }
218
    }
219

    
220
    abort();    /* should not be reached */
221
    return -1;
222
}
223

    
224
void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
225
                         const char *name, int devfn_min)
226
{
227
    qbus_create_inplace(&bus->qbus, &pci_bus_info, parent, name);
228
    assert(PCI_FUNC(devfn_min) == 0);
229
    bus->devfn_min = devfn_min;
230

    
231
    /* host bridge */
232
    QLIST_INIT(&bus->child);
233
    pci_host_bus_register(0, bus); /* for now only pci domain 0 is supported */
234

    
235
    vmstate_register(NULL, -1, &vmstate_pcibus, bus);
236
    qemu_register_reset(pci_bus_reset, bus);
237
}
238

    
239
PCIBus *pci_bus_new(DeviceState *parent, const char *name, int devfn_min)
240
{
241
    PCIBus *bus;
242

    
243
    bus = qemu_mallocz(sizeof(*bus));
244
    bus->qbus.qdev_allocated = 1;
245
    pci_bus_new_inplace(bus, parent, name, devfn_min);
246
    return bus;
247
}
248

    
249
void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
250
                  void *irq_opaque, int nirq)
251
{
252
    bus->set_irq = set_irq;
253
    bus->map_irq = map_irq;
254
    bus->irq_opaque = irq_opaque;
255
    bus->nirq = nirq;
256
    bus->irq_count = qemu_mallocz(nirq * sizeof(bus->irq_count[0]));
257
}
258

    
259
void pci_bus_hotplug(PCIBus *bus, pci_hotplug_fn hotplug, DeviceState *qdev)
260
{
261
    bus->qbus.allow_hotplug = 1;
262
    bus->hotplug = hotplug;
263
    bus->hotplug_qdev = qdev;
264
}
265

    
266
void pci_bus_set_mem_base(PCIBus *bus, target_phys_addr_t base)
267
{
268
    bus->mem_base = base;
269
}
270

    
271
PCIBus *pci_register_bus(DeviceState *parent, const char *name,
272
                         pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
273
                         void *irq_opaque, int devfn_min, int nirq)
274
{
275
    PCIBus *bus;
276

    
277
    bus = pci_bus_new(parent, name, devfn_min);
278
    pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
279
    return bus;
280
}
281

    
282
int pci_bus_num(PCIBus *s)
283
{
284
    if (!s->parent_dev)
285
        return 0;       /* pci host bridge */
286
    return s->parent_dev->config[PCI_SECONDARY_BUS];
287
}
288

    
289
static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
290
{
291
    PCIDevice *s = container_of(pv, PCIDevice, config);
292
    uint8_t *config;
293
    int i;
294

    
295
    assert(size == pci_config_size(s));
296
    config = qemu_malloc(size);
297

    
298
    qemu_get_buffer(f, config, size);
299
    for (i = 0; i < size; ++i) {
300
        if ((config[i] ^ s->config[i]) &
301
            s->cmask[i] & ~s->wmask[i] & ~s->w1cmask[i]) {
302
            qemu_free(config);
303
            return -EINVAL;
304
        }
305
    }
306
    memcpy(s->config, config, size);
307

    
308
    pci_update_mappings(s);
309

    
310
    qemu_free(config);
311
    return 0;
312
}
313

    
314
/* just put buffer */
315
static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
316
{
317
    const uint8_t **v = pv;
318
    assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
319
    qemu_put_buffer(f, *v, size);
320
}
321

    
322
static VMStateInfo vmstate_info_pci_config = {
323
    .name = "pci config",
324
    .get  = get_pci_config_device,
325
    .put  = put_pci_config_device,
326
};
327

    
328
static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
329
{
330
    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
331
    uint32_t irq_state[PCI_NUM_PINS];
332
    int i;
333
    for (i = 0; i < PCI_NUM_PINS; ++i) {
334
        irq_state[i] = qemu_get_be32(f);
335
        if (irq_state[i] != 0x1 && irq_state[i] != 0) {
336
            fprintf(stderr, "irq state %d: must be 0 or 1.\n",
337
                    irq_state[i]);
338
            return -EINVAL;
339
        }
340
    }
341

    
342
    for (i = 0; i < PCI_NUM_PINS; ++i) {
343
        pci_set_irq_state(s, i, irq_state[i]);
344
    }
345

    
346
    return 0;
347
}
348

    
349
static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
350
{
351
    int i;
352
    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
353

    
354
    for (i = 0; i < PCI_NUM_PINS; ++i) {
355
        qemu_put_be32(f, pci_irq_state(s, i));
356
    }
357
}
358

    
359
static VMStateInfo vmstate_info_pci_irq_state = {
360
    .name = "pci irq state",
361
    .get  = get_pci_irq_state,
362
    .put  = put_pci_irq_state,
363
};
364

    
365
const VMStateDescription vmstate_pci_device = {
366
    .name = "PCIDevice",
367
    .version_id = 2,
368
    .minimum_version_id = 1,
369
    .minimum_version_id_old = 1,
370
    .fields      = (VMStateField []) {
371
        VMSTATE_INT32_LE(version_id, PCIDevice),
372
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
373
                                   vmstate_info_pci_config,
374
                                   PCI_CONFIG_SPACE_SIZE),
375
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
376
                                   vmstate_info_pci_irq_state,
377
                                   PCI_NUM_PINS * sizeof(int32_t)),
378
        VMSTATE_END_OF_LIST()
379
    }
380
};
381

    
382
const VMStateDescription vmstate_pcie_device = {
383
    .name = "PCIDevice",
384
    .version_id = 2,
385
    .minimum_version_id = 1,
386
    .minimum_version_id_old = 1,
387
    .fields      = (VMStateField []) {
388
        VMSTATE_INT32_LE(version_id, PCIDevice),
389
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
390
                                   vmstate_info_pci_config,
391
                                   PCIE_CONFIG_SPACE_SIZE),
392
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
393
                                   vmstate_info_pci_irq_state,
394
                                   PCI_NUM_PINS * sizeof(int32_t)),
395
        VMSTATE_END_OF_LIST()
396
    }
397
};
398

    
399
static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
400
{
401
    return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
402
}
403

    
404
void pci_device_save(PCIDevice *s, QEMUFile *f)
405
{
406
    /* Clear interrupt status bit: it is implicit
407
     * in irq_state which we are saving.
408
     * This makes us compatible with old devices
409
     * which never set or clear this bit. */
410
    s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
411
    vmstate_save_state(f, pci_get_vmstate(s), s);
412
    /* Restore the interrupt status bit. */
413
    pci_update_irq_status(s);
414
}
415

    
416
int pci_device_load(PCIDevice *s, QEMUFile *f)
417
{
418
    int ret;
419
    ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
420
    /* Restore the interrupt status bit. */
421
    pci_update_irq_status(s);
422
    return ret;
423
}
424

    
425
static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
426
{
427
    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
428
                 pci_default_sub_vendor_id);
429
    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
430
                 pci_default_sub_device_id);
431
}
432

    
433
/*
434
 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error if funcp == NULL
435
 *       [[<domain>:]<bus>:]<slot>.<func>, return -1 on error
436
 */
437
int pci_parse_devaddr(const char *addr, int *domp, int *busp,
438
                      unsigned int *slotp, unsigned int *funcp)
439
{
440
    const char *p;
441
    char *e;
442
    unsigned long val;
443
    unsigned long dom = 0, bus = 0;
444
    unsigned int slot = 0;
445
    unsigned int func = 0;
446

    
447
    p = addr;
448
    val = strtoul(p, &e, 16);
449
    if (e == p)
450
        return -1;
451
    if (*e == ':') {
452
        bus = val;
453
        p = e + 1;
454
        val = strtoul(p, &e, 16);
455
        if (e == p)
456
            return -1;
457
        if (*e == ':') {
458
            dom = bus;
459
            bus = val;
460
            p = e + 1;
461
            val = strtoul(p, &e, 16);
462
            if (e == p)
463
                return -1;
464
        }
465
    }
466

    
467
    slot = val;
468

    
469
    if (funcp != NULL) {
470
        if (*e != '.')
471
            return -1;
472

    
473
        p = e + 1;
474
        val = strtoul(p, &e, 16);
475
        if (e == p)
476
            return -1;
477

    
478
        func = val;
479
    }
480

    
481
    /* if funcp == NULL func is 0 */
482
    if (dom > 0xffff || bus > 0xff || slot > 0x1f || func > 7)
483
        return -1;
484

    
485
    if (*e)
486
        return -1;
487

    
488
    /* Note: QEMU doesn't implement domains other than 0 */
489
    if (!pci_find_bus(pci_find_root_bus(dom), bus))
490
        return -1;
491

    
492
    *domp = dom;
493
    *busp = bus;
494
    *slotp = slot;
495
    if (funcp != NULL)
496
        *funcp = func;
497
    return 0;
498
}
499

    
500
int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
501
                     unsigned *slotp)
502
{
503
    /* strip legacy tag */
504
    if (!strncmp(addr, "pci_addr=", 9)) {
505
        addr += 9;
506
    }
507
    if (pci_parse_devaddr(addr, domp, busp, slotp, NULL)) {
508
        monitor_printf(mon, "Invalid pci address\n");
509
        return -1;
510
    }
511
    return 0;
512
}
513

    
514
PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
515
{
516
    int dom, bus;
517
    unsigned slot;
518

    
519
    if (!devaddr) {
520
        *devfnp = -1;
521
        return pci_find_bus(pci_find_root_bus(0), 0);
522
    }
523

    
524
    if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {
525
        return NULL;
526
    }
527

    
528
    *devfnp = slot << 3;
529
    return pci_find_bus(pci_find_root_bus(dom), bus);
530
}
531

    
532
static void pci_init_cmask(PCIDevice *dev)
533
{
534
    pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
535
    pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
536
    dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
537
    dev->cmask[PCI_REVISION_ID] = 0xff;
538
    dev->cmask[PCI_CLASS_PROG] = 0xff;
539
    pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
540
    dev->cmask[PCI_HEADER_TYPE] = 0xff;
541
    dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
542
}
543

    
544
static void pci_init_wmask(PCIDevice *dev)
545
{
546
    int config_size = pci_config_size(dev);
547

    
548
    dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
549
    dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
550
    pci_set_word(dev->wmask + PCI_COMMAND,
551
                 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
552
                 PCI_COMMAND_INTX_DISABLE);
553

    
554
    memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
555
           config_size - PCI_CONFIG_HEADER_SIZE);
556
}
557

    
558
static void pci_init_w1cmask(PCIDevice *dev)
559
{
560
    /*
561
     * Note: It's okay to set w1cmask even for readonly bits as
562
     * long as their value is hardwired to 0.
563
     */
564
    pci_set_word(dev->w1cmask + PCI_STATUS,
565
                 PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT |
566
                 PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT |
567
                 PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY);
568
}
569

    
570
static void pci_init_wmask_bridge(PCIDevice *d)
571
{
572
    /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
573
       PCI_SEC_LETENCY_TIMER */
574
    memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
575

    
576
    /* base and limit */
577
    d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
578
    d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
579
    pci_set_word(d->wmask + PCI_MEMORY_BASE,
580
                 PCI_MEMORY_RANGE_MASK & 0xffff);
581
    pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
582
                 PCI_MEMORY_RANGE_MASK & 0xffff);
583
    pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
584
                 PCI_PREF_RANGE_MASK & 0xffff);
585
    pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
586
                 PCI_PREF_RANGE_MASK & 0xffff);
587

    
588
    /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
589
    memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
590

    
591
/* TODO: add this define to pci_regs.h in linux and then in qemu. */
592
#define  PCI_BRIDGE_CTL_VGA_16BIT        0x10        /* VGA 16-bit decode */
593
#define  PCI_BRIDGE_CTL_DISCARD                0x100        /* Primary discard timer */
594
#define  PCI_BRIDGE_CTL_SEC_DISCARD        0x200        /* Secondary discard timer */
595
#define  PCI_BRIDGE_CTL_DISCARD_STATUS        0x400        /* Discard timer status */
596
#define  PCI_BRIDGE_CTL_DISCARD_SERR        0x800        /* Discard timer SERR# enable */
597
    pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,
598
                 PCI_BRIDGE_CTL_PARITY |
599
                 PCI_BRIDGE_CTL_SERR |
600
                 PCI_BRIDGE_CTL_ISA |
601
                 PCI_BRIDGE_CTL_VGA |
602
                 PCI_BRIDGE_CTL_VGA_16BIT |
603
                 PCI_BRIDGE_CTL_MASTER_ABORT |
604
                 PCI_BRIDGE_CTL_BUS_RESET |
605
                 PCI_BRIDGE_CTL_FAST_BACK |
606
                 PCI_BRIDGE_CTL_DISCARD |
607
                 PCI_BRIDGE_CTL_SEC_DISCARD |
608
                 PCI_BRIDGE_CTL_DISCARD_STATUS |
609
                 PCI_BRIDGE_CTL_DISCARD_SERR);
610
    /* Below does not do anything as we never set this bit, put here for
611
     * completeness. */
612
    pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,
613
                 PCI_BRIDGE_CTL_DISCARD_STATUS);
614
}
615

    
616
static int pci_init_multifunction(PCIBus *bus, PCIDevice *dev)
617
{
618
    uint8_t slot = PCI_SLOT(dev->devfn);
619
    uint8_t func;
620

    
621
    if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
622
        dev->config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
623
    }
624

    
625
    /*
626
     * multifunction bit is interpreted in two ways as follows.
627
     *   - all functions must set the bit to 1.
628
     *     Example: Intel X53
629
     *   - function 0 must set the bit, but the rest function (> 0)
630
     *     is allowed to leave the bit to 0.
631
     *     Example: PIIX3(also in qemu), PIIX4(also in qemu), ICH10,
632
     *
633
     * So OS (at least Linux) checks the bit of only function 0,
634
     * and doesn't see the bit of function > 0.
635
     *
636
     * The below check allows both interpretation.
637
     */
638
    if (PCI_FUNC(dev->devfn)) {
639
        PCIDevice *f0 = bus->devices[PCI_DEVFN(slot, 0)];
640
        if (f0 && !(f0->cap_present & QEMU_PCI_CAP_MULTIFUNCTION)) {
641
            /* function 0 should set multifunction bit */
642
            error_report("PCI: single function device can't be populated "
643
                         "in function %x.%x", slot, PCI_FUNC(dev->devfn));
644
            return -1;
645
        }
646
        return 0;
647
    }
648

    
649
    if (dev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
650
        return 0;
651
    }
652
    /* function 0 indicates single function, so function > 0 must be NULL */
653
    for (func = 1; func < PCI_FUNC_MAX; ++func) {
654
        if (bus->devices[PCI_DEVFN(slot, func)]) {
655
            error_report("PCI: %x.0 indicates single function, "
656
                         "but %x.%x is already populated.",
657
                         slot, slot, func);
658
            return -1;
659
        }
660
    }
661
    return 0;
662
}
663

    
664
static void pci_config_alloc(PCIDevice *pci_dev)
665
{
666
    int config_size = pci_config_size(pci_dev);
667

    
668
    pci_dev->config = qemu_mallocz(config_size);
669
    pci_dev->cmask = qemu_mallocz(config_size);
670
    pci_dev->wmask = qemu_mallocz(config_size);
671
    pci_dev->w1cmask = qemu_mallocz(config_size);
672
    pci_dev->used = qemu_mallocz(config_size);
673
}
674

    
675
static void pci_config_free(PCIDevice *pci_dev)
676
{
677
    qemu_free(pci_dev->config);
678
    qemu_free(pci_dev->cmask);
679
    qemu_free(pci_dev->wmask);
680
    qemu_free(pci_dev->w1cmask);
681
    qemu_free(pci_dev->used);
682
}
683

    
684
/* -1 for devfn means auto assign */
685
static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
686
                                         const char *name, int devfn,
687
                                         PCIConfigReadFunc *config_read,
688
                                         PCIConfigWriteFunc *config_write,
689
                                         bool is_bridge)
690
{
691
    if (devfn < 0) {
692
        for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
693
            devfn += PCI_FUNC_MAX) {
694
            if (!bus->devices[devfn])
695
                goto found;
696
        }
697
        error_report("PCI: no slot/function available for %s, all in use", name);
698
        return NULL;
699
    found: ;
700
    } else if (bus->devices[devfn]) {
701
        error_report("PCI: slot %d function %d not available for %s, in use by %s",
702
                     PCI_SLOT(devfn), PCI_FUNC(devfn), name, bus->devices[devfn]->name);
703
        return NULL;
704
    }
705
    pci_dev->bus = bus;
706
    pci_dev->devfn = devfn;
707
    pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
708
    pci_dev->irq_state = 0;
709
    pci_config_alloc(pci_dev);
710

    
711
    if (!is_bridge) {
712
        pci_set_default_subsystem_id(pci_dev);
713
    }
714
    pci_init_cmask(pci_dev);
715
    pci_init_wmask(pci_dev);
716
    pci_init_w1cmask(pci_dev);
717
    if (is_bridge) {
718
        pci_init_wmask_bridge(pci_dev);
719
    }
720
    if (pci_init_multifunction(bus, pci_dev)) {
721
        pci_config_free(pci_dev);
722
        return NULL;
723
    }
724

    
725
    if (!config_read)
726
        config_read = pci_default_read_config;
727
    if (!config_write)
728
        config_write = pci_default_write_config;
729
    pci_dev->config_read = config_read;
730
    pci_dev->config_write = config_write;
731
    bus->devices[devfn] = pci_dev;
732
    pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
733
    pci_dev->version_id = 2; /* Current pci device vmstate version */
734
    return pci_dev;
735
}
736

    
737
static void do_pci_unregister_device(PCIDevice *pci_dev)
738
{
739
    qemu_free_irqs(pci_dev->irq);
740
    pci_dev->bus->devices[pci_dev->devfn] = NULL;
741
    pci_config_free(pci_dev);
742
}
743

    
744
PCIDevice *pci_register_device(PCIBus *bus, const char *name,
745
                               int instance_size, int devfn,
746
                               PCIConfigReadFunc *config_read,
747
                               PCIConfigWriteFunc *config_write)
748
{
749
    PCIDevice *pci_dev;
750

    
751
    pci_dev = qemu_mallocz(instance_size);
752
    pci_dev = do_pci_register_device(pci_dev, bus, name, devfn,
753
                                     config_read, config_write,
754
                                     PCI_HEADER_TYPE_NORMAL);
755
    if (pci_dev == NULL) {
756
        hw_error("PCI: can't register device\n");
757
    }
758
    return pci_dev;
759
}
760

    
761
static target_phys_addr_t pci_to_cpu_addr(PCIBus *bus,
762
                                          target_phys_addr_t addr)
763
{
764
    return addr + bus->mem_base;
765
}
766

    
767
static void pci_unregister_io_regions(PCIDevice *pci_dev)
768
{
769
    PCIIORegion *r;
770
    int i;
771

    
772
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
773
        r = &pci_dev->io_regions[i];
774
        if (!r->size || r->addr == PCI_BAR_UNMAPPED)
775
            continue;
776
        if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
777
            isa_unassign_ioport(r->addr, r->filtered_size);
778
        } else {
779
            cpu_register_physical_memory(pci_to_cpu_addr(pci_dev->bus,
780
                                                         r->addr),
781
                                         r->filtered_size,
782
                                         IO_MEM_UNASSIGNED);
783
        }
784
    }
785
}
786

    
787
static int pci_unregister_device(DeviceState *dev)
788
{
789
    PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
790
    PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
791
    int ret = 0;
792

    
793
    if (info->exit)
794
        ret = info->exit(pci_dev);
795
    if (ret)
796
        return ret;
797

    
798
    pci_unregister_io_regions(pci_dev);
799
    pci_del_option_rom(pci_dev);
800
    do_pci_unregister_device(pci_dev);
801
    return 0;
802
}
803

    
804
void pci_register_bar(PCIDevice *pci_dev, int region_num,
805
                            pcibus_t size, uint8_t type,
806
                            PCIMapIORegionFunc *map_func)
807
{
808
    PCIIORegion *r;
809
    uint32_t addr;
810
    uint64_t wmask;
811

    
812
    assert(region_num >= 0);
813
    assert(region_num < PCI_NUM_REGIONS);
814
    if (size & (size-1)) {
815
        fprintf(stderr, "ERROR: PCI region size must be pow2 "
816
                    "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
817
        exit(1);
818
    }
819

    
820
    r = &pci_dev->io_regions[region_num];
821
    r->addr = PCI_BAR_UNMAPPED;
822
    r->size = size;
823
    r->filtered_size = size;
824
    r->type = type;
825
    r->map_func = map_func;
826

    
827
    wmask = ~(size - 1);
828
    addr = pci_bar(pci_dev, region_num);
829
    if (region_num == PCI_ROM_SLOT) {
830
        /* ROM enable bit is writeable */
831
        wmask |= PCI_ROM_ADDRESS_ENABLE;
832
    }
833
    pci_set_long(pci_dev->config + addr, type);
834
    if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
835
        r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
836
        pci_set_quad(pci_dev->wmask + addr, wmask);
837
        pci_set_quad(pci_dev->cmask + addr, ~0ULL);
838
    } else {
839
        pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
840
        pci_set_long(pci_dev->cmask + addr, 0xffffffff);
841
    }
842
}
843

    
844
static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
845
                              uint8_t type)
846
{
847
    pcibus_t base = *addr;
848
    pcibus_t limit = *addr + *size - 1;
849
    PCIDevice *br;
850

    
851
    for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
852
        uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
853

    
854
        if (type & PCI_BASE_ADDRESS_SPACE_IO) {
855
            if (!(cmd & PCI_COMMAND_IO)) {
856
                goto no_map;
857
            }
858
        } else {
859
            if (!(cmd & PCI_COMMAND_MEMORY)) {
860
                goto no_map;
861
            }
862
        }
863

    
864
        base = MAX(base, pci_bridge_get_base(br, type));
865
        limit = MIN(limit, pci_bridge_get_limit(br, type));
866
    }
867

    
868
    if (base > limit) {
869
        goto no_map;
870
    }
871
    *addr = base;
872
    *size = limit - base + 1;
873
    return;
874
no_map:
875
    *addr = PCI_BAR_UNMAPPED;
876
    *size = 0;
877
}
878

    
879
static pcibus_t pci_bar_address(PCIDevice *d,
880
                                int reg, uint8_t type, pcibus_t size)
881
{
882
    pcibus_t new_addr, last_addr;
883
    int bar = pci_bar(d, reg);
884
    uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
885

    
886
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
887
        if (!(cmd & PCI_COMMAND_IO)) {
888
            return PCI_BAR_UNMAPPED;
889
        }
890
        new_addr = pci_get_long(d->config + bar) & ~(size - 1);
891
        last_addr = new_addr + size - 1;
892
        /* NOTE: we have only 64K ioports on PC */
893
        if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
894
            return PCI_BAR_UNMAPPED;
895
        }
896
        return new_addr;
897
    }
898

    
899
    if (!(cmd & PCI_COMMAND_MEMORY)) {
900
        return PCI_BAR_UNMAPPED;
901
    }
902
    if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
903
        new_addr = pci_get_quad(d->config + bar);
904
    } else {
905
        new_addr = pci_get_long(d->config + bar);
906
    }
907
    /* the ROM slot has a specific enable bit */
908
    if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
909
        return PCI_BAR_UNMAPPED;
910
    }
911
    new_addr &= ~(size - 1);
912
    last_addr = new_addr + size - 1;
913
    /* NOTE: we do not support wrapping */
914
    /* XXX: as we cannot support really dynamic
915
       mappings, we handle specific values as invalid
916
       mappings. */
917
    if (last_addr <= new_addr || new_addr == 0 ||
918
        last_addr == PCI_BAR_UNMAPPED) {
919
        return PCI_BAR_UNMAPPED;
920
    }
921

    
922
    /* Now pcibus_t is 64bit.
923
     * Check if 32 bit BAR wraps around explicitly.
924
     * Without this, PC ide doesn't work well.
925
     * TODO: remove this work around.
926
     */
927
    if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
928
        return PCI_BAR_UNMAPPED;
929
    }
930

    
931
    /*
932
     * OS is allowed to set BAR beyond its addressable
933
     * bits. For example, 32 bit OS can set 64bit bar
934
     * to >4G. Check it. TODO: we might need to support
935
     * it in the future for e.g. PAE.
936
     */
937
    if (last_addr >= TARGET_PHYS_ADDR_MAX) {
938
        return PCI_BAR_UNMAPPED;
939
    }
940

    
941
    return new_addr;
942
}
943

    
944
static void pci_update_mappings(PCIDevice *d)
945
{
946
    PCIIORegion *r;
947
    int i;
948
    pcibus_t new_addr, filtered_size;
949

    
950
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
951
        r = &d->io_regions[i];
952

    
953
        /* this region isn't registered */
954
        if (!r->size)
955
            continue;
956

    
957
        new_addr = pci_bar_address(d, i, r->type, r->size);
958

    
959
        /* bridge filtering */
960
        filtered_size = r->size;
961
        if (new_addr != PCI_BAR_UNMAPPED) {
962
            pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
963
        }
964

    
965
        /* This bar isn't changed */
966
        if (new_addr == r->addr && filtered_size == r->filtered_size)
967
            continue;
968

    
969
        /* now do the real mapping */
970
        if (r->addr != PCI_BAR_UNMAPPED) {
971
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
972
                int class;
973
                /* NOTE: specific hack for IDE in PC case:
974
                   only one byte must be mapped. */
975
                class = pci_get_word(d->config + PCI_CLASS_DEVICE);
976
                if (class == 0x0101 && r->size == 4) {
977
                    isa_unassign_ioport(r->addr + 2, 1);
978
                } else {
979
                    isa_unassign_ioport(r->addr, r->filtered_size);
980
                }
981
            } else {
982
                cpu_register_physical_memory(pci_to_cpu_addr(d->bus, r->addr),
983
                                             r->filtered_size,
984
                                             IO_MEM_UNASSIGNED);
985
                qemu_unregister_coalesced_mmio(r->addr, r->filtered_size);
986
            }
987
        }
988
        r->addr = new_addr;
989
        r->filtered_size = filtered_size;
990
        if (r->addr != PCI_BAR_UNMAPPED) {
991
            /*
992
             * TODO: currently almost all the map funcions assumes
993
             * filtered_size == size and addr & ~(size - 1) == addr.
994
             * However with bridge filtering, they aren't always true.
995
             * Teach them such cases, such that filtered_size < size and
996
             * addr & (size - 1) != 0.
997
             */
998
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
999
                r->map_func(d, i, r->addr, r->filtered_size, r->type);
1000
            } else {
1001
                r->map_func(d, i, pci_to_cpu_addr(d->bus, r->addr),
1002
                            r->filtered_size, r->type);
1003
            }
1004
        }
1005
    }
1006
}
1007

    
1008
static inline int pci_irq_disabled(PCIDevice *d)
1009
{
1010
    return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
1011
}
1012

    
1013
/* Called after interrupt disabled field update in config space,
1014
 * assert/deassert interrupts if necessary.
1015
 * Gets original interrupt disable bit value (before update). */
1016
static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
1017
{
1018
    int i, disabled = pci_irq_disabled(d);
1019
    if (disabled == was_irq_disabled)
1020
        return;
1021
    for (i = 0; i < PCI_NUM_PINS; ++i) {
1022
        int state = pci_irq_state(d, i);
1023
        pci_change_irq_level(d, i, disabled ? -state : state);
1024
    }
1025
}
1026

    
1027
uint32_t pci_default_read_config(PCIDevice *d,
1028
                                 uint32_t address, int len)
1029
{
1030
    uint32_t val = 0;
1031
    assert(len == 1 || len == 2 || len == 4);
1032
    len = MIN(len, pci_config_size(d) - address);
1033
    memcpy(&val, d->config + address, len);
1034
    return le32_to_cpu(val);
1035
}
1036

    
1037
void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
1038
{
1039
    int i, was_irq_disabled = pci_irq_disabled(d);
1040
    uint32_t config_size = pci_config_size(d);
1041

    
1042
    for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
1043
        uint8_t wmask = d->wmask[addr + i];
1044
        uint8_t w1cmask = d->w1cmask[addr + i];
1045
        assert(!(wmask & w1cmask));
1046
        d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1047
        d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */
1048
    }
1049
    if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1050
        ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1051
        ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1052
        range_covers_byte(addr, l, PCI_COMMAND))
1053
        pci_update_mappings(d);
1054

    
1055
    if (range_covers_byte(addr, l, PCI_COMMAND))
1056
        pci_update_irq_disabled(d, was_irq_disabled);
1057
}
1058

    
1059
/***********************************************************/
1060
/* generic PCI irq support */
1061

    
1062
/* 0 <= irq_num <= 3. level must be 0 or 1 */
1063
static void pci_set_irq(void *opaque, int irq_num, int level)
1064
{
1065
    PCIDevice *pci_dev = opaque;
1066
    int change;
1067

    
1068
    change = level - pci_irq_state(pci_dev, irq_num);
1069
    if (!change)
1070
        return;
1071

    
1072
    pci_set_irq_state(pci_dev, irq_num, level);
1073
    pci_update_irq_status(pci_dev);
1074
    if (pci_irq_disabled(pci_dev))
1075
        return;
1076
    pci_change_irq_level(pci_dev, irq_num, change);
1077
}
1078

    
1079
bool pci_msi_enabled(PCIDevice *dev)
1080
{
1081
    return msix_enabled(dev) || msi_enabled(dev);
1082
}
1083

    
1084
void pci_msi_notify(PCIDevice *dev, unsigned int vector)
1085
{
1086
    if (msix_enabled(dev)) {
1087
        msix_notify(dev, vector);
1088
    } else if (msi_enabled(dev)) {
1089
        msi_notify(dev, vector);
1090
    } else {
1091
        /* MSI/MSI-X must be enabled */
1092
        abort();
1093
    }
1094
}
1095

    
1096
/***********************************************************/
1097
/* monitor info on PCI */
1098

    
1099
typedef struct {
1100
    uint16_t class;
1101
    const char *desc;
1102
} pci_class_desc;
1103

    
1104
static const pci_class_desc pci_class_descriptions[] =
1105
{
1106
    { 0x0100, "SCSI controller"},
1107
    { 0x0101, "IDE controller"},
1108
    { 0x0102, "Floppy controller"},
1109
    { 0x0103, "IPI controller"},
1110
    { 0x0104, "RAID controller"},
1111
    { 0x0106, "SATA controller"},
1112
    { 0x0107, "SAS controller"},
1113
    { 0x0180, "Storage controller"},
1114
    { 0x0200, "Ethernet controller"},
1115
    { 0x0201, "Token Ring controller"},
1116
    { 0x0202, "FDDI controller"},
1117
    { 0x0203, "ATM controller"},
1118
    { 0x0280, "Network controller"},
1119
    { 0x0300, "VGA controller"},
1120
    { 0x0301, "XGA controller"},
1121
    { 0x0302, "3D controller"},
1122
    { 0x0380, "Display controller"},
1123
    { 0x0400, "Video controller"},
1124
    { 0x0401, "Audio controller"},
1125
    { 0x0402, "Phone"},
1126
    { 0x0480, "Multimedia controller"},
1127
    { 0x0500, "RAM controller"},
1128
    { 0x0501, "Flash controller"},
1129
    { 0x0580, "Memory controller"},
1130
    { 0x0600, "Host bridge"},
1131
    { 0x0601, "ISA bridge"},
1132
    { 0x0602, "EISA bridge"},
1133
    { 0x0603, "MC bridge"},
1134
    { 0x0604, "PCI bridge"},
1135
    { 0x0605, "PCMCIA bridge"},
1136
    { 0x0606, "NUBUS bridge"},
1137
    { 0x0607, "CARDBUS bridge"},
1138
    { 0x0608, "RACEWAY bridge"},
1139
    { 0x0680, "Bridge"},
1140
    { 0x0c03, "USB controller"},
1141
    { 0, NULL}
1142
};
1143

    
1144
static void pci_for_each_device_under_bus(PCIBus *bus,
1145
                                          void (*fn)(PCIBus *b, PCIDevice *d))
1146
{
1147
    PCIDevice *d;
1148
    int devfn;
1149

    
1150
    for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1151
        d = bus->devices[devfn];
1152
        if (d) {
1153
            fn(bus, d);
1154
        }
1155
    }
1156
}
1157

    
1158
void pci_for_each_device(PCIBus *bus, int bus_num,
1159
                         void (*fn)(PCIBus *b, PCIDevice *d))
1160
{
1161
    bus = pci_find_bus(bus, bus_num);
1162

    
1163
    if (bus) {
1164
        pci_for_each_device_under_bus(bus, fn);
1165
    }
1166
}
1167

    
1168
static void pci_device_print(Monitor *mon, QDict *device)
1169
{
1170
    QDict *qdict;
1171
    QListEntry *entry;
1172
    uint64_t addr, size;
1173

    
1174
    monitor_printf(mon, "  Bus %2" PRId64 ", ", qdict_get_int(device, "bus"));
1175
    monitor_printf(mon, "device %3" PRId64 ", function %" PRId64 ":\n",
1176
                        qdict_get_int(device, "slot"),
1177
                        qdict_get_int(device, "function"));
1178
    monitor_printf(mon, "    ");
1179

    
1180
    qdict = qdict_get_qdict(device, "class_info");
1181
    if (qdict_haskey(qdict, "desc")) {
1182
        monitor_printf(mon, "%s", qdict_get_str(qdict, "desc"));
1183
    } else {
1184
        monitor_printf(mon, "Class %04" PRId64, qdict_get_int(qdict, "class"));
1185
    }
1186

    
1187
    qdict = qdict_get_qdict(device, "id");
1188
    monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
1189
                        qdict_get_int(qdict, "device"),
1190
                        qdict_get_int(qdict, "vendor"));
1191

    
1192
    if (qdict_haskey(device, "irq")) {
1193
        monitor_printf(mon, "      IRQ %" PRId64 ".\n",
1194
                            qdict_get_int(device, "irq"));
1195
    }
1196

    
1197
    if (qdict_haskey(device, "pci_bridge")) {
1198
        QDict *info;
1199

    
1200
        qdict = qdict_get_qdict(device, "pci_bridge");
1201

    
1202
        info = qdict_get_qdict(qdict, "bus");
1203
        monitor_printf(mon, "      BUS %" PRId64 ".\n",
1204
                            qdict_get_int(info, "number"));
1205
        monitor_printf(mon, "      secondary bus %" PRId64 ".\n",
1206
                            qdict_get_int(info, "secondary"));
1207
        monitor_printf(mon, "      subordinate bus %" PRId64 ".\n",
1208
                            qdict_get_int(info, "subordinate"));
1209

    
1210
        info = qdict_get_qdict(qdict, "io_range");
1211
        monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1212
                       qdict_get_int(info, "base"),
1213
                       qdict_get_int(info, "limit"));
1214

    
1215
        info = qdict_get_qdict(qdict, "memory_range");
1216
        monitor_printf(mon,
1217
                       "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1218
                       qdict_get_int(info, "base"),
1219
                       qdict_get_int(info, "limit"));
1220

    
1221
        info = qdict_get_qdict(qdict, "prefetchable_range");
1222
        monitor_printf(mon, "      prefetchable memory range "
1223
                       "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
1224
                       qdict_get_int(info, "base"),
1225
        qdict_get_int(info, "limit"));
1226
    }
1227

    
1228
    QLIST_FOREACH_ENTRY(qdict_get_qlist(device, "regions"), entry) {
1229
        qdict = qobject_to_qdict(qlist_entry_obj(entry));
1230
        monitor_printf(mon, "      BAR%d: ", (int) qdict_get_int(qdict, "bar"));
1231

    
1232
        addr = qdict_get_int(qdict, "address");
1233
        size = qdict_get_int(qdict, "size");
1234

    
1235
        if (!strcmp(qdict_get_str(qdict, "type"), "io")) {
1236
            monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1237
                                " [0x%04"FMT_PCIBUS"].\n",
1238
                                addr, addr + size - 1);
1239
        } else {
1240
            monitor_printf(mon, "%d bit%s memory at 0x%08"FMT_PCIBUS
1241
                               " [0x%08"FMT_PCIBUS"].\n",
1242
                                qdict_get_bool(qdict, "mem_type_64") ? 64 : 32,
1243
                                qdict_get_bool(qdict, "prefetch") ?
1244
                                " prefetchable" : "", addr, addr + size - 1);
1245
        }
1246
    }
1247

    
1248
    monitor_printf(mon, "      id \"%s\"\n", qdict_get_str(device, "qdev_id"));
1249

    
1250
    if (qdict_haskey(device, "pci_bridge")) {
1251
        qdict = qdict_get_qdict(device, "pci_bridge");
1252
        if (qdict_haskey(qdict, "devices")) {
1253
            QListEntry *dev;
1254
            QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1255
                pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1256
            }
1257
        }
1258
    }
1259
}
1260

    
1261
void do_pci_info_print(Monitor *mon, const QObject *data)
1262
{
1263
    QListEntry *bus, *dev;
1264

    
1265
    QLIST_FOREACH_ENTRY(qobject_to_qlist(data), bus) {
1266
        QDict *qdict = qobject_to_qdict(qlist_entry_obj(bus));
1267
        QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1268
            pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1269
        }
1270
    }
1271
}
1272

    
1273
static QObject *pci_get_dev_class(const PCIDevice *dev)
1274
{
1275
    int class;
1276
    const pci_class_desc *desc;
1277

    
1278
    class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1279
    desc = pci_class_descriptions;
1280
    while (desc->desc && class != desc->class)
1281
        desc++;
1282

    
1283
    if (desc->desc) {
1284
        return qobject_from_jsonf("{ 'desc': %s, 'class': %d }",
1285
                                  desc->desc, class);
1286
    } else {
1287
        return qobject_from_jsonf("{ 'class': %d }", class);
1288
    }
1289
}
1290

    
1291
static QObject *pci_get_dev_id(const PCIDevice *dev)
1292
{
1293
    return qobject_from_jsonf("{ 'device': %d, 'vendor': %d }",
1294
                              pci_get_word(dev->config + PCI_VENDOR_ID),
1295
                              pci_get_word(dev->config + PCI_DEVICE_ID));
1296
}
1297

    
1298
static QObject *pci_get_regions_list(const PCIDevice *dev)
1299
{
1300
    int i;
1301
    QList *regions_list;
1302

    
1303
    regions_list = qlist_new();
1304

    
1305
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
1306
        QObject *obj;
1307
        const PCIIORegion *r = &dev->io_regions[i];
1308

    
1309
        if (!r->size) {
1310
            continue;
1311
        }
1312

    
1313
        if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1314
            obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'io', "
1315
                                     "'address': %" PRId64 ", "
1316
                                     "'size': %" PRId64 " }",
1317
                                     i, r->addr, r->size);
1318
        } else {
1319
            int mem_type_64 = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64;
1320

    
1321
            obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'memory', "
1322
                                     "'mem_type_64': %i, 'prefetch': %i, "
1323
                                     "'address': %" PRId64 ", "
1324
                                     "'size': %" PRId64 " }",
1325
                                     i, mem_type_64,
1326
                                     r->type & PCI_BASE_ADDRESS_MEM_PREFETCH,
1327
                                     r->addr, r->size);
1328
        }
1329

    
1330
        qlist_append_obj(regions_list, obj);
1331
    }
1332

    
1333
    return QOBJECT(regions_list);
1334
}
1335

    
1336
static QObject *pci_get_devices_list(PCIBus *bus, int bus_num);
1337

    
1338
static QObject *pci_get_dev_dict(PCIDevice *dev, PCIBus *bus, int bus_num)
1339
{
1340
    uint8_t type;
1341
    QObject *obj;
1342

    
1343
    obj = qobject_from_jsonf("{ 'bus': %d, 'slot': %d, 'function': %d,"                                       "'class_info': %p, 'id': %p, 'regions': %p,"
1344
                              " 'qdev_id': %s }",
1345
                              bus_num,
1346
                              PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
1347
                              pci_get_dev_class(dev), pci_get_dev_id(dev),
1348
                              pci_get_regions_list(dev),
1349
                              dev->qdev.id ? dev->qdev.id : "");
1350

    
1351
    if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1352
        QDict *qdict = qobject_to_qdict(obj);
1353
        qdict_put(qdict, "irq", qint_from_int(dev->config[PCI_INTERRUPT_LINE]));
1354
    }
1355

    
1356
    type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1357
    if (type == PCI_HEADER_TYPE_BRIDGE) {
1358
        QDict *qdict;
1359
        QObject *pci_bridge;
1360

    
1361
        pci_bridge = qobject_from_jsonf("{ 'bus': "
1362
        "{ 'number': %d, 'secondary': %d, 'subordinate': %d }, "
1363
        "'io_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1364
        "'memory_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1365
        "'prefetchable_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "} }",
1366
        dev->config[PCI_PRIMARY_BUS], dev->config[PCI_SECONDARY_BUS],
1367
        dev->config[PCI_SUBORDINATE_BUS],
1368
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO),
1369
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO),
1370
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1371
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1372
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1373
                               PCI_BASE_ADDRESS_MEM_PREFETCH),
1374
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1375
                                PCI_BASE_ADDRESS_MEM_PREFETCH));
1376

    
1377
        if (dev->config[PCI_SECONDARY_BUS] != 0) {
1378
            PCIBus *child_bus = pci_find_bus(bus, dev->config[PCI_SECONDARY_BUS]);
1379

    
1380
            if (child_bus) {
1381
                qdict = qobject_to_qdict(pci_bridge);
1382
                qdict_put_obj(qdict, "devices",
1383
                              pci_get_devices_list(child_bus,
1384
                                                   dev->config[PCI_SECONDARY_BUS]));
1385
            }
1386
        }
1387
        qdict = qobject_to_qdict(obj);
1388
        qdict_put_obj(qdict, "pci_bridge", pci_bridge);
1389
    }
1390

    
1391
    return obj;
1392
}
1393

    
1394
static QObject *pci_get_devices_list(PCIBus *bus, int bus_num)
1395
{
1396
    int devfn;
1397
    PCIDevice *dev;
1398
    QList *dev_list;
1399

    
1400
    dev_list = qlist_new();
1401

    
1402
    for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1403
        dev = bus->devices[devfn];
1404
        if (dev) {
1405
            qlist_append_obj(dev_list, pci_get_dev_dict(dev, bus, bus_num));
1406
        }
1407
    }
1408

    
1409
    return QOBJECT(dev_list);
1410
}
1411

    
1412
static QObject *pci_get_bus_dict(PCIBus *bus, int bus_num)
1413
{
1414
    bus = pci_find_bus(bus, bus_num);
1415
    if (bus) {
1416
        return qobject_from_jsonf("{ 'bus': %d, 'devices': %p }",
1417
                                  bus_num, pci_get_devices_list(bus, bus_num));
1418
    }
1419

    
1420
    return NULL;
1421
}
1422

    
1423
void do_pci_info(Monitor *mon, QObject **ret_data)
1424
{
1425
    QList *bus_list;
1426
    struct PCIHostBus *host;
1427

    
1428
    bus_list = qlist_new();
1429

    
1430
    QLIST_FOREACH(host, &host_buses, next) {
1431
        QObject *obj = pci_get_bus_dict(host->bus, 0);
1432
        if (obj) {
1433
            qlist_append_obj(bus_list, obj);
1434
        }
1435
    }
1436

    
1437
    *ret_data = QOBJECT(bus_list);
1438
}
1439

    
1440
static const char * const pci_nic_models[] = {
1441
    "ne2k_pci",
1442
    "i82551",
1443
    "i82557b",
1444
    "i82559er",
1445
    "rtl8139",
1446
    "e1000",
1447
    "pcnet",
1448
    "virtio",
1449
    NULL
1450
};
1451

    
1452
static const char * const pci_nic_names[] = {
1453
    "ne2k_pci",
1454
    "i82551",
1455
    "i82557b",
1456
    "i82559er",
1457
    "rtl8139",
1458
    "e1000",
1459
    "pcnet",
1460
    "virtio-net-pci",
1461
    NULL
1462
};
1463

    
1464
/* Initialize a PCI NIC.  */
1465
/* FIXME callers should check for failure, but don't */
1466
PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1467
                        const char *default_devaddr)
1468
{
1469
    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1470
    PCIBus *bus;
1471
    int devfn;
1472
    PCIDevice *pci_dev;
1473
    DeviceState *dev;
1474
    int i;
1475

    
1476
    i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1477
    if (i < 0)
1478
        return NULL;
1479

    
1480
    bus = pci_get_bus_devfn(&devfn, devaddr);
1481
    if (!bus) {
1482
        error_report("Invalid PCI device address %s for device %s",
1483
                     devaddr, pci_nic_names[i]);
1484
        return NULL;
1485
    }
1486

    
1487
    pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1488
    dev = &pci_dev->qdev;
1489
    qdev_set_nic_properties(dev, nd);
1490
    if (qdev_init(dev) < 0)
1491
        return NULL;
1492
    return pci_dev;
1493
}
1494

    
1495
PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1496
                               const char *default_devaddr)
1497
{
1498
    PCIDevice *res;
1499

    
1500
    if (qemu_show_nic_models(nd->model, pci_nic_models))
1501
        exit(0);
1502

    
1503
    res = pci_nic_init(nd, default_model, default_devaddr);
1504
    if (!res)
1505
        exit(1);
1506
    return res;
1507
}
1508

    
1509
static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1510
{
1511
    pci_update_mappings(d);
1512
}
1513

    
1514
void pci_bridge_update_mappings(PCIBus *b)
1515
{
1516
    PCIBus *child;
1517

    
1518
    pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1519

    
1520
    QLIST_FOREACH(child, &b->child, sibling) {
1521
        pci_bridge_update_mappings(child);
1522
    }
1523
}
1524

    
1525
PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1526
{
1527
    PCIBus *sec;
1528

    
1529
    if (!bus) {
1530
        return NULL;
1531
    }
1532

    
1533
    if (pci_bus_num(bus) == bus_num) {
1534
        return bus;
1535
    }
1536

    
1537
    /* try child bus */
1538
    if (!bus->parent_dev /* host pci bridge */ ||
1539
        (bus->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1540
         bus_num <= bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {
1541
        for (; bus; bus = sec) {
1542
            QLIST_FOREACH(sec, &bus->child, sibling) {
1543
                assert(sec->parent_dev);
1544
                if (sec->parent_dev->config[PCI_SECONDARY_BUS] == bus_num) {
1545
                    return sec;
1546
                }
1547
                if (sec->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1548
                    bus_num <= sec->parent_dev->config[PCI_SUBORDINATE_BUS]) {
1549
                    break;
1550
                }
1551
            }
1552
        }
1553
    }
1554

    
1555
    return NULL;
1556
}
1557

    
1558
PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function)
1559
{
1560
    bus = pci_find_bus(bus, bus_num);
1561

    
1562
    if (!bus)
1563
        return NULL;
1564

    
1565
    return bus->devices[PCI_DEVFN(slot, function)];
1566
}
1567

    
1568
static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1569
{
1570
    PCIDevice *pci_dev = (PCIDevice *)qdev;
1571
    PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1572
    PCIBus *bus;
1573
    int devfn, rc;
1574
    bool is_default_rom;
1575

    
1576
    /* initialize cap_present for pci_is_express() and pci_config_size() */
1577
    if (info->is_express) {
1578
        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1579
    }
1580

    
1581
    bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1582
    devfn = pci_dev->devfn;
1583
    pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
1584
                                     info->config_read, info->config_write,
1585
                                     info->is_bridge);
1586
    if (pci_dev == NULL)
1587
        return -1;
1588
    rc = info->init(pci_dev);
1589
    if (rc != 0) {
1590
        do_pci_unregister_device(pci_dev);
1591
        return rc;
1592
    }
1593

    
1594
    /* rom loading */
1595
    is_default_rom = false;
1596
    if (pci_dev->romfile == NULL && info->romfile != NULL) {
1597
        pci_dev->romfile = qemu_strdup(info->romfile);
1598
        is_default_rom = true;
1599
    }
1600
    pci_add_option_rom(pci_dev, is_default_rom);
1601

    
1602
    if (bus->hotplug) {
1603
        /* Let buses differentiate between hotplug and when device is
1604
         * enabled during qemu machine creation. */
1605
        rc = bus->hotplug(bus->hotplug_qdev, pci_dev,
1606
                          qdev->hotplugged ? PCI_HOTPLUG_ENABLED:
1607
                          PCI_COLDPLUG_ENABLED);
1608
        if (rc != 0) {
1609
            int r = pci_unregister_device(&pci_dev->qdev);
1610
            assert(!r);
1611
            return rc;
1612
        }
1613
    }
1614
    return 0;
1615
}
1616

    
1617
static int pci_unplug_device(DeviceState *qdev)
1618
{
1619
    PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1620

    
1621
    return dev->bus->hotplug(dev->bus->hotplug_qdev, dev,
1622
                             PCI_HOTPLUG_DISABLED);
1623
}
1624

    
1625
void pci_qdev_register(PCIDeviceInfo *info)
1626
{
1627
    info->qdev.init = pci_qdev_init;
1628
    info->qdev.unplug = pci_unplug_device;
1629
    info->qdev.exit = pci_unregister_device;
1630
    info->qdev.bus_info = &pci_bus_info;
1631
    qdev_register(&info->qdev);
1632
}
1633

    
1634
void pci_qdev_register_many(PCIDeviceInfo *info)
1635
{
1636
    while (info->qdev.name) {
1637
        pci_qdev_register(info);
1638
        info++;
1639
    }
1640
}
1641

    
1642
PCIDevice *pci_create_multifunction(PCIBus *bus, int devfn, bool multifunction,
1643
                                    const char *name)
1644
{
1645
    DeviceState *dev;
1646

    
1647
    dev = qdev_create(&bus->qbus, name);
1648
    qdev_prop_set_uint32(dev, "addr", devfn);
1649
    qdev_prop_set_bit(dev, "multifunction", multifunction);
1650
    return DO_UPCAST(PCIDevice, qdev, dev);
1651
}
1652

    
1653
PCIDevice *pci_create_simple_multifunction(PCIBus *bus, int devfn,
1654
                                           bool multifunction,
1655
                                           const char *name)
1656
{
1657
    PCIDevice *dev = pci_create_multifunction(bus, devfn, multifunction, name);
1658
    qdev_init_nofail(&dev->qdev);
1659
    return dev;
1660
}
1661

    
1662
PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1663
{
1664
    return pci_create_multifunction(bus, devfn, false, name);
1665
}
1666

    
1667
PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1668
{
1669
    return pci_create_simple_multifunction(bus, devfn, false, name);
1670
}
1671

    
1672
static int pci_find_space(PCIDevice *pdev, uint8_t size)
1673
{
1674
    int config_size = pci_config_size(pdev);
1675
    int offset = PCI_CONFIG_HEADER_SIZE;
1676
    int i;
1677
    for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1678
        if (pdev->used[i])
1679
            offset = i + 1;
1680
        else if (i - offset + 1 == size)
1681
            return offset;
1682
    return 0;
1683
}
1684

    
1685
static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1686
                                        uint8_t *prev_p)
1687
{
1688
    uint8_t next, prev;
1689

    
1690
    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1691
        return 0;
1692

    
1693
    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1694
         prev = next + PCI_CAP_LIST_NEXT)
1695
        if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1696
            break;
1697

    
1698
    if (prev_p)
1699
        *prev_p = prev;
1700
    return next;
1701
}
1702

    
1703
static void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1704
{
1705
    cpu_register_physical_memory(addr, size, pdev->rom_offset);
1706
}
1707

    
1708
/* Patch the PCI vendor and device ids in a PCI rom image if necessary.
1709
   This is needed for an option rom which is used for more than one device. */
1710
static void pci_patch_ids(PCIDevice *pdev, uint8_t *ptr, int size)
1711
{
1712
    uint16_t vendor_id;
1713
    uint16_t device_id;
1714
    uint16_t rom_vendor_id;
1715
    uint16_t rom_device_id;
1716
    uint16_t rom_magic;
1717
    uint16_t pcir_offset;
1718
    uint8_t checksum;
1719

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

    
1723
    /* Only a valid rom will be patched. */
1724
    rom_magic = pci_get_word(ptr);
1725
    if (rom_magic != 0xaa55) {
1726
        PCI_DPRINTF("Bad ROM magic %04x\n", rom_magic);
1727
        return;
1728
    }
1729
    pcir_offset = pci_get_word(ptr + 0x18);
1730
    if (pcir_offset + 8 >= size || memcmp(ptr + pcir_offset, "PCIR", 4)) {
1731
        PCI_DPRINTF("Bad PCIR offset 0x%x or signature\n", pcir_offset);
1732
        return;
1733
    }
1734

    
1735
    vendor_id = pci_get_word(pdev->config + PCI_VENDOR_ID);
1736
    device_id = pci_get_word(pdev->config + PCI_DEVICE_ID);
1737
    rom_vendor_id = pci_get_word(ptr + pcir_offset + 4);
1738
    rom_device_id = pci_get_word(ptr + pcir_offset + 6);
1739

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

    
1743
    checksum = ptr[6];
1744

    
1745
    if (vendor_id != rom_vendor_id) {
1746
        /* Patch vendor id and checksum (at offset 6 for etherboot roms). */
1747
        checksum += (uint8_t)rom_vendor_id + (uint8_t)(rom_vendor_id >> 8);
1748
        checksum -= (uint8_t)vendor_id + (uint8_t)(vendor_id >> 8);
1749
        PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1750
        ptr[6] = checksum;
1751
        pci_set_word(ptr + pcir_offset + 4, vendor_id);
1752
    }
1753

    
1754
    if (device_id != rom_device_id) {
1755
        /* Patch device id and checksum (at offset 6 for etherboot roms). */
1756
        checksum += (uint8_t)rom_device_id + (uint8_t)(rom_device_id >> 8);
1757
        checksum -= (uint8_t)device_id + (uint8_t)(device_id >> 8);
1758
        PCI_DPRINTF("ROM checksum %02x / %02x\n", ptr[6], checksum);
1759
        ptr[6] = checksum;
1760
        pci_set_word(ptr + pcir_offset + 6, device_id);
1761
    }
1762
}
1763

    
1764
/* Add an option rom for the device */
1765
static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom)
1766
{
1767
    int size;
1768
    char *path;
1769
    void *ptr;
1770
    char name[32];
1771

    
1772
    if (!pdev->romfile)
1773
        return 0;
1774
    if (strlen(pdev->romfile) == 0)
1775
        return 0;
1776

    
1777
    if (!pdev->rom_bar) {
1778
        /*
1779
         * Load rom via fw_cfg instead of creating a rom bar,
1780
         * for 0.11 compatibility.
1781
         */
1782
        int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
1783
        if (class == 0x0300) {
1784
            rom_add_vga(pdev->romfile);
1785
        } else {
1786
            rom_add_option(pdev->romfile);
1787
        }
1788
        return 0;
1789
    }
1790

    
1791
    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1792
    if (path == NULL) {
1793
        path = qemu_strdup(pdev->romfile);
1794
    }
1795

    
1796
    size = get_image_size(path);
1797
    if (size < 0) {
1798
        error_report("%s: failed to find romfile \"%s\"",
1799
                     __FUNCTION__, pdev->romfile);
1800
        return -1;
1801
    }
1802
    if (size & (size - 1)) {
1803
        size = 1 << qemu_fls(size);
1804
    }
1805

    
1806
    if (pdev->qdev.info->vmsd)
1807
        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);
1808
    else
1809
        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);
1810
    pdev->rom_offset = qemu_ram_alloc(&pdev->qdev, name, size);
1811

    
1812
    ptr = qemu_get_ram_ptr(pdev->rom_offset);
1813
    load_image(path, ptr);
1814
    qemu_free(path);
1815

    
1816
    if (is_default_rom) {
1817
        /* Only the default rom images will be patched (if needed). */
1818
        pci_patch_ids(pdev, ptr, size);
1819
    }
1820

    
1821
    pci_register_bar(pdev, PCI_ROM_SLOT, size,
1822
                     0, pci_map_option_rom);
1823

    
1824
    return 0;
1825
}
1826

    
1827
static void pci_del_option_rom(PCIDevice *pdev)
1828
{
1829
    if (!pdev->rom_offset)
1830
        return;
1831

    
1832
    qemu_ram_free(pdev->rom_offset);
1833
    pdev->rom_offset = 0;
1834
}
1835

    
1836
/*
1837
 * if !offset
1838
 * Reserve space and add capability to the linked list in pci config space
1839
 *
1840
 * if offset = 0,
1841
 * Find and reserve space and add capability to the linked list
1842
 * in pci config space */
1843
int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,
1844
                       uint8_t offset, uint8_t size)
1845
{
1846
    uint8_t *config;
1847
    if (!offset) {
1848
        offset = pci_find_space(pdev, size);
1849
        if (!offset) {
1850
            return -ENOSPC;
1851
        }
1852
    }
1853

    
1854
    config = pdev->config + offset;
1855
    config[PCI_CAP_LIST_ID] = cap_id;
1856
    config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1857
    pdev->config[PCI_CAPABILITY_LIST] = offset;
1858
    pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1859
    memset(pdev->used + offset, 0xFF, size);
1860
    /* Make capability read-only by default */
1861
    memset(pdev->wmask + offset, 0, size);
1862
    /* Check capability by default */
1863
    memset(pdev->cmask + offset, 0xFF, size);
1864
    return offset;
1865
}
1866

    
1867
/* Unlink capability from the pci config space. */
1868
void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1869
{
1870
    uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
1871
    if (!offset)
1872
        return;
1873
    pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
1874
    /* Make capability writeable again */
1875
    memset(pdev->wmask + offset, 0xff, size);
1876
    memset(pdev->w1cmask + offset, 0, size);
1877
    /* Clear cmask as device-specific registers can't be checked */
1878
    memset(pdev->cmask + offset, 0, size);
1879
    memset(pdev->used + offset, 0, size);
1880

    
1881
    if (!pdev->config[PCI_CAPABILITY_LIST])
1882
        pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
1883
}
1884

    
1885
/* Reserve space for capability at a known offset (to call after load). */
1886
void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
1887
{
1888
    memset(pdev->used + offset, 0xff, size);
1889
}
1890

    
1891
uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
1892
{
1893
    return pci_find_capability_list(pdev, cap_id, NULL);
1894
}
1895

    
1896
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
1897
{
1898
    PCIDevice *d = (PCIDevice *)dev;
1899
    const pci_class_desc *desc;
1900
    char ctxt[64];
1901
    PCIIORegion *r;
1902
    int i, class;
1903

    
1904
    class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1905
    desc = pci_class_descriptions;
1906
    while (desc->desc && class != desc->class)
1907
        desc++;
1908
    if (desc->desc) {
1909
        snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
1910
    } else {
1911
        snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
1912
    }
1913

    
1914
    monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
1915
                   "pci id %04x:%04x (sub %04x:%04x)\n",
1916
                   indent, "", ctxt, pci_bus_num(d->bus),
1917
                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
1918
                   pci_get_word(d->config + PCI_VENDOR_ID),
1919
                   pci_get_word(d->config + PCI_DEVICE_ID),
1920
                   pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
1921
                   pci_get_word(d->config + PCI_SUBSYSTEM_ID));
1922
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
1923
        r = &d->io_regions[i];
1924
        if (!r->size)
1925
            continue;
1926
        monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
1927
                       " [0x%"FMT_PCIBUS"]\n",
1928
                       indent, "",
1929
                       i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
1930
                       r->addr, r->addr + r->size - 1);
1931
    }
1932
}
1933

    
1934
static char *pcibus_get_dev_path(DeviceState *dev)
1935
{
1936
    PCIDevice *d = (PCIDevice *)dev;
1937
    char path[16];
1938

    
1939
    snprintf(path, sizeof(path), "%04x:%02x:%02x.%x",
1940
             pci_find_domain(d->bus), d->config[PCI_SECONDARY_BUS],
1941
             PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));
1942

    
1943
    return strdup(path);
1944
}
1945