Statistics
| Branch: | Revision:

root / hw / pci.c @ e075e788

History | View | Annotate | Download (57 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 "monitor.h"
27
#include "net.h"
28
#include "sysemu.h"
29
#include "loader.h"
30
#include "qemu-objects.h"
31

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

    
39
struct PCIBus {
40
    BusState qbus;
41
    int devfn_min;
42
    pci_set_irq_fn set_irq;
43
    pci_map_irq_fn map_irq;
44
    pci_hotplug_fn hotplug;
45
    DeviceState *hotplug_qdev;
46
    void *irq_opaque;
47
    PCIDevice *devices[256];
48
    PCIDevice *parent_dev;
49
    target_phys_addr_t mem_base;
50

    
51
    QLIST_HEAD(, PCIBus) child; /* this will be replaced by qdev later */
52
    QLIST_ENTRY(PCIBus) sibling;/* this will be replaced by qdev later */
53

    
54
    /* The bus IRQ state is the logical OR of the connected devices.
55
       Keep a count of the number of devices with raised IRQs.  */
56
    int nirq;
57
    int *irq_count;
58
};
59

    
60
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
61

    
62
static struct BusInfo pci_bus_info = {
63
    .name       = "PCI",
64
    .size       = sizeof(PCIBus),
65
    .print_dev  = pcibus_dev_print,
66
    .props      = (Property[]) {
67
        DEFINE_PROP_PCI_DEVFN("addr", PCIDevice, devfn, -1),
68
        DEFINE_PROP_STRING("romfile", PCIDevice, romfile),
69
        DEFINE_PROP_UINT32("rombar",  PCIDevice, rom_bar, 1),
70
        DEFINE_PROP_END_OF_LIST()
71
    }
72
};
73

    
74
static void pci_update_mappings(PCIDevice *d);
75
static void pci_set_irq(void *opaque, int irq_num, int level);
76
static int pci_add_option_rom(PCIDevice *pdev);
77

    
78
static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
79
static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
80

    
81
struct PCIHostBus {
82
    int domain;
83
    struct PCIBus *bus;
84
    QLIST_ENTRY(PCIHostBus) next;
85
};
86
static QLIST_HEAD(, PCIHostBus) host_buses;
87

    
88
static const VMStateDescription vmstate_pcibus = {
89
    .name = "PCIBUS",
90
    .version_id = 1,
91
    .minimum_version_id = 1,
92
    .minimum_version_id_old = 1,
93
    .fields      = (VMStateField []) {
94
        VMSTATE_INT32_EQUAL(nirq, PCIBus),
95
        VMSTATE_VARRAY_INT32(irq_count, PCIBus, nirq, 0, vmstate_info_int32, int32_t),
96
        VMSTATE_END_OF_LIST()
97
    }
98
};
99

    
100
static int pci_bar(PCIDevice *d, int reg)
101
{
102
    uint8_t type;
103

    
104
    if (reg != PCI_ROM_SLOT)
105
        return PCI_BASE_ADDRESS_0 + reg * 4;
106

    
107
    type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
108
    return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
109
}
110

    
111
static inline int pci_irq_state(PCIDevice *d, int irq_num)
112
{
113
        return (d->irq_state >> irq_num) & 0x1;
114
}
115

    
116
static inline void pci_set_irq_state(PCIDevice *d, int irq_num, int level)
117
{
118
        d->irq_state &= ~(0x1 << irq_num);
119
        d->irq_state |= level << irq_num;
120
}
121

    
122
static void pci_change_irq_level(PCIDevice *pci_dev, int irq_num, int change)
123
{
124
    PCIBus *bus;
125
    for (;;) {
126
        bus = pci_dev->bus;
127
        irq_num = bus->map_irq(pci_dev, irq_num);
128
        if (bus->set_irq)
129
            break;
130
        pci_dev = bus->parent_dev;
131
    }
132
    bus->irq_count[irq_num] += change;
133
    bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);
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
static void pci_device_reset(PCIDevice *dev)
148
{
149
    int r;
150

    
151
    dev->irq_state = 0;
152
    pci_update_irq_status(dev);
153
    dev->config[PCI_COMMAND] &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY |
154
                                  PCI_COMMAND_MASTER);
155
    dev->config[PCI_CACHE_LINE_SIZE] = 0x0;
156
    dev->config[PCI_INTERRUPT_LINE] = 0x0;
157
    for (r = 0; r < PCI_NUM_REGIONS; ++r) {
158
        if (!dev->io_regions[r].size) {
159
            continue;
160
        }
161
        pci_set_long(dev->config + pci_bar(dev, r), dev->io_regions[r].type);
162
    }
163
    pci_update_mappings(dev);
164
}
165

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

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

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

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

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

    
200
    return NULL;
201
}
202

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

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

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

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

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

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

    
233
    vmstate_register(-1, &vmstate_pcibus, bus);
234
    qemu_register_reset(pci_bus_reset, bus);
235
}
236

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

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

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

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

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

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

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

    
280
static void pci_register_secondary_bus(PCIBus *parent,
281
                                       PCIBus *bus,
282
                                       PCIDevice *dev,
283
                                       pci_map_irq_fn map_irq,
284
                                       const char *name)
285
{
286
    qbus_create_inplace(&bus->qbus, &pci_bus_info, &dev->qdev, name);
287
    bus->map_irq = map_irq;
288
    bus->parent_dev = dev;
289

    
290
    QLIST_INIT(&bus->child);
291
    QLIST_INSERT_HEAD(&parent->child, bus, sibling);
292
}
293

    
294
static void pci_unregister_secondary_bus(PCIBus *bus)
295
{
296
    assert(QLIST_EMPTY(&bus->child));
297
    QLIST_REMOVE(bus, sibling);
298
}
299

    
300
int pci_bus_num(PCIBus *s)
301
{
302
    if (!s->parent_dev)
303
        return 0;       /* pci host bridge */
304
    return s->parent_dev->config[PCI_SECONDARY_BUS];
305
}
306

    
307
static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
308
{
309
    PCIDevice *s = container_of(pv, PCIDevice, config);
310
    uint8_t *config;
311
    int i;
312

    
313
    assert(size == pci_config_size(s));
314
    config = qemu_malloc(size);
315

    
316
    qemu_get_buffer(f, config, size);
317
    for (i = 0; i < size; ++i) {
318
        if ((config[i] ^ s->config[i]) & s->cmask[i] & ~s->wmask[i]) {
319
            qemu_free(config);
320
            return -EINVAL;
321
        }
322
    }
323
    memcpy(s->config, config, size);
324

    
325
    pci_update_mappings(s);
326

    
327
    qemu_free(config);
328
    return 0;
329
}
330

    
331
/* just put buffer */
332
static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
333
{
334
    const uint8_t **v = pv;
335
    assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
336
    qemu_put_buffer(f, *v, size);
337
}
338

    
339
static VMStateInfo vmstate_info_pci_config = {
340
    .name = "pci config",
341
    .get  = get_pci_config_device,
342
    .put  = put_pci_config_device,
343
};
344

    
345
static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
346
{
347
    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
348
    uint32_t irq_state[PCI_NUM_PINS];
349
    int i;
350
    for (i = 0; i < PCI_NUM_PINS; ++i) {
351
        irq_state[i] = qemu_get_be32(f);
352
        if (irq_state[i] != 0x1 && irq_state[i] != 0) {
353
            fprintf(stderr, "irq state %d: must be 0 or 1.\n",
354
                    irq_state[i]);
355
            return -EINVAL;
356
        }
357
    }
358

    
359
    for (i = 0; i < PCI_NUM_PINS; ++i) {
360
        pci_set_irq_state(s, i, irq_state[i]);
361
    }
362

    
363
    return 0;
364
}
365

    
366
static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
367
{
368
    int i;
369
    PCIDevice *s = container_of(pv, PCIDevice, irq_state);
370

    
371
    for (i = 0; i < PCI_NUM_PINS; ++i) {
372
        qemu_put_be32(f, pci_irq_state(s, i));
373
    }
374
}
375

    
376
static VMStateInfo vmstate_info_pci_irq_state = {
377
    .name = "pci irq state",
378
    .get  = get_pci_irq_state,
379
    .put  = put_pci_irq_state,
380
};
381

    
382
const VMStateDescription vmstate_pci_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
                                   PCI_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
