Statistics
| Branch: | Revision:

root / hw / pci.c @ 3d09c490

History | View | Annotate | Download (46.7 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

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

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

    
48
    QLIST_HEAD(, PCIBus) child; /* this will be replaced by qdev later */
49
    QLIST_ENTRY(PCIBus) sibling;/* this will be replaced by qdev later */
50

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

    
57
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent);
58

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

    
70
static void pci_update_mappings(PCIDevice *d);
71
static void pci_set_irq(void *opaque, int irq_num, int level);
72
static int pci_add_option_rom(PCIDevice *pdev);
73

    
74
target_phys_addr_t pci_mem_base;
75
static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
76
static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
77

    
78
struct PCIHostBus {
79
    int domain;
80
    struct PCIBus *bus;
81
    QLIST_ENTRY(PCIHostBus) next;
82
};
83
static QLIST_HEAD(, PCIHostBus) host_buses;
84

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

    
97
static int pci_bar(PCIDevice *d, int reg)
98
{
99
    uint8_t type;
100

    
101
    if (reg != PCI_ROM_SLOT)
102
        return PCI_BASE_ADDRESS_0 + reg * 4;
103

    
104
    type = d->config[PCI_HEADER_TYPE] & ~PCI_HEADER_TYPE_MULTI_FUNCTION;
105
    return type == PCI_HEADER_TYPE_BRIDGE ? PCI_ROM_ADDRESS1 : PCI_ROM_ADDRESS;
106
}
107

    
108
static inline int pci_irq_state(PCIDevice *d, int irq_num)
109
{
110
        return (d->irq_state >> irq_num) & 0x1;
111
}
112

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

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

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

    
144
static void pci_device_reset(PCIDevice *dev)
145
{
146
    int r;
147

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

    
163
static void pci_bus_reset(void *opaque)
164
{
165
    PCIBus *bus = opaque;
166
    int i;
167

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

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

    
187
PCIBus *pci_find_root_bus(int domain)
188
{
189
    struct PCIHostBus *host;
190

    
191
    QLIST_FOREACH(host, &host_buses, next) {
192
        if (host->domain == domain) {
193
            return host->bus;
194
        }
195
    }
196

    
197
    return NULL;
198
}
199

    
200
void pci_bus_new_inplace(PCIBus *bus, DeviceState *parent,
201
                         const char *name, int devfn_min)
202
{
203
    qbus_create_inplace(&bus->qbus, &pci_bus_info, parent, name);
204
    bus->devfn_min = devfn_min;
205

    
206
    /* host bridge */
207
    QLIST_INIT(&bus->child);
208
    pci_host_bus_register(0, bus); /* for now only pci domain 0 is supported */
209

    
210
    vmstate_register(-1, &vmstate_pcibus, bus);
211
    qemu_register_reset(pci_bus_reset, bus);
212
}
213

    
214
PCIBus *pci_bus_new(DeviceState *parent, const char *name, int devfn_min)
215
{
216
    PCIBus *bus;
217

    
218
    bus = qemu_mallocz(sizeof(*bus));
219
    bus->qbus.qdev_allocated = 1;
220
    pci_bus_new_inplace(bus, parent, name, devfn_min);
221
    return bus;
222
}
223

    
224
void pci_bus_irqs(PCIBus *bus, pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
225
                  void *irq_opaque, int nirq)
226
{
227
    bus->set_irq = set_irq;
228
    bus->map_irq = map_irq;
229
    bus->irq_opaque = irq_opaque;
230
    bus->nirq = nirq;
231
    bus->irq_count = qemu_mallocz(nirq * sizeof(bus->irq_count[0]));
232
}
233

    
234
void pci_bus_hotplug(PCIBus *bus, pci_hotplug_fn hotplug)
235
{
236
    bus->qbus.allow_hotplug = 1;
237
    bus->hotplug = hotplug;
238
}
239

    
240
PCIBus *pci_register_bus(DeviceState *parent, const char *name,
241
                         pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
242
                         void *irq_opaque, int devfn_min, int nirq)
243
{
244
    PCIBus *bus;
245

    
246
    bus = pci_bus_new(parent, name, devfn_min);
247
    pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
248
    return bus;
249
}
250

    
251
static void pci_register_secondary_bus(PCIBus *parent,
252
                                       PCIBus *bus,
253
                                       PCIDevice *dev,
254
                                       pci_map_irq_fn map_irq,
255
                                       const char *name)
256
{
257
    qbus_create_inplace(&bus->qbus, &pci_bus_info, &dev->qdev, name);
258
    bus->map_irq = map_irq;
259
    bus->parent_dev = dev;
260

    
261
    QLIST_INIT(&bus->child);
262
    QLIST_INSERT_HEAD(&parent->child, bus, sibling);
263
}
264

    
265
static void pci_unregister_secondary_bus(PCIBus *bus)
266
{
267
    assert(QLIST_EMPTY(&bus->child));
268
    QLIST_REMOVE(bus, sibling);
269
}
270

    
271
int pci_bus_num(PCIBus *s)
272
{
273
    if (!s->parent_dev)
274
        return 0;       /* pci host bridge */
275
    return s->parent_dev->config[PCI_SECONDARY_BUS];
276
}
277

    
278
static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
279
{
280
    PCIDevice *s = container_of(pv, PCIDevice, config);
281
    uint8_t *config;
282
    int i;
283

    
284
    assert(size == pci_config_size(s));
285
    config = qemu_malloc(size);
286

    
287
    qemu_get_buffer(f, config, size);
288
    for (i = 0; i < size; ++i) {
289
        if ((config[i] ^ s->config[i]) & s->cmask[i] & ~s->wmask[i]) {
290
            qemu_free(config);
291
            return -EINVAL;
292
        }
293
    }
294
    memcpy(s->config, config, size);
295

    
296
    pci_update_mappings(s);
297

    
298
    qemu_free(config);
299
    return 0;
300
}
301

    
302
/* just put buffer */
303
static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
304
{
305
    const uint8_t **v = pv;
306
    assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
307
    qemu_put_buffer(f, *v, size);
308
}
309

    
310
static VMStateInfo vmstate_info_pci_config = {
311
    .name = "pci config",
312
    .get  = get_pci_config_device,
313
    .put  = put_pci_config_device,
314
};
315

    
316
static int get_pci_irq_state(QEMUFile *f, void *pv, size_t size)
317
{
318
    PCIDevice *s = container_of(pv, PCIDevice, config);
319
    uint32_t irq_state[PCI_NUM_PINS];
320
    int i;
321
    for (i = 0; i < PCI_NUM_PINS; ++i) {
322
        irq_state[i] = qemu_get_be32(f);
323
        if (irq_state[i] != 0x1 && irq_state[i] != 0) {
324
            fprintf(stderr, "irq state %d: must be 0 or 1.\n",
325
                    irq_state[i]);
326
            return -EINVAL;
327
        }
328
    }
329

    
330
    for (i = 0; i < PCI_NUM_PINS; ++i) {
331
        pci_set_irq_state(s, i, irq_state[i]);
332
    }
333

    
334
    return 0;
335
}
336

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

    
342
    for (i = 0; i < PCI_NUM_PINS; ++i) {
343
        qemu_put_be32(f, pci_irq_state(s, i));
344
    }
345
}
346

    
347
static VMStateInfo vmstate_info_pci_irq_state = {
348
    .name = "pci irq state",
349
    .get  = get_pci_irq_state,
350
    .put  = put_pci_irq_state,
351
};
352

    
353
const VMStateDescription vmstate_pci_device = {
354
    .name = "PCIDevice",
355
    .version_id = 2,
356
    .minimum_version_id = 1,
357
    .minimum_version_id_old = 1,
358
    .fields      = (VMStateField []) {
359
        VMSTATE_INT32_LE(version_id, PCIDevice),
360
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
361
                                   vmstate_info_pci_config,
362
                                   PCI_CONFIG_SPACE_SIZE),
363
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
364
                                   vmstate_info_pci_irq_state,
365
                                   PCI_NUM_PINS * sizeof(int32_t)),
366
        VMSTATE_END_OF_LIST()
367
    }
368
};
369

    
370
const VMStateDescription vmstate_pcie_device = {
371
    .name = "PCIDevice",
372
    .version_id = 2,
373
    .minimum_version_id = 1,
374
    .minimum_version_id_old = 1,
375
    .fields      = (VMStateField []) {
376
        VMSTATE_INT32_LE(version_id, PCIDevice),
377
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
378
                                   vmstate_info_pci_config,
379
                                   PCIE_CONFIG_SPACE_SIZE),
380
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
381
                                   vmstate_info_pci_irq_state,
382
                                   PCI_NUM_PINS * sizeof(int32_t)),
383
        VMSTATE_END_OF_LIST()
384
    }
385
};
386

    
387
static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
388
{
389
    return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
390
}
391

    
392
void pci_device_save(PCIDevice *s, QEMUFile *f)
393
{
394
    /* Clear interrupt status bit: it is implicit
395
     * in irq_state which we are saving.
396
     * This makes us compatible with old devices
397
     * which never set or clear this bit. */
398
    s->config[PCI_STATUS] &= ~PCI_STATUS_INTERRUPT;
399
    vmstate_save_state(f, pci_get_vmstate(s), s);
400
    /* Restore the interrupt status bit. */
401
    pci_update_irq_status(s);
402
}
403

    
404
int pci_device_load(PCIDevice *s, QEMUFile *f)
405
{
406
    int ret;
407
    ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
408
    /* Restore the interrupt status bit. */
409
    pci_update_irq_status(s);
410
    return ret;
411
}
412

    
413
static int pci_set_default_subsystem_id(PCIDevice *pci_dev)
414
{
415
    uint16_t *id;
416

    
417
    id = (void*)(&pci_dev->config[PCI_SUBSYSTEM_VENDOR_ID]);
418
    id[0] = cpu_to_le16(pci_default_sub_vendor_id);
419
    id[1] = cpu_to_le16(pci_default_sub_device_id);
420
    return 0;
421
}
422

    
423
/*
424
 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error
425
 */
426
static int pci_parse_devaddr(const char *addr, int *domp, int *busp, unsigned *slotp)
427
{
428
    const char *p;
429
    char *e;
430
    unsigned long val;
431
    unsigned long dom = 0, bus = 0;
432
    unsigned slot = 0;
433

    
434
    p = addr;
435
    val = strtoul(p, &e, 16);
436
    if (e == p)
437
        return -1;
438
    if (*e == ':') {
439
        bus = val;
440
        p = e + 1;
441
        val = strtoul(p, &e, 16);
442
        if (e == p)
443
            return -1;
444
        if (*e == ':') {
445
            dom = bus;
446
            bus = val;
447
            p = e + 1;
448
            val = strtoul(p, &e, 16);
449
            if (e == p)
450
                return -1;
451
        }
452
    }
453

    
454
    if (dom > 0xffff || bus > 0xff || val > 0x1f)
455
        return -1;
456

    
457
    slot = val;
458

    
459
    if (*e)
460
        return -1;
461

    
462
    /* Note: QEMU doesn't implement domains other than 0 */
463
    if (!pci_find_bus(pci_find_root_bus(dom), bus))
464
        return -1;
465

    
466
    *domp = dom;
467
    *busp = bus;
468
    *slotp = slot;
469
    return 0;
470
}
471

    
472
int pci_read_devaddr(Monitor *mon, const char *addr, int *domp, int *busp,
473
                     unsigned *slotp)
474
{
475
    /* strip legacy tag */
476
    if (!strncmp(addr, "pci_addr=", 9)) {
477
        addr += 9;
478
    }
479
    if (pci_parse_devaddr(addr, domp, busp, slotp)) {
480
        monitor_printf(mon, "Invalid pci address\n");
481
        return -1;
482
    }
483
    return 0;
484
}
485

    
486
PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
487
{
488
    int dom, bus;
489
    unsigned slot;
490

    
491
    if (!devaddr) {
492
        *devfnp = -1;
493
        return pci_find_bus(pci_find_root_bus(0), 0);
494
    }
495

    
496
    if (pci_parse_devaddr(devaddr, &dom, &bus, &slot) < 0) {
497
        return NULL;
498
    }
499

    
500
    *devfnp = slot << 3;
501
    return pci_find_bus(pci_find_root_bus(0), bus);
502
}
503

    
504
static void pci_init_cmask(PCIDevice *dev)
505
{
506
    pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
507
    pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
508
    dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
509
    dev->cmask[PCI_REVISION_ID] = 0xff;
510
    dev->cmask[PCI_CLASS_PROG] = 0xff;
511
    pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
512
    dev->cmask[PCI_HEADER_TYPE] = 0xff;
513
    dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
514
}
515

    
516
static void pci_init_wmask(PCIDevice *dev)
517
{
518
    int config_size = pci_config_size(dev);
519

    
520
    dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
521
    dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
522
    pci_set_word(dev->wmask + PCI_COMMAND,
523
                 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
524
                 PCI_COMMAND_INTX_DISABLE);
525

    
526
    memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
527
           config_size - PCI_CONFIG_HEADER_SIZE);