const VMStateDescription vmstate_pcie_device = {
400
    .name = "PCIDevice",
401
    .version_id = 2,
402
    .minimum_version_id = 1,
403
    .minimum_version_id_old = 1,
404
    .fields      = (VMStateField []) {
405
        VMSTATE_INT32_LE(version_id, PCIDevice),
406
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
407
                                   vmstate_info_pci_config,
408
                                   PCIE_CONFIG_SPACE_SIZE),
409
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
410
                                   vmstate_info_pci_irq_state,
411
                                   PCI_NUM_PINS * sizeof(int32_t)),
412
        VMSTATE_END_OF_LIST()
413
    }
414
};
415

    
416
static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
417
{
418
    return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
419
}
420

    
421
void pci_device_save(PCIDevice *s, QEMUFile *f)
422
{
423
    /* Clear interrupt status bit: it is implicit
424
     * in irq_state which we are saving.
425
     * This makes us compatible with old devices
426
     * which never set or clear this bit. */
427
    s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
428
    vmstate_save_state(f, pci_get_vmstate(s), s);
429
    /* Restore the interrupt status bit. */
430
    pci_update_irq_status(s);
431
}
432

    
433
int pci_device_load(PCIDevice *s, QEMUFile *f)
434
{
435
    int ret;
436
    ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
437
    /* Restore the interrupt status bit. */
438
    pci_update_irq_status(s);
439
    return ret;
440
}
441

    
442
static void pci_set_default_subsystem_id(PCIDevice *pci_dev)
443
{
444
    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,
445
                 pci_default_sub_vendor_id);
446
    pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,
447
                 pci_default_sub_device_id);
448
}
449

    
450
/*
451
 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error
452
 */
453
static int pci_parse_devaddr(const char *addr, int *domp, int *busp, unsigned *slotp)
454
{
455
    const char *p;
456
    char *e;
457
    unsigned long val;
458
    unsigned long dom = 0, bus = 0;
459
    unsigned slot = 0;
460

    
461
    p = addr;
462
    val = strtoul(p, &e, 16);
463
    if (e == p)
464
        return -1;
465
    if (*e == ':') {
466
        bus = val;
467
        p = e + 1;
468
        val = strtoul(p, &e, 16);
469
        if (e == p)
470
            return -1;
471
        if (*e == ':') {
472
            dom = bus;
473
            bus = val;
474
            p = e + 1;
475
            val = strtoul(p, &e, 16);
476
            if (e == p)
477
                return -1;
478
        }
479
    }
480

    
481
    if (dom > 0xffff || bus > 0xff || val > 0x1f)
482
        return -1;
483

    
484
    slot = val;
485

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

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

    
493
    *domp = dom;
494
    *busp = bus;
495
    *slotp = slot;
496
    return 0;
497
}
498

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

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

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

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

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

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

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

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

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

    
557
static void pci_init_wmask_bridge(PCIDevice *d)
558
{
559
    /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
560
       PCI_SEC_LETENCY_TIMER */
561
    memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
562

    
563
    /* base and limit */
564
    d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
565
    d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
566
    pci_set_word(d->wmask + PCI_MEMORY_BASE,
567
                 PCI_MEMORY_RANGE_MASK & 0xffff);
568
    pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
569
                 PCI_MEMORY_RANGE_MASK & 0xffff);
570
    pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
571
                 PCI_PREF_RANGE_MASK & 0xffff);
572
    pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
573
                 PCI_PREF_RANGE_MASK & 0xffff);
574

    
575
    /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
576
    memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
577

    
578
    pci_set_word(d->wmask + PCI_BRIDGE_CONTROL, 0xffff);
579
}
580

    
581
static void pci_config_alloc(PCIDevice *pci_dev)
582
{
583
    int config_size = pci_config_size(pci_dev);
584

    
585
    pci_dev->config = qemu_mallocz(config_size);
586
    pci_dev->cmask = qemu_mallocz(config_size);
587
    pci_dev->wmask = qemu_mallocz(config_size);
588
    pci_dev->used = qemu_mallocz(config_size);
589
}
590

    
591
static void pci_config_free(PCIDevice *pci_dev)
592
{
593
    qemu_free(pci_dev->config);
594
    qemu_free(pci_dev->cmask);
595
    qemu_free(pci_dev->wmask);
596
    qemu_free(pci_dev->used);
597
}
598

    
599
/* -1 for devfn means auto assign */
600
static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
601
                                         const char *name, int devfn,
602
                                         PCIConfigReadFunc *config_read,
603
                                         PCIConfigWriteFunc *config_write,
604
                                         uint8_t header_type)
605
{
606
    if (devfn < 0) {
607
        for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
608
            devfn += 8) {
609
            if (!bus->devices[devfn])
610
                goto found;
611
        }
612
        error_report("PCI: no devfn available for %s, all in use", name);
613
        return NULL;
614
    found: ;
615
    } else if (bus->devices[devfn]) {
616
        error_report("PCI: devfn %d not available for %s, in use by %s",
617
                     devfn, name, bus->devices[devfn]->name);
618
        return NULL;
619
    }
620
    pci_dev->bus = bus;
621
    pci_dev->devfn = devfn;
622
    pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
623
    pci_dev->irq_state = 0;
624
    pci_config_alloc(pci_dev);
625

    
626
    header_type &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
627
    if (header_type == PCI_HEADER_TYPE_NORMAL) {
628
        pci_set_default_subsystem_id(pci_dev);
629
    }
630
    pci_init_cmask(pci_dev);
631
    pci_init_wmask(pci_dev);
632
    if (header_type == PCI_HEADER_TYPE_BRIDGE) {
633
        pci_init_wmask_bridge(pci_dev);
634
    }
635

    
636
    if (!config_read)
637
        config_read = pci_default_read_config;
638
    if (!config_write)
639
        config_write = pci_default_write_config;
640
    pci_dev->config_read = config_read;
641
    pci_dev->config_write = config_write;
642
    bus->devices[devfn] = pci_dev;
643
    pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
644
    pci_dev->version_id = 2; /* Current pci device vmstate version */
645
    return pci_dev;
646
}
647

    
648
static void do_pci_unregister_device(PCIDevice *pci_dev)
649
{
650
    qemu_free_irqs(pci_dev->irq);
651
    pci_dev->bus->devices[pci_dev->devfn] = NULL;
652
    pci_config_free(pci_dev);
653
}
654

    
655
PCIDevice *pci_register_device(PCIBus *bus, const char *name,
656
                               int instance_size, int devfn,
657
                               PCIConfigReadFunc *config_read,
658
                               PCIConfigWriteFunc *config_write)
659
{
660
    PCIDevice *pci_dev;
661

    
662
    pci_dev = qemu_mallocz(instance_size);
663
    pci_dev = do_pci_register_device(pci_dev, bus, name, devfn,
664
                                     config_read, config_write,
665
                                     PCI_HEADER_TYPE_NORMAL);
666
    if (pci_dev == NULL) {
667
        hw_error("PCI: can't register device\n");
668
    }
669
    return pci_dev;
670
}
671

    
672
static target_phys_addr_t pci_to_cpu_addr(PCIBus *bus,
673
                                          target_phys_addr_t addr)
674
{
675
    return addr + bus->mem_base;
676
}
677

    
678
static void pci_unregister_io_regions(PCIDevice *pci_dev)
679
{
680
    PCIIORegion *r;
681
    int i;
682

    
683
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
684
        r = &pci_dev->io_regions[i];
685
        if (!r->size || r->addr == PCI_BAR_UNMAPPED)
686
            continue;
687
        if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
688
            isa_unassign_ioport(r->addr, r->filtered_size);
689
        } else {
690
            cpu_register_physical_memory(pci_to_cpu_addr(pci_dev->bus,
691
                                                         r->addr),
692
                                         r->filtered_size,
693
                                         IO_MEM_UNASSIGNED);
694
        }
695
    }
696
}
697

    
698
static int pci_unregister_device(DeviceState *dev)
699
{
700
    PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
701
    PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
702
    int ret = 0;
703

    
704
    if (info->exit)
705
        ret = info->exit(pci_dev);
706
    if (ret)
707
        return ret;
708

    
709
    pci_unregister_io_regions(pci_dev);
710
    do_pci_unregister_device(pci_dev);
711
    return 0;
712
}
713

    
714
void pci_register_bar(PCIDevice *pci_dev, int region_num,
715
                            pcibus_t size, int type,
716
                            PCIMapIORegionFunc *map_func)
717
{
718
    PCIIORegion *r;
719
    uint32_t addr;
720
    pcibus_t wmask;
721

    
722
    if ((unsigned int)region_num >= PCI_NUM_REGIONS)
723
        return;
724

    
725
    if (size & (size-1)) {
726
        fprintf(stderr, "ERROR: PCI region size must be pow2 "
727
                    "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
728
        exit(1);
729
    }
730

    
731
    r = &pci_dev->io_regions[region_num];
732
    r->addr = PCI_BAR_UNMAPPED;
733
    r->size = size;
734
    r->filtered_size = size;
735
    r->type = type;
736
    r->map_func = map_func;
737

    
738
    wmask = ~(size - 1);
739
    addr = pci_bar(pci_dev, region_num);
740
    if (region_num == PCI_ROM_SLOT) {
741
        /* ROM enable bit is writeable */
742
        wmask |= PCI_ROM_ADDRESS_ENABLE;
743
    }
744
    pci_set_long(pci_dev->config + addr, type);
745
    if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
746
        r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
747
        pci_set_quad(pci_dev->wmask + addr, wmask);
748
        pci_set_quad(pci_dev->cmask + addr, ~0ULL);
749
    } else {
750
        pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
751
        pci_set_long(pci_dev->cmask + addr, 0xffffffff);
752
    }
753
}
754

    
755
static uint32_t pci_config_get_io_base(PCIDevice *d,
756
                                       uint32_t base, uint32_t base_upper16)
757
{
758
    uint32_t val;
759

    
760
    val = ((uint32_t)d->config[base] & PCI_IO_RANGE_MASK) << 8;
761
    if (d->config[base] & PCI_IO_RANGE_TYPE_32) {
762
        val |= (uint32_t)pci_get_word(d->config + base_upper16) << 16;
763
    }
764
    return val;
765
}
766

    
767
static pcibus_t pci_config_get_memory_base(PCIDevice *d, uint32_t base)
768
{
769
    return ((pcibus_t)pci_get_word(d->config + base) & PCI_MEMORY_RANGE_MASK)
770
        << 16;
771
}
772

    
773
static pcibus_t pci_config_get_pref_base(PCIDevice *d,
774
                                         uint32_t base, uint32_t upper)
775
{
776
    pcibus_t tmp;
777
    pcibus_t val;
778

    
779
    tmp = (pcibus_t)pci_get_word(d->config + base);
780
    val = (tmp & PCI_PREF_RANGE_MASK) << 16;
781
    if (tmp & PCI_PREF_RANGE_TYPE_64) {
782
        val |= (pcibus_t)pci_get_long(d->config + upper) << 32;
783
    }
784
    return val;
785
}
786

    
787
static pcibus_t pci_bridge_get_base(PCIDevice *bridge, uint8_t type)
788
{
789
    pcibus_t base;
790
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
791
        base = pci_config_get_io_base(bridge,
792
                                      PCI_IO_BASE, PCI_IO_BASE_UPPER16);
793
    } else {
794
        if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
795
            base = pci_config_get_pref_base(
796
                bridge, PCI_PREF_MEMORY_BASE, PCI_PREF_BASE_UPPER32);
797
        } else {
798
            base = pci_config_get_memory_base(bridge, PCI_MEMORY_BASE);
799
        }
800
    }
801

    
802
    return base;
803
}
804

    
805
static pcibus_t pci_bridge_get_limit(PCIDevice *bridge, uint8_t type)
806
{
807
    pcibus_t limit;
808
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
809
        limit = pci_config_get_io_base(bridge,
810
                                      PCI_IO_LIMIT, PCI_IO_LIMIT_UPPER16);
811
        limit |= 0xfff;         /* PCI bridge spec 3.2.5.6. */
812
    } else {
813
        if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
814
            limit = pci_config_get_pref_base(
815
                bridge, PCI_PREF_MEMORY_LIMIT, PCI_PREF_LIMIT_UPPER32);
816
        } else {
817
            limit = pci_config_get_memory_base(bridge, PCI_MEMORY_LIMIT);
818
        }
819
        limit |= 0xfffff;       /* PCI bridge spec 3.2.5.{1, 8}. */
820
    }
821
    return limit;
822
}
823

    
824
static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
825
                              uint8_t type)
826
{
827
    pcibus_t base = *addr;
828
    pcibus_t limit = *addr + *size - 1;
829
    PCIDevice *br;
830

    
831
    for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
832
        uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
833

    
834
        if (type & PCI_BASE_ADDRESS_SPACE_IO) {
835
            if (!(cmd & PCI_COMMAND_IO)) {
836
                goto no_map;
837
            }
838
        } else {
839
            if (!(cmd & PCI_COMMAND_MEMORY)) {
840
                goto no_map;
841
            }
842
        }
843

    
844
        base = MAX(base, pci_bridge_get_base(br, type));
845
        limit = MIN(limit, pci_bridge_get_limit(br, type));
846
    }
847

    
848
    if (base > limit) {
849
        goto no_map;
850
    }
851
    *addr = base;
852
    *size = limit - base + 1;
853
    return;
854
no_map:
855
    *addr = PCI_BAR_UNMAPPED;
856
    *size = 0;
857
}
858

    
859
static pcibus_t pci_bar_address(PCIDevice *d,
860
                                int reg, uint8_t type, pcibus_t size)
861
{
862
    pcibus_t new_addr, last_addr;
863
    int bar = pci_bar(d, reg);
864
    uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
865

    
866
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
867
        if (!(cmd & PCI_COMMAND_IO)) {
868
            return PCI_BAR_UNMAPPED;
869
        }
870
        new_addr = pci_get_long(d->config + bar) & ~(size - 1);
871
        last_addr = new_addr + size - 1;
872
        /* NOTE: we have only 64K ioports on PC */
873
        if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
874
            return PCI_BAR_UNMAPPED;
875
        }
876
        return new_addr;
877
    }
878

    
879
    if (!(cmd & PCI_COMMAND_MEMORY)) {
880
        return PCI_BAR_UNMAPPED;
881
    }
882
    if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