528
}
529

    
530
static void pci_init_wmask_bridge(PCIDevice *d)
531
{
532
    /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
533
       PCI_SEC_LETENCY_TIMER */
534
    memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
535

    
536
    /* base and limit */
537
    d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
538
    d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
539
    pci_set_word(d->wmask + PCI_MEMORY_BASE,
540
                 PCI_MEMORY_RANGE_MASK & 0xffff);
541
    pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
542
                 PCI_MEMORY_RANGE_MASK & 0xffff);
543
    pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
544
                 PCI_PREF_RANGE_MASK & 0xffff);
545
    pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
546
                 PCI_PREF_RANGE_MASK & 0xffff);
547

    
548
    /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
549
    memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
550

    
551
    pci_set_word(d->wmask + PCI_BRIDGE_CONTROL, 0xffff);
552
}
553

    
554
static void pci_config_alloc(PCIDevice *pci_dev)
555
{
556
    int config_size = pci_config_size(pci_dev);
557

    
558
    pci_dev->config = qemu_mallocz(config_size);
559
    pci_dev->cmask = qemu_mallocz(config_size);
560
    pci_dev->wmask = qemu_mallocz(config_size);
561
    pci_dev->used = qemu_mallocz(config_size);
562
}
563

    
564
static void pci_config_free(PCIDevice *pci_dev)
565
{
566
    qemu_free(pci_dev->config);
567
    qemu_free(pci_dev->cmask);
568
    qemu_free(pci_dev->wmask);
569
    qemu_free(pci_dev->used);
570
}
571

    
572
/* -1 for devfn means auto assign */
573
static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,
574
                                         const char *name, int devfn,
575
                                         PCIConfigReadFunc *config_read,
576
                                         PCIConfigWriteFunc *config_write,
577
                                         uint8_t header_type)
578
{
579
    if (devfn < 0) {
580
        for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);
581
            devfn += 8) {
582
            if (!bus->devices[devfn])
583
                goto found;
584
        }
585
        qemu_error("PCI: no devfn available for %s, all in use\n", name);
586
        return NULL;
587
    found: ;
588
    } else if (bus->devices[devfn]) {
589
        qemu_error("PCI: devfn %d not available for %s, in use by %s\n", devfn,
590
                 name, bus->devices[devfn]->name);
591
        return NULL;
592
    }
593
    pci_dev->bus = bus;
594
    pci_dev->devfn = devfn;
595
    pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);
596
    pci_dev->irq_state = 0;
597
    pci_config_alloc(pci_dev);
598

    
599
    header_type &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
600
    if (header_type == PCI_HEADER_TYPE_NORMAL) {
601
        pci_set_default_subsystem_id(pci_dev);
602
    }
603
    pci_init_cmask(pci_dev);
604
    pci_init_wmask(pci_dev);
605
    if (header_type == PCI_HEADER_TYPE_BRIDGE) {
606
        pci_init_wmask_bridge(pci_dev);
607
    }
608

    
609
    if (!config_read)
610
        config_read = pci_default_read_config;
611
    if (!config_write)
612
        config_write = pci_default_write_config;
613
    pci_dev->config_read = config_read;
614
    pci_dev->config_write = config_write;
615
    bus->devices[devfn] = pci_dev;
616
    pci_dev->irq = qemu_allocate_irqs(pci_set_irq, pci_dev, PCI_NUM_PINS);
617
    pci_dev->version_id = 2; /* Current pci device vmstate version */
618
    return pci_dev;
619
}
620

    
621
PCIDevice *pci_register_device(PCIBus *bus, const char *name,
622
                               int instance_size, int devfn,
623
                               PCIConfigReadFunc *config_read,
624
                               PCIConfigWriteFunc *config_write)
625
{
626
    PCIDevice *pci_dev;
627

    
628
    pci_dev = qemu_mallocz(instance_size);
629
    pci_dev = do_pci_register_device(pci_dev, bus, name, devfn,
630
                                     config_read, config_write,
631
                                     PCI_HEADER_TYPE_NORMAL);
632
    if (pci_dev == NULL) {
633
        hw_error("PCI: can't register device\n");
634
    }
635
    return pci_dev;
636
}
637
static target_phys_addr_t pci_to_cpu_addr(target_phys_addr_t addr)
638
{
639
    return addr + pci_mem_base;
640
}
641

    
642
static void pci_unregister_io_regions(PCIDevice *pci_dev)
643
{
644
    PCIIORegion *r;
645
    int i;
646

    
647
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
648
        r = &pci_dev->io_regions[i];
649
        if (!r->size || r->addr == PCI_BAR_UNMAPPED)
650
            continue;
651
        if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
652
            isa_unassign_ioport(r->addr, r->filtered_size);
653
        } else {
654
            cpu_register_physical_memory(pci_to_cpu_addr(r->addr),
655
                                                     r->filtered_size,
656
                                                     IO_MEM_UNASSIGNED);
657
        }
658
    }
659
}
660

    
661
static int pci_unregister_device(DeviceState *dev)
662
{
663
    PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
664
    PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
665
    int ret = 0;
666

    
667
    if (info->exit)
668
        ret = info->exit(pci_dev);
669
    if (ret)
670
        return ret;
671

    
672
    pci_unregister_io_regions(pci_dev);
673

    
674
    qemu_free_irqs(pci_dev->irq);
675
    pci_dev->bus->devices[pci_dev->devfn] = NULL;
676
    pci_config_free(pci_dev);
677
    return 0;
678
}
679

    
680
void pci_register_bar(PCIDevice *pci_dev, int region_num,
681
                            pcibus_t size, int type,
682
                            PCIMapIORegionFunc *map_func)
683
{
684
    PCIIORegion *r;
685
    uint32_t addr;
686
    pcibus_t wmask;
687

    
688
    if ((unsigned int)region_num >= PCI_NUM_REGIONS)
689
        return;
690

    
691
    if (size & (size-1)) {
692
        fprintf(stderr, "ERROR: PCI region size must be pow2 "
693
                    "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
694
        exit(1);
695
    }
696

    
697
    r = &pci_dev->io_regions[region_num];
698
    r->addr = PCI_BAR_UNMAPPED;
699
    r->size = size;
700
    r->filtered_size = size;
701
    r->type = type;
702
    r->map_func = map_func;
703

    
704
    wmask = ~(size - 1);
705
    addr = pci_bar(pci_dev, region_num);
706
    if (region_num == PCI_ROM_SLOT) {
707
        /* ROM enable bit is writeable */
708
        wmask |= PCI_ROM_ADDRESS_ENABLE;
709
    }
710
    pci_set_long(pci_dev->config + addr, type);
711
    if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
712
        r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
713
        pci_set_quad(pci_dev->wmask + addr, wmask);
714
        pci_set_quad(pci_dev->cmask + addr, ~0ULL);
715
    } else {
716
        pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
717
        pci_set_long(pci_dev->cmask + addr, 0xffffffff);
718
    }
719
}
720

    
721
static uint32_t pci_config_get_io_base(PCIDevice *d,
722
                                       uint32_t base, uint32_t base_upper16)