883
        new_addr = pci_get_quad(d->config + bar);
884
    } else {
885
        new_addr = pci_get_long(d->config + bar);
886
    }
887
    /* the ROM slot has a specific enable bit */
888
    if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
889
        return PCI_BAR_UNMAPPED;
890
    }
891
    new_addr &= ~(size - 1);
892
    last_addr = new_addr + size - 1;
893
    /* NOTE: we do not support wrapping */
894
    /* XXX: as we cannot support really dynamic
895
       mappings, we handle specific values as invalid
896
       mappings. */
897
    if (last_addr <= new_addr || new_addr == 0 ||
898
        last_addr == PCI_BAR_UNMAPPED) {
899
        return PCI_BAR_UNMAPPED;
900
    }
901

    
902
    /* Now pcibus_t is 64bit.
903
     * Check if 32 bit BAR wraps around explicitly.
904
     * Without this, PC ide doesn't work well.
905
     * TODO: remove this work around.
906
     */
907
    if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
908
        return PCI_BAR_UNMAPPED;
909
    }
910

    
911
    /*
912
     * OS is allowed to set BAR beyond its addressable
913
     * bits. For example, 32 bit OS can set 64bit bar
914
     * to >4G. Check it. TODO: we might need to support
915
     * it in the future for e.g. PAE.
916
     */
917
    if (last_addr >= TARGET_PHYS_ADDR_MAX) {
918
        return PCI_BAR_UNMAPPED;
919
    }
920

    
921
    return new_addr;
922
}
923

    
924
static void pci_update_mappings(PCIDevice *d)
925
{
926
    PCIIORegion *r;
927
    int i;
928
    pcibus_t new_addr, filtered_size;
929

    
930
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
931
        r = &d->io_regions[i];
932

    
933
        /* this region isn't registered */
934
        if (!r->size)
935
            continue;
936

    
937
        new_addr = pci_bar_address(d, i, r->type, r->size);
938

    
939
        /* bridge filtering */
940
        filtered_size = r->size;
941
        if (new_addr != PCI_BAR_UNMAPPED) {
942
            pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
943
        }
944

    
945
        /* This bar isn't changed */
946
        if (new_addr == r->addr && filtered_size == r->filtered_size)
947
            continue;
948

    
949
        /* now do the real mapping */
950
        if (r->addr != PCI_BAR_UNMAPPED) {
951
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
952
                int class;
953
                /* NOTE: specific hack for IDE in PC case:
954
                   only one byte must be mapped. */
955
                class = pci_get_word(d->config + PCI_CLASS_DEVICE);
956
                if (class == 0x0101 && r->size == 4) {
957
                    isa_unassign_ioport(r->addr + 2, 1);
958
                } else {
959
                    isa_unassign_ioport(r->addr, r->filtered_size);
960
                }
961
            } else {
962
                cpu_register_physical_memory(pci_to_cpu_addr(d->bus, r->addr),
963
                                             r->filtered_size,
964
                                             IO_MEM_UNASSIGNED);
965
                qemu_unregister_coalesced_mmio(r->addr, r->filtered_size);
966
            }
967
        }
968
        r->addr = new_addr;
969
        r->filtered_size = filtered_size;
970
        if (r->addr != PCI_BAR_UNMAPPED) {
971
            /*
972
             * TODO: currently almost all the map funcions assumes
973
             * filtered_size == size and addr & ~(size - 1) == addr.
974
             * However with bridge filtering, they aren't always true.
975
             * Teach them such cases, such that filtered_size < size and
976
             * addr & (size - 1) != 0.
977
             */
978
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
979
                r->map_func(d, i, r->addr, r->filtered_size, r->type);
980
            } else {
981
                r->map_func(d, i, pci_to_cpu_addr(d->bus, r->addr),
982
                            r->filtered_size, r->type);
983
            }
984
        }
985
    }
986
}
987

    
988
static inline int pci_irq_disabled(PCIDevice *d)
989
{
990
    return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
991
}
992

    
993
/* Called after interrupt disabled field update in config space,
994
 * assert/deassert interrupts if necessary.
995
 * Gets original interrupt disable bit value (before update). */
996
static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
997
{
998
    int i, disabled = pci_irq_disabled(d);
999
    if (disabled == was_irq_disabled)
1000
        return;
1001
    for (i = 0; i < PCI_NUM_PINS; ++i) {
1002
        int state = pci_irq_state(d, i);
1003
        pci_change_irq_level(d, i, disabled ? -state : state);
1004
    }
1005
}
1006

    
1007
uint32_t pci_default_read_config(PCIDevice *d,
1008
                                 uint32_t address, int len)
1009
{
1010
    uint32_t val = 0;
1011
    assert(len == 1 || len == 2 || len == 4);
1012
    len = MIN(len, pci_config_size(d) - address);
1013
    memcpy(&val, d->config + address, len);
1014
    return le32_to_cpu(val);
1015
}
1016

    
1017
void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
1018
{
1019
    int i, was_irq_disabled = pci_irq_disabled(d);
1020
    uint32_t config_size = pci_config_size(d);
1021

    
1022
    for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
1023
        uint8_t wmask = d->wmask[addr + i];
1024
        d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
1025
    }
1026
    if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
1027
        ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
1028
        ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
1029
        range_covers_byte(addr, l, PCI_COMMAND))
1030
        pci_update_mappings(d);
1031

    
1032
    if (range_covers_byte(addr, l, PCI_COMMAND))
1033
        pci_update_irq_disabled(d, was_irq_disabled);
1034
}
1035

    
1036
/***********************************************************/
1037
/* generic PCI irq support */
1038

    
1039
/* 0 <= irq_num <= 3. level must be 0 or 1 */
1040
static void pci_set_irq(void *opaque, int irq_num, int level)
1041
{
1042
    PCIDevice *pci_dev = opaque;
1043
    int change;
1044

    
1045
    change = level - pci_irq_state(pci_dev, irq_num);
1046
    if (!change)
1047
        return;
1048

    
1049
    pci_set_irq_state(pci_dev, irq_num, level);
1050
    pci_update_irq_status(pci_dev);
1051
    if (pci_irq_disabled(pci_dev))
1052
        return;
1053
    pci_change_irq_level(pci_dev, irq_num, change);
1054
}
1055

    
1056
/***********************************************************/
1057
/* monitor info on PCI */
1058

    
1059
typedef struct {
1060
    uint16_t class;
1061
    const char *desc;
1062
} pci_class_desc;
1063

    
1064
static const pci_class_desc pci_class_descriptions[] =
1065
{
1066
    { 0x0100, "SCSI controller"},
1067
    { 0x0101, "IDE controller"},
1068
    { 0x0102, "Floppy controller"},
1069
    { 0x0103, "IPI controller"},
1070
    { 0x0104, "RAID controller"},
1071
    { 0x0106, "SATA controller"},
1072
    { 0x0107, "SAS controller"},
1073
    { 0x0180, "Storage controller"},
1074
    { 0x0200, "Ethernet controller"},
1075
    { 0x0201, "Token Ring controller"},
1076
    { 0x0202, "FDDI controller"},
1077
    { 0x0203, "ATM controller"},
1078
    { 0x0280, "Network controller"},
1079
    { 0x0300, "VGA controller"},
1080
    { 0x0301, "XGA controller"},
1081
    { 0x0302, "3D controller"},
1082
    { 0x0380, "Display controller"},
1083
    { 0x0400, "Video controller"},
1084
    { 0x0401, "Audio controller"},
1085
    { 0x0402, "Phone"},
1086
    { 0x0480, "Multimedia controller"},
1087
    { 0x0500, "RAM controller"},
1088
    { 0x0501, "Flash controller"},
1089
    { 0x0580, "Memory controller"},
1090
    { 0x0600, "Host bridge"},
1091
    { 0x0601, "ISA bridge"},
1092
    { 0x0602, "EISA bridge"},
1093
    { 0x0603, "MC bridge"},
1094
    { 0x0604, "PCI bridge"},
1095
    { 0x0605, "PCMCIA bridge"},
1096
    { 0x0606, "NUBUS bridge"},
1097
    { 0x0607, "CARDBUS bridge"},
1098
    { 0x0608, "RACEWAY bridge"},
1099
    { 0x0680, "Bridge"},
1100
    { 0x0c03, "USB controller"},
1101
    { 0, NULL}
1102
};
1103

    
1104
static void pci_for_each_device_under_bus(PCIBus *bus,
1105
                                          void (*fn)(PCIBus *b, PCIDevice *d))
1106
{
1107
    PCIDevice *d;
1108
    int devfn;
1109

    
1110
    for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1111
        d = bus->devices[devfn];
1112
        if (d) {
1113
            fn(bus, d);
1114
        }
1115
    }
1116
}
1117

    
1118
void pci_for_each_device(PCIBus *bus, int bus_num,
1119
                         void (*fn)(PCIBus *b, PCIDevice *d))
1120
{
1121
    bus = pci_find_bus(bus, bus_num);
1122

    
1123
    if (bus) {
1124
        pci_for_each_device_under_bus(bus, fn);
1125
    }
1126
}
1127

    
1128
static void pci_device_print(Monitor *mon, QDict *device)
1129
{
1130
    QDict *qdict;
1131
    QListEntry *entry;
1132
    uint64_t addr, size;
1133

    
1134
    monitor_printf(mon, "  Bus %2" PRId64 ", ", qdict_get_int(device, "bus"));
1135
    monitor_printf(mon, "device %3" PRId64 ", function %" PRId64 ":\n",
1136
                        qdict_get_int(device, "slot"),
1137
                        qdict_get_int(device, "function"));
1138
    monitor_printf(mon, "    ");
1139

    
1140
    qdict = qdict_get_qdict(device, "class_info");
1141
    if (qdict_haskey(qdict, "desc")) {
1142
        monitor_printf(mon, "%s", qdict_get_str(qdict, "desc"));
1143
    } else {
1144
        monitor_printf(mon, "Class %04" PRId64, qdict_get_int(qdict, "class"));
1145
    }
1146

    
1147
    qdict = qdict_get_qdict(device, "id");
1148
    monitor_printf(mon, ": PCI device %04" PRIx64 ":%04" PRIx64 "\n",
1149
                        qdict_get_int(qdict, "device"),
1150
                        qdict_get_int(qdict, "vendor"));
1151

    
1152
    if (qdict_haskey(device, "irq")) {
1153
        monitor_printf(mon, "      IRQ %" PRId64 ".\n",
1154
                            qdict_get_int(device, "irq"));
1155
    }
1156

    
1157
    if (qdict_haskey(device, "pci_bridge")) {
1158
        QDict *info;
1159

    
1160
        qdict = qdict_get_qdict(device, "pci_bridge");
1161

    
1162
        info = qdict_get_qdict(qdict, "bus");
1163
        monitor_printf(mon, "      BUS %" PRId64 ".\n",
1164
                            qdict_get_int(info, "number"));
1165
        monitor_printf(mon, "      secondary bus %" PRId64 ".\n",
1166
                            qdict_get_int(info, "secondary"));
1167
        monitor_printf(mon, "      subordinate bus %" PRId64 ".\n",
1168
                            qdict_get_int(info, "subordinate"));
1169

    
1170
        info = qdict_get_qdict(qdict, "io_range");
1171
        monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1172
                       qdict_get_int(info, "base"),
1173
                       qdict_get_int(info, "limit"));
1174

    
1175
        info = qdict_get_qdict(qdict, "memory_range");
1176
        monitor_printf(mon,
1177
                       "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1178
                       qdict_get_int(info, "base"),
1179
                       qdict_get_int(info, "limit"));
1180

    
1181
        info = qdict_get_qdict(qdict, "prefetchable_range");
1182
        monitor_printf(mon, "      prefetchable memory range "
1183
                       "[0x%08"PRIx64", 0x%08"PRIx64"]\n",
1184
                       qdict_get_int(info, "base"),
1185
        qdict_get_int(info, "limit"));
1186
    }
1187

    
1188
    QLIST_FOREACH_ENTRY(qdict_get_qlist(device, "regions"), entry) {
1189
        qdict = qobject_to_qdict(qlist_entry_obj(entry));
1190
        monitor_printf(mon, "      BAR%d: ", (int) qdict_get_int(qdict, "bar"));
1191

    
1192
        addr = qdict_get_int(qdict, "address");
1193
        size = qdict_get_int(qdict, "size");
1194

    
1195
        if (!strcmp(qdict_get_str(qdict, "type"), "io")) {
1196
            monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1197
                                " [0x%04"FMT_PCIBUS"].\n",
1198
                                addr, addr + size - 1);
1199
        } else {
1200
            monitor_printf(mon, "%d bit%s memory at 0x%08"FMT_PCIBUS
1201
                               " [0x%08"FMT_PCIBUS"].\n",
1202
                                qdict_get_bool(qdict, "mem_type_64") ? 64 : 32,
1203
                                qdict_get_bool(qdict, "prefetch") ?
1204
                                " prefetchable" : "", addr, addr + size - 1);
1205
        }
1206
    }
1207

    
1208
    monitor_printf(mon, "      id \"%s\"\n", qdict_get_str(device, "qdev_id"));
1209

    
1210
    if (qdict_haskey(device, "pci_bridge")) {
1211
        qdict = qdict_get_qdict(device, "pci_bridge");
1212
        if (qdict_haskey(qdict, "devices")) {
1213
            QListEntry *dev;
1214
            QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1215
                pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1216
            }
1217
        }
1218
    }
1219
}
1220

    
1221
void do_pci_info_print(Monitor *mon, const QObject *data)
1222
{
1223
    QListEntry *bus, *dev;
1224

    
1225
    QLIST_FOREACH_ENTRY(qobject_to_qlist(data), bus) {
1226
        QDict *qdict = qobject_to_qdict(qlist_entry_obj(bus));
1227
        QLIST_FOREACH_ENTRY(qdict_get_qlist(qdict, "devices"), dev) {
1228
            pci_device_print(mon, qobject_to_qdict(qlist_entry_obj(dev)));
1229
        }
1230
    }
1231
}
1232

    
1233
static QObject *pci_get_dev_class(const PCIDevice *dev)
1234
{
1235
    int class;
1236
    const pci_class_desc *desc;
1237

    
1238
    class = pci_get_word(dev->config + PCI_CLASS_DEVICE);
1239
    desc = pci_class_descriptions;
1240
    while (desc->desc && class != desc->class)
1241
        desc++;
1242

    
1243
    if (desc->desc) {
1244
        return qobject_from_jsonf("{ 'desc': %s, 'class': %d }",
1245
                                  desc->desc, class);
1246
    } else {
1247
        return qobject_from_jsonf("{ 'class': %d }", class);
1248
    }
1249
}
1250

    
1251
static QObject *pci_get_dev_id(const PCIDevice *dev)
1252
{
1253
    return qobject_from_jsonf("{ 'device': %d, 'vendor': %d }",
1254
                              pci_get_word(dev->config + PCI_VENDOR_ID),
1255
                              pci_get_word(dev->config + PCI_DEVICE_ID));
1256
}
1257

    
1258
static QObject *pci_get_regions_list(const PCIDevice *dev)
1259
{
1260
    int i;
1261
    QList *regions_list;
1262

    
1263
    regions_list = qlist_new();
1264

    
1265
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
1266
        QObject *obj;
1267
        const PCIIORegion *r = &dev->io_regions[i];
1268

    
1269
        if (!r->size) {
1270
            continue;
1271
        }
1272

    
1273
        if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1274
            obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'io', "
1275
                                     "'address': %" PRId64 ", "
1276
                                     "'size': %" PRId64 " }",
1277
                                     i, r->addr, r->size);