723
{
724
    uint32_t val;
725

    
726
    val = ((uint32_t)d->config[base] & PCI_IO_RANGE_MASK) << 8;
727
    if (d->config[base] & PCI_IO_RANGE_TYPE_32) {
728
        val |= (uint32_t)pci_get_word(d->config + base_upper16) << 16;
729
    }
730
    return val;
731
}
732

    
733
static pcibus_t pci_config_get_memory_base(PCIDevice *d, uint32_t base)
734
{
735
    return ((pcibus_t)pci_get_word(d->config + base) & PCI_MEMORY_RANGE_MASK)
736
        << 16;
737
}
738

    
739
static pcibus_t pci_config_get_pref_base(PCIDevice *d,
740
                                         uint32_t base, uint32_t upper)
741
{
742
    pcibus_t tmp;
743
    pcibus_t val;
744

    
745
    tmp = (pcibus_t)pci_get_word(d->config + base);
746
    val = (tmp & PCI_PREF_RANGE_MASK) << 16;
747
    if (tmp & PCI_PREF_RANGE_TYPE_64) {
748
        val |= (pcibus_t)pci_get_long(d->config + upper) << 32;
749
    }
750
    return val;
751
}
752

    
753
static pcibus_t pci_bridge_get_base(PCIDevice *bridge, uint8_t type)
754
{
755
    pcibus_t base;
756
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
757
        base = pci_config_get_io_base(bridge,
758
                                      PCI_IO_BASE, PCI_IO_BASE_UPPER16);
759
    } else {
760
        if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
761
            base = pci_config_get_pref_base(
762
                bridge, PCI_PREF_MEMORY_BASE, PCI_PREF_BASE_UPPER32);
763
        } else {
764
            base = pci_config_get_memory_base(bridge, PCI_MEMORY_BASE);
765
        }
766
    }
767

    
768
    return base;
769
}
770

    
771
static pcibus_t pci_bridge_get_limit(PCIDevice *bridge, uint8_t type)
772
{
773
    pcibus_t limit;
774
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
775
        limit = pci_config_get_io_base(bridge,
776
                                      PCI_IO_LIMIT, PCI_IO_LIMIT_UPPER16);
777
        limit |= 0xfff;         /* PCI bridge spec 3.2.5.6. */
778
    } else {
779
        if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
780
            limit = pci_config_get_pref_base(
781
                bridge, PCI_PREF_MEMORY_LIMIT, PCI_PREF_LIMIT_UPPER32);
782
        } else {
783
            limit = pci_config_get_memory_base(bridge, PCI_MEMORY_LIMIT);
784
        }
785
        limit |= 0xfffff;       /* PCI bridge spec 3.2.5.{1, 8}. */
786
    }
787
    return limit;
788
}
789

    
790
static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
791
                              uint8_t type)
792
{
793
    pcibus_t base = *addr;
794
    pcibus_t limit = *addr + *size - 1;
795
    PCIDevice *br;
796

    
797
    for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
798
        uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
799

    
800
        if (type & PCI_BASE_ADDRESS_SPACE_IO) {
801
            if (!(cmd & PCI_COMMAND_IO)) {
802
                goto no_map;
803
            }
804
        } else {
805
            if (!(cmd & PCI_COMMAND_MEMORY)) {
806
                goto no_map;
807
            }
808
        }
809

    
810
        base = MAX(base, pci_bridge_get_base(br, type));
811
        limit = MIN(limit, pci_bridge_get_limit(br, type));
812
    }
813

    
814
    if (base > limit) {
815
        goto no_map;
816
    }
817
    *addr = base;
818
    *size = limit - base + 1;
819
    return;
820
no_map:
821
    *addr = PCI_BAR_UNMAPPED;
822
    *size = 0;
823
}
824

    
825
static pcibus_t pci_bar_address(PCIDevice *d,
826
                                int reg, uint8_t type, pcibus_t size)
827
{
828
    pcibus_t new_addr, last_addr;
829
    int bar = pci_bar(d, reg);
830
    uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
831

    
832
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
833
        if (!(cmd & PCI_COMMAND_IO)) {
834
            return PCI_BAR_UNMAPPED;
835
        }
836
        new_addr = pci_get_long(d->config + bar) & ~(size - 1);
837
        last_addr = new_addr + size - 1;
838
        /* NOTE: we have only 64K ioports on PC */
839
        if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
840
            return PCI_BAR_UNMAPPED;
841
        }
842
        return new_addr;
843
    }
844

    
845
    if (!(cmd & PCI_COMMAND_MEMORY)) {
846
        return PCI_BAR_UNMAPPED;
847
    }
848
    if (type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
849
        new_addr = pci_get_quad(d->config + bar);
850
    } else {
851
        new_addr = pci_get_long(d->config + bar);
852
    }
853
    /* the ROM slot has a specific enable bit */
854
    if (reg == PCI_ROM_SLOT && !(new_addr & PCI_ROM_ADDRESS_ENABLE)) {
855
        return PCI_BAR_UNMAPPED;
856
    }
857
    new_addr &= ~(size - 1);
858
    last_addr = new_addr + size - 1;
859
    /* NOTE: we do not support wrapping */
860
    /* XXX: as we cannot support really dynamic
861
       mappings, we handle specific values as invalid
862
       mappings. */
863
    if (last_addr <= new_addr || new_addr == 0 ||
864
        last_addr == PCI_BAR_UNMAPPED) {
865
        return PCI_BAR_UNMAPPED;
866
    }
867

    
868
    /* Now pcibus_t is 64bit.
869
     * Check if 32 bit BAR wraps around explicitly.
870
     * Without this, PC ide doesn't work well.
871
     * TODO: remove this work around.
872
     */
873
    if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
874
        return PCI_BAR_UNMAPPED;
875
    }
876

    
877
    /*
878
     * OS is allowed to set BAR beyond its addressable
879
     * bits. For example, 32 bit OS can set 64bit bar
880
     * to >4G. Check it. TODO: we might need to support
881
     * it in the future for e.g. PAE.
882
     */