1278
        } else {
1279
            int mem_type_64 = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64;
1280

    
1281
            obj = qobject_from_jsonf("{ 'bar': %d, 'type': 'memory', "
1282
                                     "'mem_type_64': %i, 'prefetch': %i, "
1283
                                     "'address': %" PRId64 ", "
1284
                                     "'size': %" PRId64 " }",
1285
                                     i, mem_type_64,
1286
                                     r->type & PCI_BASE_ADDRESS_MEM_PREFETCH,
1287
                                     r->addr, r->size);
1288
        }
1289

    
1290
        qlist_append_obj(regions_list, obj);
1291
    }
1292

    
1293
    return QOBJECT(regions_list);
1294
}
1295

    
1296
static QObject *pci_get_devices_list(PCIBus *bus, int bus_num);
1297

    
1298
static QObject *pci_get_dev_dict(PCIDevice *dev, PCIBus *bus, int bus_num)
1299
{
1300
    uint8_t type;
1301
    QObject *obj;
1302

    
1303
    obj = qobject_from_jsonf("{ 'bus': %d, 'slot': %d, 'function': %d,"                                       "'class_info': %p, 'id': %p, 'regions': %p,"
1304
                              " 'qdev_id': %s }",
1305
                              bus_num,
1306
                              PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn),
1307
                              pci_get_dev_class(dev), pci_get_dev_id(dev),
1308
                              pci_get_regions_list(dev),
1309
                              dev->qdev.id ? dev->qdev.id : "");
1310

    
1311
    if (dev->config[PCI_INTERRUPT_PIN] != 0) {
1312
        QDict *qdict = qobject_to_qdict(obj);
1313
        qdict_put(qdict, "irq", qint_from_int(dev->config[PCI_INTERRUPT_LINE]));
1314
    }
1315

    
1316
    type = dev->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
1317
    if (type == PCI_HEADER_TYPE_BRIDGE) {
1318
        QDict *qdict;
1319
        QObject *pci_bridge;
1320

    
1321
        pci_bridge = qobject_from_jsonf("{ 'bus': "
1322
        "{ 'number': %d, 'secondary': %d, 'subordinate': %d }, "
1323
        "'io_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1324
        "'memory_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "}, "
1325
        "'prefetchable_range': { 'base': %" PRId64 ", 'limit': %" PRId64 "} }",
1326
        dev->config[PCI_PRIMARY_BUS], dev->config[PCI_SECONDARY_BUS],
1327
        dev->config[PCI_SUBORDINATE_BUS],
1328
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_IO),
1329
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_IO),
1330
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1331
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY),
1332
        pci_bridge_get_base(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1333
                               PCI_BASE_ADDRESS_MEM_PREFETCH),
1334
        pci_bridge_get_limit(dev, PCI_BASE_ADDRESS_SPACE_MEMORY |
1335
                                PCI_BASE_ADDRESS_MEM_PREFETCH));
1336

    
1337
        if (dev->config[PCI_SECONDARY_BUS] != 0) {
1338
            PCIBus *child_bus = pci_find_bus(bus, dev->config[PCI_SECONDARY_BUS]);
1339

    
1340
            if (child_bus) {
1341
                qdict = qobject_to_qdict(pci_bridge);
1342
                qdict_put_obj(qdict, "devices",
1343
                              pci_get_devices_list(child_bus,
1344
                                                   dev->config[PCI_SECONDARY_BUS]));
1345
            }
1346
        }
1347
        qdict = qobject_to_qdict(obj);
1348
        qdict_put_obj(qdict, "pci_bridge", pci_bridge);
1349
    }
1350

    
1351
    return obj;
1352
}
1353

    
1354
static QObject *pci_get_devices_list(PCIBus *bus, int bus_num)
1355
{
1356
    int devfn;
1357
    PCIDevice *dev;
1358
    QList *dev_list;
1359

    
1360
    dev_list = qlist_new();
1361

    
1362
    for (devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1363
        dev = bus->devices[devfn];
1364
        if (dev) {
1365
            qlist_append_obj(dev_list, pci_get_dev_dict(dev, bus, bus_num));
1366
        }
1367
    }
1368

    
1369
    return QOBJECT(dev_list);
1370
}
1371

    
1372
static QObject *pci_get_bus_dict(PCIBus *bus, int bus_num)
1373
{
1374
    bus = pci_find_bus(bus, bus_num);
1375
    if (bus) {
1376
        return qobject_from_jsonf("{ 'bus': %d, 'devices': %p }",
1377
                                  bus_num, pci_get_devices_list(bus, bus_num));
1378
    }
1379

    
1380
    return NULL;
1381
}
1382

    
1383
/**
1384
 * do_pci_info(): PCI buses and devices information
1385
 *
1386
 * The returned QObject is a QList of all buses. Each bus is
1387
 * represented by a QDict, which has a key with a QList of all
1388
 * PCI devices attached to it. Each device is represented by
1389
 * a QDict.
1390
 *
1391
 * The bus QDict contains the following:
1392
 *
1393
 * - "bus": bus number
1394
 * - "devices": a QList of QDicts, each QDict represents a PCI
1395
 *   device
1396
 *
1397
 * The PCI device QDict contains the following:
1398
 *
1399
 * - "bus": identical to the parent's bus number
1400
 * - "slot": slot number
1401
 * - "function": function number
1402
 * - "class_info": a QDict containing:
1403
 *      - "desc": device class description (optional)
1404
 *      - "class": device class number
1405
 * - "id": a QDict containing:
1406
 *      - "device": device ID
1407
 *      - "vendor": vendor ID
1408
 * - "irq": device's IRQ if assigned (optional)
1409
 * - "qdev_id": qdev id string
1410
 * - "pci_bridge": It's a QDict, only present if this device is a
1411
 *   PCI bridge, contains:
1412
 *      - "bus": bus number
1413
 *      - "secondary": secondary bus number
1414
 *      - "subordinate": subordinate bus number
1415
 *      - "io_range": a QDict with memory range information
1416
 *      - "memory_range": a QDict with memory range information
1417
 *      - "prefetchable_range": a QDict with memory range information
1418
 *      - "devices": a QList of PCI devices if there's any attached (optional)
1419
 * - "regions": a QList of QDicts, each QDict represents a
1420
 *   memory region of this device
1421
 *
1422
 * The memory range QDict contains the following:
1423
 *
1424
 * - "base": base memory address
1425
 * - "limit": limit value
1426
 *
1427
 * The region QDict can be an I/O region or a memory region,
1428
 * an I/O region QDict contains the following:
1429
 *
1430
 * - "type": "io"
1431
 * - "bar": BAR number
1432
 * - "address": memory address
1433
 * - "size": memory size
1434
 *
1435
 * A memory region QDict contains the following:
1436
 *
1437
 * - "type": "memory"
1438
 * - "bar": BAR number
1439
 * - "address": memory address
1440
 * - "size": memory size
1441
 * - "mem_type_64": true or false
1442
 * - "prefetch": true or false
1443
 */