883
    if (last_addr >= TARGET_PHYS_ADDR_MAX) {
884
        return PCI_BAR_UNMAPPED;
885
    }
886

    
887
    return new_addr;
888
}
889

    
890
static void pci_update_mappings(PCIDevice *d)
891
{
892
    PCIIORegion *r;
893
    int i;
894
    pcibus_t new_addr, filtered_size;
895

    
896
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
897
        r = &d->io_regions[i];
898

    
899
        /* this region isn't registered */
900
        if (!r->size)
901
            continue;
902

    
903
        new_addr = pci_bar_address(d, i, r->type, r->size);
904

    
905
        /* bridge filtering */
906
        filtered_size = r->size;
907
        if (new_addr != PCI_BAR_UNMAPPED) {
908
            pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
909
        }
910

    
911
        /* This bar isn't changed */
912
        if (new_addr == r->addr && filtered_size == r->filtered_size)
913
            continue;
914

    
915
        /* now do the real mapping */
916
        if (r->addr != PCI_BAR_UNMAPPED) {
917
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
918
                int class;
919
                /* NOTE: specific hack for IDE in PC case:
920
                   only one byte must be mapped. */
921
                class = pci_get_word(d->config + PCI_CLASS_DEVICE);
922
                if (class == 0x0101 && r->size == 4) {
923
                    isa_unassign_ioport(r->addr + 2, 1);
924
                } else {
925
                    isa_unassign_ioport(r->addr, r->filtered_size);
926
                }
927
            } else {
928
                cpu_register_physical_memory(pci_to_cpu_addr(r->addr),
929
                                             r->filtered_size,
930
                                             IO_MEM_UNASSIGNED);
931
                qemu_unregister_coalesced_mmio(r->addr, r->filtered_size);
932
            }
933
        }
934
        r->addr = new_addr;
935
        r->filtered_size = filtered_size;
936
        if (r->addr != PCI_BAR_UNMAPPED) {
937
            /*
938
             * TODO: currently almost all the map funcions assumes
939
             * filtered_size == size and addr & ~(size - 1) == addr.
940
             * However with bridge filtering, they aren't always true.
941
             * Teach them such cases, such that filtered_size < size and
942
             * addr & (size - 1) != 0.
943
             */
944
            r->map_func(d, i, r->addr, r->filtered_size, r->type);
945
        }
946
    }
947
}
948

    
949
static inline int pci_irq_disabled(PCIDevice *d)
950
{
951
    return pci_get_word(d->config + PCI_COMMAND) & PCI_COMMAND_INTX_DISABLE;
952
}
953

    
954
/* Called after interrupt disabled field update in config space,
955
 * assert/deassert interrupts if necessary.
956
 * Gets original interrupt disable bit value (before update). */
957
static void pci_update_irq_disabled(PCIDevice *d, int was_irq_disabled)
958
{
959
    int i, disabled = pci_irq_disabled(d);
960
    if (disabled == was_irq_disabled)
961
        return;
962
    for (i = 0; i < PCI_NUM_PINS; ++i) {
963
        int state = pci_irq_state(d, i);
964
        pci_change_irq_level(d, i, disabled ? -state : state);
965
    }
966
}
967

    
968
uint32_t pci_default_read_config(PCIDevice *d,
969
                                 uint32_t address, int len)
970
{
971
    uint32_t val = 0;
972
    assert(len == 1 || len == 2 || len == 4);
973
    len = MIN(len, pci_config_size(d) - address);
974
    memcpy(&val, d->config + address, len);
975
    return le32_to_cpu(val);
976
}
977

    
978
void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
979
{
980
    int i, was_irq_disabled = pci_irq_disabled(d);
981
    uint32_t config_size = pci_config_size(d);
982

    
983
    for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
984
        uint8_t wmask = d->wmask[addr + i];
985
        d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
986
    }
987
    if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
988
        ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
989
        ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
990
        range_covers_byte(addr, l, PCI_COMMAND))
991
        pci_update_mappings(d);
992

    
993
    if (range_covers_byte(addr, l, PCI_COMMAND))
994
        pci_update_irq_disabled(d, was_irq_disabled);
995
}
996

    
997
/***********************************************************/
998
/* generic PCI irq support */
999

    
1000
/* 0 <= irq_num <= 3. level must be 0 or 1 */
1001
static void pci_set_irq(void *opaque, int irq_num, int level)
1002
{
1003
    PCIDevice *pci_dev = opaque;
1004
    int change;
1005

    
1006
    change = level - pci_irq_state(pci_dev, irq_num);
1007
    if (!change)
1008
        return;
1009

    
1010
    pci_set_irq_state(pci_dev, irq_num, level);
1011
    pci_update_irq_status(pci_dev);
1012
    if (pci_irq_disabled(pci_dev))
1013
        return;
1014
    pci_change_irq_level(pci_dev, irq_num, change);
1015
}
1016

    
1017
/***********************************************************/
1018
/* monitor info on PCI */
1019

    
1020
typedef struct {
1021
    uint16_t class;
1022
    const char *desc;
1023
} pci_class_desc;
1024

    
1025
static const pci_class_desc pci_class_descriptions[] =
1026
{
1027
    { 0x0100, "SCSI controller"},
1028
    { 0x0101, "IDE controller"},
1029
    { 0x0102, "Floppy controller"},
1030
    { 0x0103, "IPI controller"},
1031
    { 0x0104, "RAID controller"},
1032
    { 0x0106, "SATA controller"},
1033
    { 0x0107, "SAS controller"},
1034
    { 0x0180, "Storage controller"},
1035
    { 0x0200, "Ethernet controller"},
1036
    { 0x0201, "Token Ring controller"},
1037
    { 0x0202, "FDDI controller"},
1038
    { 0x0203, "ATM controller"},
1039
    { 0x0280, "Network controller"},
1040
    { 0x0300, "VGA controller"},
1041
    { 0x0301, "XGA controller"},
1042
    { 0x0302, "3D controller"},
1043
    { 0x0380, "Display controller"},
1044
    { 0x0400, "Video controller"},
1045
    { 0x0401, "Audio controller"},
1046
    { 0x0402, "Phone"},
1047
    { 0x0480, "Multimedia controller"},
1048
    { 0x0500, "RAM controller"},
1049
    { 0x0501, "Flash controller"},
1050
    { 0x0580, "Memory controller"},
1051
    { 0x0600, "Host bridge"},
1052
    { 0x0601, "ISA bridge"},
1053
    { 0x0602, "EISA bridge"},
1054
    { 0x0603, "MC bridge"},
1055
    { 0x0604, "PCI bridge"},
1056
    { 0x0605, "PCMCIA bridge"},
1057
    { 0x0606, "NUBUS bridge"},
1058
    { 0x0607, "CARDBUS bridge"},
1059
    { 0x0608, "RACEWAY bridge"},
1060
    { 0x0680, "Bridge"},
1061
    { 0x0c03, "USB controller"},
1062
    { 0, NULL}
1063
};
1064

    
1065
static void pci_info_device(PCIBus *bus, PCIDevice *d)
1066
{
1067
    Monitor *mon = cur_mon;
1068
    int i, class;
1069
    PCIIORegion *r;
1070
    const pci_class_desc *desc;
1071

    
1072
    monitor_printf(mon, "  Bus %2d, device %3d, function %d:\n",
1073
                   pci_bus_num(d->bus),
1074
                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));
1075
    class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1076
    monitor_printf(mon, "    ");
1077
    desc = pci_class_descriptions;
1078
    while (desc->desc && class != desc->class)
1079
        desc++;
1080
    if (desc->desc) {
1081
        monitor_printf(mon, "%s", desc->desc);
1082
    } else {
1083
        monitor_printf(mon, "Class %04x", class);
1084
    }
1085
    monitor_printf(mon, ": PCI device %04x:%04x\n",
1086
           pci_get_word(d->config + PCI_VENDOR_ID),
1087
           pci_get_word(d->config + PCI_DEVICE_ID));
1088

    
1089
    if (d->config[PCI_INTERRUPT_PIN] != 0) {
1090
        monitor_printf(mon, "      IRQ %d.\n",
1091
                       d->config[PCI_INTERRUPT_LINE]);
1092
    }
1093
    if (class == 0x0604) {
1094
        uint64_t base;
1095
        uint64_t limit;
1096

    
1097
        monitor_printf(mon, "      BUS %d.\n", d->config[0x19]);
1098
        monitor_printf(mon, "      secondary bus %d.\n",
1099
                       d->config[PCI_SECONDARY_BUS]);
1100
        monitor_printf(mon, "      subordinate bus %d.\n",
1101
                       d->config[PCI_SUBORDINATE_BUS]);
1102

    
1103
        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_IO);
1104
        limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_IO);
1105
        monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1106
                       base, limit);
1107

    
1108
        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY);
1109
        limit= pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_MEMORY);
1110
        monitor_printf(mon,
1111
                       "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1112
                       base, limit);
1113

    
1114
        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY |
1115
                                   PCI_BASE_ADDRESS_MEM_PREFETCH);
1116
        limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_MEMORY |
1117
                                     PCI_BASE_ADDRESS_MEM_PREFETCH);
1118
        monitor_printf(mon, "      prefetchable memory range "
1119
                       "[0x%08"PRIx64", 0x%08"PRIx64"]\n", base, limit);
1120
    }
1121
    for(i = 0;i < PCI_NUM_REGIONS; i++) {
1122
        r = &d->io_regions[i];
1123
        if (r->size != 0) {
1124
            monitor_printf(mon, "      BAR%d: ", i);
1125
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1126
                monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1127
                               " [0x%04"FMT_PCIBUS"].\n",
1128
                               r->addr, r->addr + r->size - 1);
1129
            } else {
1130
                const char *type = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64 ?
1131
                    "64 bit" : "32 bit";
1132
                const char *prefetch =
1133
                    r->type & PCI_BASE_ADDRESS_MEM_PREFETCH ?
1134
                    " prefetchable" : "";
1135

    
1136
                monitor_printf(mon, "%s%s memory at 0x%08"FMT_PCIBUS
1137
                               " [0x%08"FMT_PCIBUS"].\n",
1138
                               type, prefetch,
1139
                               r->addr, r->addr + r->size - 1);
1140
            }
1141
        }
1142
    }
1143
    monitor_printf(mon, "      id \"%s\"\n", d->qdev.id ? d->qdev.id : "");
1144
    if (class == 0x0604 && d->config[0x19] != 0) {
1145
        pci_for_each_device(bus, d->config[0x19], pci_info_device);
1146
    }
1147
}
1148

    
1149
static void pci_for_each_device_under_bus(PCIBus *bus,
1150
                                          void (*fn)(PCIBus *b, PCIDevice *d))
1151
{
1152
    PCIDevice *d;
1153
    int devfn;
1154

    
1155
    for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1156
        d = bus->devices[devfn];
1157
        if (d)
1158
            fn(bus, d);
1159
    }
1160
}
1161

    
1162
void pci_for_each_device(PCIBus *bus, int bus_num,
1163
                         void (*fn)(PCIBus *b, PCIDevice *d))
1164
{
1165
    bus = pci_find_bus(bus, bus_num);
1166

    
1167
    if (bus) {
1168
        pci_for_each_device_under_bus(bus, fn);
1169
    }
1170
}
1171

    
1172
void pci_info(Monitor *mon)
1173
{
1174
    struct PCIHostBus *host;
1175
    QLIST_FOREACH(host, &host_buses, next) {
1176
        pci_for_each_device(host->bus, 0, pci_info_device);
1177
    }
1178
}
1179

    
1180
static const char * const pci_nic_models[] = {
1181
    "ne2k_pci",
1182
    "i82551",
1183
    "i82557b",
1184
    "i82559er",
1185
    "rtl8139",
1186
    "e1000",
1187
    "pcnet",
1188
    "virtio",
1189
    NULL
1190
};
1191

    
1192
static const char * const pci_nic_names[] = {
1193
    "ne2k_pci",
1194
    "i82551",
1195
    "i82557b",
1196
    "i82559er",
1197
    "rtl8139",
1198
    "e1000",
1199
    "pcnet",
1200
    "virtio-net-pci",
1201
    NULL
1202
};
1203

    
1204
/* Initialize a PCI NIC.  */
1205
/* FIXME callers should check for failure, but don't */
1206
PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1207
                        const char *default_devaddr)
1208
{
1209
    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1210
    PCIBus *bus;
1211
    int devfn;
1212
    PCIDevice *pci_dev;
1213
    DeviceState *dev;
1214
    int i;
1215

    
1216
    i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1217
    if (i < 0)
1218
        return NULL;
1219

    
1220
    bus = pci_get_bus_devfn(&devfn, devaddr);
1221
    if (!bus) {
1222
        qemu_error("Invalid PCI device address %s for device %s\n",
1223
                   devaddr, pci_nic_names[i]);
1224
        return NULL;
1225
    }
1226

    
1227
    pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1228
    dev = &pci_dev->qdev;
1229
    if (nd->name)
1230
        dev->id = qemu_strdup(nd->name);
1231
    qdev_set_nic_properties(dev, nd);
1232
    if (qdev_init(dev) < 0)
1233
        return NULL;
1234
    return pci_dev;
1235
}
1236

    
1237
PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1238
                               const char *default_devaddr)