1444
void do_pci_info(Monitor *mon, QObject **ret_data)
1445
{
1446
    QList *bus_list;
1447
    struct PCIHostBus *host;
1448

    
1449
    bus_list = qlist_new();
1450

    
1451
    QLIST_FOREACH(host, &host_buses, next) {
1452
        QObject *obj = pci_get_bus_dict(host->bus, 0);
1453
        if (obj) {
1454
            qlist_append_obj(bus_list, obj);
1455
        }
1456
    }
1457

    
1458
    *ret_data = QOBJECT(bus_list);
1459
}
1460

    
1461
static const char * const pci_nic_models[] = {
1462
    "ne2k_pci",
1463
    "i82551",
1464
    "i82557b",
1465
    "i82559er",
1466
    "rtl8139",
1467
    "e1000",
1468
    "pcnet",
1469
    "virtio",
1470
    NULL
1471
};
1472

    
1473
static const char * const pci_nic_names[] = {
1474
    "ne2k_pci",
1475
    "i82551",
1476
    "i82557b",
1477
    "i82559er",
1478
    "rtl8139",
1479
    "e1000",
1480
    "pcnet",
1481
    "virtio-net-pci",
1482
    NULL
1483
};
1484

    
1485
/* Initialize a PCI NIC.  */
1486
/* FIXME callers should check for failure, but don't */
1487
PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1488
                        const char *default_devaddr)
1489
{
1490
    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1491
    PCIBus *bus;
1492
    int devfn;
1493
    PCIDevice *pci_dev;
1494
    DeviceState *dev;
1495
    int i;
1496

    
1497
    i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1498
    if (i < 0)
1499
        return NULL;
1500

    
1501
    bus = pci_get_bus_devfn(&devfn, devaddr);
1502
    if (!bus) {
1503
        error_report("Invalid PCI device address %s for device %s",
1504
                     devaddr, pci_nic_names[i]);
1505
        return NULL;
1506
    }
1507

    
1508
    pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1509
    dev = &pci_dev->qdev;
1510
    if (nd->name)
1511
        dev->id = qemu_strdup(nd->name);
1512
    qdev_set_nic_properties(dev, nd);
1513
    if (qdev_init(dev) < 0)
1514
        return NULL;
1515
    return pci_dev;
1516
}
1517

    
1518
PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1519
                               const char *default_devaddr)
1520
{
1521
    PCIDevice *res;
1522

    
1523
    if (qemu_show_nic_models(nd->model, pci_nic_models))
1524
        exit(0);
1525

    
1526
    res = pci_nic_init(nd, default_model, default_devaddr);
1527
    if (!res)
1528
        exit(1);
1529
    return res;
1530
}
1531

    
1532
typedef struct {
1533
    PCIDevice dev;
1534
    PCIBus bus;
1535
    uint32_t vid;
1536
    uint32_t did;
1537
} PCIBridge;
1538

    
1539

    
1540
static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1541
{
1542
    pci_update_mappings(d);
1543
}
1544

    
1545
static void pci_bridge_update_mappings(PCIBus *b)
1546
{
1547
    PCIBus *child;
1548

    
1549
    pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1550

    
1551
    QLIST_FOREACH(child, &b->child, sibling) {
1552
        pci_bridge_update_mappings(child);
1553
    }
1554
}
1555

    
1556
static void pci_bridge_write_config(PCIDevice *d,
1557
                             uint32_t address, uint32_t val, int len)
1558
{
1559
    pci_default_write_config(d, address, val, len);
1560

    
1561
    if (/* io base/limit */
1562
        ranges_overlap(address, len, PCI_IO_BASE, 2) ||
1563

    
1564
        /* memory base/limit, prefetchable base/limit and
1565
           io base/limit upper 16 */
1566
        ranges_overlap(address, len, PCI_MEMORY_BASE, 20)) {
1567
        pci_bridge_update_mappings(d->bus);
1568
    }
1569
}
1570

    
1571
PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1572
{
1573
    PCIBus *sec;
1574

    
1575
    if (!bus) {
1576
        return NULL;
1577
    }
1578

    
1579
    if (pci_bus_num(bus) == bus_num) {
1580
        return bus;
1581
    }
1582

    
1583
    /* try child bus */
1584
    if (!bus->parent_dev /* host pci bridge */ ||
1585
        (bus->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1586
         bus_num <= bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {
1587
        for (; bus; bus = sec) {
1588
            QLIST_FOREACH(sec, &bus->child, sibling) {
1589
                assert(sec->parent_dev);
1590
                if (sec->parent_dev->config[PCI_SECONDARY_BUS] == bus_num) {
1591
                    return sec;
1592
                }
1593
                if (sec->parent_dev->config[PCI_SECONDARY_BUS] < bus_num &&
1594
                    bus_num <= sec->parent_dev->config[PCI_SUBORDINATE_BUS]) {
1595
                    break;
1596
                }
1597
            }
1598
        }
1599
    }
1600

    
1601
    return NULL;
1602
}
1603

    
1604
PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function)
1605
{
1606
    bus = pci_find_bus(bus, bus_num);
1607

    
1608
    if (!bus)
1609
        return NULL;
1610

    
1611
    return bus->devices[PCI_DEVFN(slot, function)];
1612
}
1613

    
1614
static int pci_bridge_initfn(PCIDevice *dev)
1615
{
1616
    PCIBridge *s = DO_UPCAST(PCIBridge, dev, dev);
1617

    
1618
    pci_config_set_vendor_id(s->dev.config, s->vid);
1619
    pci_config_set_device_id(s->dev.config, s->did);
1620

    
1621
    pci_set_word(dev->config + PCI_STATUS,
1622
                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1623
    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_PCI);
1624
    dev->config[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_BRIDGE;
1625
    pci_set_word(dev->config + PCI_SEC_STATUS,
1626
                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1627
    return 0;
1628
}
1629

    
1630
static int pci_bridge_exitfn(PCIDevice *pci_dev)
1631
{
1632
    PCIBridge *s = DO_UPCAST(PCIBridge, dev, pci_dev);
1633
    PCIBus *bus = &s->bus;
1634
    pci_unregister_secondary_bus(bus);
1635
    return 0;
1636
}
1637

    
1638
PCIBus *pci_bridge_init(PCIBus *bus, int devfn, uint16_t vid, uint16_t did,
1639
                        pci_map_irq_fn map_irq, const char *name)
1640
{
1641
    PCIDevice *dev;
1642
    PCIBridge *s;
1643

    
1644
    dev = pci_create(bus, devfn, "pci-bridge");
1645
    qdev_prop_set_uint32(&dev->qdev, "vendorid", vid);
1646
    qdev_prop_set_uint32(&dev->qdev, "deviceid", did);
1647
    qdev_init_nofail(&dev->qdev);
1648

    
1649
    s = DO_UPCAST(PCIBridge, dev, dev);
1650
    pci_register_secondary_bus(bus, &s->bus, &s->dev, map_irq, name);
1651
    return &s->bus;
1652
}
1653

    
1654
PCIDevice *pci_bridge_get_device(PCIBus *bus)
1655
{
1656
    return bus->parent_dev;
1657
}
1658

    
1659
static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1660
{
1661
    PCIDevice *pci_dev = (PCIDevice *)qdev;
1662
    PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1663
    PCIBus *bus;
1664
    int devfn, rc;
1665

    
1666
    /* initialize cap_present for pci_is_express() and pci_config_size() */
1667
    if (info->is_express) {
1668
        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1669
    }
1670

    
1671
    bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1672
    devfn = pci_dev->devfn;
1673
    pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
1674
                                     info->config_read, info->config_write,
1675
                                     info->header_type);
1676
    if (pci_dev == NULL)
1677
        return -1;
1678
    rc = info->init(pci_dev);
1679
    if (rc != 0) {
1680
        do_pci_unregister_device(pci_dev);
1681
        return rc;
1682
    }
1683

    
1684
    /* rom loading */
1685
    if (pci_dev->romfile == NULL && info->romfile != NULL)
1686
        pci_dev->romfile = qemu_strdup(info->romfile);
1687
    pci_add_option_rom(pci_dev);
1688

    
1689
    if (qdev->hotplugged)
1690
        bus->hotplug(bus->hotplug_qdev, pci_dev, 1);
1691
    return 0;
1692
}
1693

    
1694
static int pci_unplug_device(DeviceState *qdev)
1695
{
1696
    PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1697

    
1698
    dev->bus->hotplug(dev->bus->hotplug_qdev, dev, 0);
1699
    return 0;
1700
}
1701

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

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

    
1719
PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1720
{
1721
    DeviceState *dev;
1722

    
1723
    dev = qdev_create(&bus->qbus, name);
1724
    qdev_prop_set_uint32(dev, "addr", devfn);
1725
    return DO_UPCAST(PCIDevice, qdev, dev);
1726
}
1727

    
1728
PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1729
{
1730
    PCIDevice *dev = pci_create(bus, devfn, name);
1731
    qdev_init_nofail(&dev->qdev);
1732
    return dev;
1733
}
1734

    
1735
static int pci_find_space(PCIDevice *pdev, uint8_t size)
1736
{
1737
    int config_size = pci_config_size(pdev);
1738
    int offset = PCI_CONFIG_HEADER_SIZE;
1739
    int i;
1740
    for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1741
        if (pdev->used[i])
1742
            offset = i + 1;
1743
        else if (i - offset + 1 == size)
1744
            return offset;
1745
    return 0;
1746
}
1747

    
1748
static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1749
                                        uint8_t *prev_p)
1750
{
1751
    uint8_t next, prev;
1752

    
1753
    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1754
        return 0;
1755

    
1756
    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1757
         prev = next + PCI_CAP_LIST_NEXT)
1758
        if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1759
            break;
1760

    
1761
    if (prev_p)
1762
        *prev_p = prev;
1763
    return next;
1764
}
1765

    
1766
static void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1767
{
1768
    cpu_register_physical_memory(addr, size, pdev->rom_offset);
1769
}
1770

    
1771
/* Add an option rom for the device */
1772
static int pci_add_option_rom(PCIDevice *pdev)
1773
{
1774
    int size;
1775
    char *path;
1776
    void *ptr;
1777

    
1778
    if (!pdev->romfile)
1779
        return 0;
1780
    if (strlen(pdev->romfile) == 0)
1781
        return 0;
1782

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

    
1797
    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1798
    if (path == NULL) {
1799
        path = qemu_strdup(pdev->romfile);
1800
    }
1801

    
1802
    size = get_image_size(path);
1803
    if (size < 0) {
1804
        error_report("%s: failed to find romfile \"%s\"",
1805
                     __FUNCTION__, pdev->romfile);
1806
        return -1;
1807
    }
1808
    if (size & (size - 1)) {
1809
        size = 1 << qemu_fls(size);
1810
    }
1811

    
1812
    pdev->rom_offset = qemu_ram_alloc(size);
1813

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

    
1818
    pci_register_bar(pdev, PCI_ROM_SLOT, size,
1819
                     0, pci_map_option_rom);
1820

    
1821
    return 0;
1822
}
1823

    
1824
/* Reserve space and add capability to the linked list in pci config space */
1825
int pci_add_capability_at_offset(PCIDevice *pdev, uint8_t cap_id,
1826
                                 uint8_t offset, uint8_t size)