1239
{
1240
    PCIDevice *res;
1241

    
1242
    if (qemu_show_nic_models(nd->model, pci_nic_models))
1243
        exit(0);
1244

    
1245
    res = pci_nic_init(nd, default_model, default_devaddr);
1246
    if (!res)
1247
        exit(1);
1248
    return res;
1249
}
1250

    
1251
typedef struct {
1252
    PCIDevice dev;
1253
    PCIBus bus;
1254
    uint32_t vid;
1255
    uint32_t did;
1256
} PCIBridge;
1257

    
1258

    
1259
static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1260
{
1261
    pci_update_mappings(d);
1262
}
1263

    
1264
static void pci_bridge_update_mappings(PCIBus *b)
1265
{
1266
    PCIBus *child;
1267

    
1268
    pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1269

    
1270
    QLIST_FOREACH(child, &b->child, sibling) {
1271
        pci_bridge_update_mappings(child);
1272
    }
1273
}
1274

    
1275
static void pci_bridge_write_config(PCIDevice *d,
1276
                             uint32_t address, uint32_t val, int len)
1277
{
1278
    pci_default_write_config(d, address, val, len);
1279

    
1280
    if (/* io base/limit */
1281
        ranges_overlap(address, len, PCI_IO_BASE, 2) ||
1282

    
1283
        /* memory base/limit, prefetchable base/limit and
1284
           io base/limit upper 16 */
1285
        ranges_overlap(address, len, PCI_MEMORY_BASE, 20)) {
1286
        pci_bridge_update_mappings(d->bus);
1287
    }
1288
}
1289

    
1290
PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1291
{
1292
    PCIBus *sec;
1293

    
1294
    if (!bus)
1295
        return NULL;
1296

    
1297
    if (pci_bus_num(bus) == bus_num) {
1298
        return bus;
1299
    }
1300

    
1301
    /* try child bus */
1302
    QLIST_FOREACH(sec, &bus->child, sibling) {
1303

    
1304
        if (!bus->parent_dev /* pci host bridge */
1305
            || (pci_bus_num(sec) <= bus_num &&
1306
                bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {
1307
            return pci_find_bus(sec, bus_num);
1308
        }
1309
    }
1310

    
1311
    return NULL;
1312
}
1313

    
1314
PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function)
1315
{
1316
    bus = pci_find_bus(bus, bus_num);
1317

    
1318
    if (!bus)
1319
        return NULL;
1320

    
1321
    return bus->devices[PCI_DEVFN(slot, function)];
1322
}
1323

    
1324
static int pci_bridge_initfn(PCIDevice *dev)
1325
{
1326
    PCIBridge *s = DO_UPCAST(PCIBridge, dev, dev);
1327

    
1328
    pci_config_set_vendor_id(s->dev.config, s->vid);
1329
    pci_config_set_device_id(s->dev.config, s->did);
1330

    
1331
    pci_set_word(dev->config + PCI_STATUS,
1332
                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1333
    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_PCI);
1334
    dev->config[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_BRIDGE;
1335
    pci_set_word(dev->config + PCI_SEC_STATUS,
1336
                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1337
    return 0;
1338
}
1339

    
1340
static int pci_bridge_exitfn(PCIDevice *pci_dev)
1341
{
1342
    PCIBridge *s = DO_UPCAST(PCIBridge, dev, pci_dev);
1343
    PCIBus *bus = &s->bus;
1344
    pci_unregister_secondary_bus(bus);
1345
    return 0;
1346
}
1347

    
1348
PCIBus *pci_bridge_init(PCIBus *bus, int devfn, uint16_t vid, uint16_t did,
1349
                        pci_map_irq_fn map_irq, const char *name)
1350
{
1351
    PCIDevice *dev;
1352
    PCIBridge *s;
1353

    
1354
    dev = pci_create(bus, devfn, "pci-bridge");
1355
    qdev_prop_set_uint32(&dev->qdev, "vendorid", vid);
1356
    qdev_prop_set_uint32(&dev->qdev, "deviceid", did);
1357
    qdev_init_nofail(&dev->qdev);
1358

    
1359
    s = DO_UPCAST(PCIBridge, dev, dev);
1360
    pci_register_secondary_bus(bus, &s->bus, &s->dev, map_irq, name);
1361
    return &s->bus;
1362
}
1363

    
1364
PCIDevice *pci_bridge_get_device(PCIBus *bus)
1365
{
1366
    return bus->parent_dev;
1367
}
1368

    
1369
static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1370
{
1371
    PCIDevice *pci_dev = (PCIDevice *)qdev;
1372
    PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1373
    PCIBus *bus;
1374
    int devfn, rc;
1375

    
1376
    /* initialize cap_present for pci_is_express() and pci_config_size() */
1377
    if (info->is_express) {
1378
        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1379
    }
1380

    
1381
    bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1382
    devfn = pci_dev->devfn;
1383
    pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
1384
                                     info->config_read, info->config_write,
1385
                                     info->header_type);
1386
    if (pci_dev == NULL)
1387
        return -1;
1388
    rc = info->init(pci_dev);
1389
    if (rc != 0)
1390
        return rc;
1391

    
1392
    /* rom loading */
1393
    if (pci_dev->romfile == NULL && info->romfile != NULL)
1394
        pci_dev->romfile = qemu_strdup(info->romfile);
1395
    pci_add_option_rom(pci_dev);
1396

    
1397
    if (qdev->hotplugged)
1398
        bus->hotplug(pci_dev, 1);
1399
    return 0;
1400
}
1401

    
1402
static int pci_unplug_device(DeviceState *qdev)
1403
{
1404
    PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1405

    
1406
    dev->bus->hotplug(dev, 0);
1407
    return 0;
1408
}
1409

    
1410
void pci_qdev_register(PCIDeviceInfo *info)
1411
{
1412
    info->qdev.init = pci_qdev_init;
1413
    info->qdev.unplug = pci_unplug_device;
1414
    info->qdev.exit = pci_unregister_device;
1415
    info->qdev.bus_info = &pci_bus_info;
1416
    qdev_register(&info->qdev);
1417
}
1418

    
1419
void pci_qdev_register_many(PCIDeviceInfo *info)
1420
{
1421
    while (info->qdev.name) {
1422
        pci_qdev_register(info);
1423
        info++;
1424
    }
1425
}
1426

    
1427
PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1428
{
1429
    DeviceState *dev;
1430

    
1431
    dev = qdev_create(&bus->qbus, name);
1432
    qdev_prop_set_uint32(dev, "addr", devfn);
1433
    return DO_UPCAST(PCIDevice, qdev, dev);
1434
}
1435

    
1436
PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1437
{
1438
    PCIDevice *dev = pci_create(bus, devfn, name);
1439
    qdev_init_nofail(&dev->qdev);
1440
    return dev;
1441
}
1442

    
1443
static int pci_find_space(PCIDevice *pdev, uint8_t size)
1444
{
1445
    int config_size = pci_config_size(pdev);
1446
    int offset = PCI_CONFIG_HEADER_SIZE;
1447
    int i;
1448
    for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1449
        if (pdev->used[i])
1450
            offset = i + 1;
1451
        else if (i - offset + 1 == size)
1452
            return offset;
1453
    return 0;
1454
}
1455

    
1456
static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1457
                                        uint8_t *prev_p)
1458
{
1459
    uint8_t next, prev;
1460

    
1461
    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1462
        return 0;
1463

    
1464
    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1465
         prev = next + PCI_CAP_LIST_NEXT)
1466
        if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1467
            break;
1468

    
1469
    if (prev_p)
1470
        *prev_p = prev;
1471
    return next;
1472
}
1473

    
1474
static void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1475
{
1476
    cpu_register_physical_memory(addr, size, pdev->rom_offset);
1477
}
1478

    
1479
/* Add an option rom for the device */
1480
static int pci_add_option_rom(PCIDevice *pdev)
1481
{
1482
    int size;
1483
    char *path;
1484
    void *ptr;
1485

    
1486
    if (!pdev->romfile)
1487
        return 0;
1488
    if (strlen(pdev->romfile) == 0)
1489
        return 0;
1490

    
1491
    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1492
    if (path == NULL) {
1493
        path = qemu_strdup(pdev->romfile);
1494
    }
1495

    
1496
    size = get_image_size(path);
1497
    if (size < 0) {
1498
        qemu_error("%s: failed to find romfile \"%s\"\n", __FUNCTION__,
1499
                   pdev->romfile);
1500
        return -1;
1501
    }
1502
    if (size & (size - 1)) {
1503
        size = 1 << qemu_fls(size);
1504
    }
1505

    
1506
    pdev->rom_offset = qemu_ram_alloc(size);
1507

    
1508
    ptr = qemu_get_ram_ptr(pdev->rom_offset);
1509
    load_image(path, ptr);
1510
    qemu_free(path);
1511

    
1512
    pci_register_bar(pdev, PCI_ROM_SLOT, size,
1513
                     0, pci_map_option_rom);
1514

    
1515
    return 0;
1516
}
1517

    
1518
/* Reserve space and add capability to the linked list in pci config space */
1519
int pci_add_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1520
{
1521
    uint8_t offset = pci_find_space(pdev, size);
1522
    uint8_t *config = pdev->config + offset;
1523
    if (!offset)
1524
        return -ENOSPC;
1525
    config[PCI_CAP_LIST_ID] = cap_id;
1526
    config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1527
    pdev->config[PCI_CAPABILITY_LIST] = offset;
1528
    pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1529
    memset(pdev->used + offset, 0xFF, size);
1530
    /* Make capability read-only by default */
1531
    memset(pdev->wmask + offset, 0, size);
1532
    /* Check capability by default */
1533
    memset(pdev->cmask + offset, 0xFF, size);
1534
    return offset;
1535
}
1536

    
1537
/* Unlink capability from the pci config space. */
1538
void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1539
{
1540
    uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
1541
    if (!offset)
1542
        return;
1543
    pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
1544
    /* Make capability writeable again */
1545
    memset(pdev->wmask + offset, 0xff, size);
1546
    /* Clear cmask as device-specific registers can't be checked */
1547
    memset(pdev->cmask + offset, 0, size);
1548
    memset(pdev->used + offset, 0, size);
1549

    
1550
    if (!pdev->config[PCI_CAPABILITY_LIST])
1551
        pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
1552
}
1553

    
1554
/* Reserve space for capability at a known offset (to call after load). */
1555
void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
1556
{
1557
    memset(pdev->used + offset, 0xff, size);
1558
}
1559

    
1560
uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
1561
{
1562
    return pci_find_capability_list(pdev, cap_id, NULL);
1563
}
1564

    
1565
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
1566
{
1567
    PCIDevice *d = (PCIDevice *)dev;
1568
    const pci_class_desc *desc;
1569
    char ctxt[64];
1570
    PCIIORegion *r;
1571
    int i, class;
1572

    
1573
    class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1574
    desc = pci_class_descriptions;
1575
    while (desc->desc && class != desc->class)
1576
        desc++;
1577
    if (desc->desc) {
1578
        snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
1579
    } else {
1580
        snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
1581
    }
1582

    
1583
    monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
1584
                   "pci id %04x:%04x (sub %04x:%04x)\n",
1585
                   indent, "", ctxt,
1586
                   d->config[PCI_SECONDARY_BUS],
1587
                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
1588
                   pci_get_word(d->config + PCI_VENDOR_ID),
1589
                   pci_get_word(d->config + PCI_DEVICE_ID),
1590
                   pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
1591
                   pci_get_word(d->config + PCI_SUBSYSTEM_ID));
1592
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
1593
        r = &d->io_regions[i];
1594
        if (!r->size)
1595
            continue;
1596
        monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
1597
                       " [0x%"FMT_PCIBUS"]\n",
1598
                       indent, "",
1599
                       i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
1600
                       r->addr, r->addr + r->size - 1);
1601
    }
1602
}
1603

    
1604
static PCIDeviceInfo bridge_info = {
1605
    .qdev.name    = "pci-bridge",
1606
    .qdev.size    = sizeof(PCIBridge),
1607
    .init         = pci_bridge_initfn,
1608
    .exit         = pci_bridge_exitfn,
1609
    .config_write = pci_bridge_write_config,
1610
    .qdev.props   = (Property[]) {
1611
        DEFINE_PROP_HEX32("vendorid", PCIBridge, vid, 0),
1612
        DEFINE_PROP_HEX32("deviceid", PCIBridge, did, 0),
1613
        DEFINE_PROP_END_OF_LIST(),
1614
    }
1615
};
1616

    
1617
static void pci_register_devices(void)
1618
{
1619
    pci_qdev_register(&bridge_info);
1620
}
1621

    
1622
device_init(pci_register_devices)