1827
{
1828
    uint8_t *config = pdev->config + offset;
1829
    config[PCI_CAP_LIST_ID] = cap_id;
1830
    config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1831
    pdev->config[PCI_CAPABILITY_LIST] = offset;
1832
    pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1833
    memset(pdev->used + offset, 0xFF, size);
1834
    /* Make capability read-only by default */
1835
    memset(pdev->wmask + offset, 0, size);
1836
    /* Check capability by default */
1837
    memset(pdev->cmask + offset, 0xFF, size);
1838
    return offset;
1839
}
1840

    
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, uint8_t size)
1844
{
1845
    uint8_t offset = pci_find_space(pdev, size);
1846
    if (!offset) {
1847
        return -ENOSPC;
1848
    }
1849
    return pci_add_capability_at_offset(pdev, cap_id, offset, size);
1850
}
1851

    
1852
/* Unlink capability from the pci config space. */
1853
void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1854
{
1855
    uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
1856
    if (!offset)
1857
        return;
1858
    pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
1859
    /* Make capability writeable again */
1860
    memset(pdev->wmask + offset, 0xff, size);
1861
    /* Clear cmask as device-specific registers can't be checked */
1862
    memset(pdev->cmask + offset, 0, size);
1863
    memset(pdev->used + offset, 0, size);
1864

    
1865
    if (!pdev->config[PCI_CAPABILITY_LIST])
1866
        pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
1867
}
1868

    
1869
/* Reserve space for capability at a known offset (to call after load). */
1870
void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
1871
{
1872
    memset(pdev->used + offset, 0xff, size);
1873
}
1874

    
1875
uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
1876
{
1877
    return pci_find_capability_list(pdev, cap_id, NULL);
1878
}
1879

    
1880
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
1881
{
1882
    PCIDevice *d = (PCIDevice *)dev;
1883
    const pci_class_desc *desc;
1884
    char ctxt[64];
1885
    PCIIORegion *r;
1886
    int i, class;
1887

    
1888
    class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1889
    desc = pci_class_descriptions;
1890
    while (desc->desc && class != desc->class)
1891
        desc++;
1892
    if (desc->desc) {
1893
        snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
1894
    } else {
1895
        snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
1896
    }
1897

    
1898
    monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
1899
                   "pci id %04x:%04x (sub %04x:%04x)\n",
1900
                   indent, "", ctxt,
1901
                   d->config[PCI_SECONDARY_BUS],
1902
                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
1903
                   pci_get_word(d->config + PCI_VENDOR_ID),
1904
                   pci_get_word(d->config + PCI_DEVICE_ID),
1905
                   pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
1906
                   pci_get_word(d->config + PCI_SUBSYSTEM_ID));
1907
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
1908
        r = &d->io_regions[i];
1909
        if (!r->size)
1910
            continue;
1911
        monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
1912
                       " [0x%"FMT_PCIBUS"]\n",
1913
                       indent, "",
1914
                       i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
1915
                       r->addr, r->addr + r->size - 1);
1916
    }
1917
}
1918

    
1919
static PCIDeviceInfo bridge_info = {
1920
    .qdev.name    = "pci-bridge",
1921
    .qdev.size    = sizeof(PCIBridge),
1922
    .init         = pci_bridge_initfn,
1923
    .exit         = pci_bridge_exitfn,
1924
    .config_write = pci_bridge_write_config,
1925
    .header_type  = PCI_HEADER_TYPE_BRIDGE,
1926
    .qdev.props   = (Property[]) {
1927
        DEFINE_PROP_HEX32("vendorid", PCIBridge, vid, 0),
1928
        DEFINE_PROP_HEX32("deviceid", PCIBridge, did, 0),
1929
        DEFINE_PROP_END_OF_LIST(),
1930
    }
1931
};
1932

    
1933
static void pci_register_devices(void)
1934
{
1935
    pci_qdev_register(&bridge_info);
1936
}
1937

    
1938
device_init(pci_register_devices)