Statistics
| Branch: | Revision:

root / hw / pci.c @ c71b5b4a

History | View | Annotate | Download (46.1 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
    uint32_t config_reg; /* XXX: suppress */
45
    void *irq_opaque;
46
    PCIDevice *devices[256];
47
    PCIDevice *parent_dev;
48
    target_phys_addr_t mem_base;
49

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

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

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

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

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

    
76
static uint16_t pci_default_sub_vendor_id = PCI_SUBVENDOR_ID_REDHAT_QUMRANET;
77
static uint16_t pci_default_sub_device_id = PCI_SUBDEVICE_ID_QEMU;
78

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
198
    return NULL;
199
}
200

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

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

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

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

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

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

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

    
241
void pci_bus_set_mem_base(PCIBus *bus, target_phys_addr_t base)
242
{
243
    bus->mem_base = base;
244
}
245

    
246
PCIBus *pci_register_bus(DeviceState *parent, const char *name,
247
                         pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,
248
                         void *irq_opaque, int devfn_min, int nirq)
249
{
250
    PCIBus *bus;
251

    
252
    bus = pci_bus_new(parent, name, devfn_min);
253
    pci_bus_irqs(bus, set_irq, map_irq, irq_opaque, nirq);
254
    return bus;
255
}
256

    
257
static void pci_register_secondary_bus(PCIBus *parent,
258
                                       PCIBus *bus,
259
                                       PCIDevice *dev,
260
                                       pci_map_irq_fn map_irq,
261
                                       const char *name)
262
{
263
    qbus_create_inplace(&bus->qbus, &pci_bus_info, &dev->qdev, name);
264
    bus->map_irq = map_irq;
265
    bus->parent_dev = dev;
266

    
267
    QLIST_INIT(&bus->child);
268
    QLIST_INSERT_HEAD(&parent->child, bus, sibling);
269
}
270

    
271
static void pci_unregister_secondary_bus(PCIBus *bus)
272
{
273
    assert(QLIST_EMPTY(&bus->child));
274
    QLIST_REMOVE(bus, sibling);
275
}
276

    
277
int pci_bus_num(PCIBus *s)
278
{
279
    if (!s->parent_dev)
280
        return 0;       /* pci host bridge */
281
    return s->parent_dev->config[PCI_SECONDARY_BUS];
282
}
283

    
284
static int get_pci_config_device(QEMUFile *f, void *pv, size_t size)
285
{
286
    PCIDevice *s = container_of(pv, PCIDevice, config);
287
    uint8_t *config;
288
    int i;
289

    
290
    assert(size == pci_config_size(s));
291
    config = qemu_malloc(size);
292

    
293
    qemu_get_buffer(f, config, size);
294
    for (i = 0; i < size; ++i) {
295
        if ((config[i] ^ s->config[i]) & s->cmask[i] & ~s->wmask[i]) {
296
            qemu_free(config);
297
            return -EINVAL;
298
        }
299
    }
300
    memcpy(s->config, config, size);
301

    
302
    pci_update_mappings(s);
303

    
304
    qemu_free(config);
305
    return 0;
306
}
307

    
308
/* just put buffer */
309
static void put_pci_config_device(QEMUFile *f, void *pv, size_t size)
310
{
311
    const uint8_t **v = pv;
312
    assert(size == pci_config_size(container_of(pv, PCIDevice, config)));
313
    qemu_put_buffer(f, *v, size);
314
}
315

    
316
static VMStateInfo vmstate_info_pci_config = {
317
    .name = "pci config",
318
    .get  = get_pci_config_device,
319
    .put  = put_pci_config_device,
320
};
321

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

    
336
    for (i = 0; i < PCI_NUM_PINS; ++i) {
337
        pci_set_irq_state(s, i, irq_state[i]);
338
    }
339

    
340
    return 0;
341
}
342

    
343
static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)
344
{
345
    int i;
346
    PCIDevice *s = container_of(pv, PCIDevice, config);
347

    
348
    for (i = 0; i < PCI_NUM_PINS; ++i) {
349
        qemu_put_be32(f, pci_irq_state(s, i));
350
    }
351
}
352

    
353
static VMStateInfo vmstate_info_pci_irq_state = {
354
    .name = "pci irq state",
355
    .get  = get_pci_irq_state,
356
    .put  = put_pci_irq_state,
357
};
358

    
359
const VMStateDescription vmstate_pci_device = {
360
    .name = "PCIDevice",
361
    .version_id = 2,
362
    .minimum_version_id = 1,
363
    .minimum_version_id_old = 1,
364
    .fields      = (VMStateField []) {
365
        VMSTATE_INT32_LE(version_id, PCIDevice),
366
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
367
                                   vmstate_info_pci_config,
368
                                   PCI_CONFIG_SPACE_SIZE),
369
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
370
                                   vmstate_info_pci_irq_state,
371
                                   PCI_NUM_PINS * sizeof(int32_t)),
372
        VMSTATE_END_OF_LIST()
373
    }
374
};
375

    
376
const VMStateDescription vmstate_pcie_device = {
377
    .name = "PCIDevice",
378
    .version_id = 2,
379
    .minimum_version_id = 1,
380
    .minimum_version_id_old = 1,
381
    .fields      = (VMStateField []) {
382
        VMSTATE_INT32_LE(version_id, PCIDevice),
383
        VMSTATE_BUFFER_UNSAFE_INFO(config, PCIDevice, 0,
384
                                   vmstate_info_pci_config,
385
                                   PCIE_CONFIG_SPACE_SIZE),
386
        VMSTATE_BUFFER_UNSAFE_INFO(irq_state, PCIDevice, 2,
387
                                   vmstate_info_pci_irq_state,
388
                                   PCI_NUM_PINS * sizeof(int32_t)),
389
        VMSTATE_END_OF_LIST()
390
    }
391
};
392

    
393
static inline const VMStateDescription *pci_get_vmstate(PCIDevice *s)
394
{
395
    return pci_is_express(s) ? &vmstate_pcie_device : &vmstate_pci_device;
396
}
397

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

    
410
int pci_device_load(PCIDevice *s, QEMUFile *f)
411
{
412
    int ret;
413
    ret = vmstate_load_state(f, pci_get_vmstate(s), s, s->version_id);
414
    /* Restore the interrupt status bit. */
415
    pci_update_irq_status(s);
416
    return ret;
417
}
418

    
419
static int pci_set_default_subsystem_id(PCIDevice *pci_dev)
420
{
421
    uint16_t *id;
422

    
423
    id = (void*)(&pci_dev->config[PCI_SUBVENDOR_ID]);
424
    id[0] = cpu_to_le16(pci_default_sub_vendor_id);
425
    id[1] = cpu_to_le16(pci_default_sub_device_id);
426
    return 0;
427
}
428

    
429
/*
430
 * Parse [[<domain>:]<bus>:]<slot>, return -1 on error
431
 */
432
static int pci_parse_devaddr(const char *addr, int *domp, int *busp, unsigned *slotp)
433
{
434
    const char *p;
435
    char *e;
436
    unsigned long val;
437
    unsigned long dom = 0, bus = 0;
438
    unsigned slot = 0;
439

    
440
    p = addr;
441
    val = strtoul(p, &e, 16);
442
    if (e == p)
443
        return -1;
444
    if (*e == ':') {
445
        bus = val;
446
        p = e + 1;
447
        val = strtoul(p, &e, 16);
448
        if (e == p)
449
            return -1;
450
        if (*e == ':') {
451
            dom = bus;
452
            bus = val;
453
            p = e + 1;
454
            val = strtoul(p, &e, 16);
455
            if (e == p)
456
                return -1;
457
        }
458
    }
459

    
460
    if (dom > 0xffff || bus > 0xff || val > 0x1f)
461
        return -1;
462

    
463
    slot = val;
464

    
465
    if (*e)
466
        return -1;
467

    
468
    /* Note: QEMU doesn't implement domains other than 0 */
469
    if (!pci_find_bus(pci_find_root_bus(dom), bus))
470
        return -1;
471

    
472
    *domp = dom;
473
    *busp = bus;
474
    *slotp = slot;
475
    return 0;
476
}
477

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

    
492
PCIBus *pci_get_bus_devfn(int *devfnp, const char *devaddr)
493
{
494
    int dom, bus;
495
    unsigned slot;
496

    
497
    if (!devaddr) {
498
        *devfnp = -1;
499
        return pci_find_bus(pci_find_root_bus(0), 0);
500
    }
501

    
502
    if (pci_parse_devaddr(devaddr, &dom, &bus, &slot) < 0) {
503
        return NULL;
504
    }
505

    
506
    *devfnp = slot << 3;
507
    return pci_find_bus(pci_find_root_bus(0), bus);
508
}
509

    
510
static void pci_init_cmask(PCIDevice *dev)
511
{
512
    pci_set_word(dev->cmask + PCI_VENDOR_ID, 0xffff);
513
    pci_set_word(dev->cmask + PCI_DEVICE_ID, 0xffff);
514
    dev->cmask[PCI_STATUS] = PCI_STATUS_CAP_LIST;
515
    dev->cmask[PCI_REVISION_ID] = 0xff;
516
    dev->cmask[PCI_CLASS_PROG] = 0xff;
517
    pci_set_word(dev->cmask + PCI_CLASS_DEVICE, 0xffff);
518
    dev->cmask[PCI_HEADER_TYPE] = 0xff;
519
    dev->cmask[PCI_CAPABILITY_LIST] = 0xff;
520
}
521

    
522
static void pci_init_wmask(PCIDevice *dev)
523
{
524
    int config_size = pci_config_size(dev);
525

    
526
    dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;
527
    dev->wmask[PCI_INTERRUPT_LINE] = 0xff;
528
    pci_set_word(dev->wmask + PCI_COMMAND,
529
                 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);
530

    
531
    memset(dev->wmask + PCI_CONFIG_HEADER_SIZE, 0xff,
532
           config_size - PCI_CONFIG_HEADER_SIZE);
533
}
534

    
535
static void pci_init_wmask_bridge(PCIDevice *d)
536
{
537
    /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and
538
       PCI_SEC_LETENCY_TIMER */
539
    memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);
540

    
541
    /* base and limit */
542
    d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;
543
    d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;
544
    pci_set_word(d->wmask + PCI_MEMORY_BASE,
545
                 PCI_MEMORY_RANGE_MASK & 0xffff);
546
    pci_set_word(d->wmask + PCI_MEMORY_LIMIT,
547
                 PCI_MEMORY_RANGE_MASK & 0xffff);
548
    pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,
549
                 PCI_PREF_RANGE_MASK & 0xffff);
550
    pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,
551
                 PCI_PREF_RANGE_MASK & 0xffff);
552

    
553
    /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */
554
    memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);
555

    
556
    pci_set_word(d->wmask + PCI_BRIDGE_CONTROL, 0xffff);
557
}
558

    
559
static void pci_config_alloc(PCIDevice *pci_dev)
560
{
561
    int config_size = pci_config_size(pci_dev);
562

    
563
    pci_dev->config = qemu_mallocz(config_size);
564
    pci_dev->cmask = qemu_mallocz(config_size);
565
    pci_dev->wmask = qemu_mallocz(config_size);
566
    pci_dev->used = qemu_mallocz(config_size);
567
}
568

    
569
static void pci_config_free(PCIDevice *pci_dev)
570
{
571
    qemu_free(pci_dev->config);
572
    qemu_free(pci_dev->cmask);
573
    qemu_free(pci_dev->wmask);
574
    qemu_free(pci_dev->used);
575
}
576

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

    
604
    header_type &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
605
    if (header_type == PCI_HEADER_TYPE_NORMAL) {
606
        pci_set_default_subsystem_id(pci_dev);
607
    }
608
    pci_init_cmask(pci_dev);
609
    pci_init_wmask(pci_dev);
610
    if (header_type == PCI_HEADER_TYPE_BRIDGE) {
611
        pci_init_wmask_bridge(pci_dev);
612
    }
613

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

    
626
PCIDevice *pci_register_device(PCIBus *bus, const char *name,
627
                               int instance_size, int devfn,
628
                               PCIConfigReadFunc *config_read,
629
                               PCIConfigWriteFunc *config_write)
630
{
631
    PCIDevice *pci_dev;
632

    
633
    pci_dev = qemu_mallocz(instance_size);
634
    pci_dev = do_pci_register_device(pci_dev, bus, name, devfn,
635
                                     config_read, config_write,
636
                                     PCI_HEADER_TYPE_NORMAL);
637
    if (pci_dev == NULL) {
638
        hw_error("PCI: can't register device\n");
639
    }
640
    return pci_dev;
641
}
642

    
643
static target_phys_addr_t pci_to_cpu_addr(PCIBus *bus,
644
                                          target_phys_addr_t addr)
645
{
646
    return addr + bus->mem_base;
647
}
648

    
649
static void pci_unregister_io_regions(PCIDevice *pci_dev)
650
{
651
    PCIIORegion *r;
652
    int i;
653

    
654
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
655
        r = &pci_dev->io_regions[i];
656
        if (!r->size || r->addr == PCI_BAR_UNMAPPED)
657
            continue;
658
        if (r->type == PCI_BASE_ADDRESS_SPACE_IO) {
659
            isa_unassign_ioport(r->addr, r->filtered_size);
660
        } else {
661
            cpu_register_physical_memory(pci_to_cpu_addr(pci_dev->bus,
662
                                                         r->addr),
663
                                         r->filtered_size,
664
                                         IO_MEM_UNASSIGNED);
665
        }
666
    }
667
}
668

    
669
static int pci_unregister_device(DeviceState *dev)
670
{
671
    PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
672
    PCIDeviceInfo *info = DO_UPCAST(PCIDeviceInfo, qdev, dev->info);
673
    int ret = 0;
674

    
675
    if (info->exit)
676
        ret = info->exit(pci_dev);
677
    if (ret)
678
        return ret;
679

    
680
    pci_unregister_io_regions(pci_dev);
681

    
682
    qemu_free_irqs(pci_dev->irq);
683
    pci_dev->bus->devices[pci_dev->devfn] = NULL;
684
    pci_config_free(pci_dev);
685
    return 0;
686
}
687

    
688
void pci_register_bar(PCIDevice *pci_dev, int region_num,
689
                            pcibus_t size, int type,
690
                            PCIMapIORegionFunc *map_func)
691
{
692
    PCIIORegion *r;
693
    uint32_t addr;
694
    pcibus_t wmask;
695

    
696
    if ((unsigned int)region_num >= PCI_NUM_REGIONS)
697
        return;
698

    
699
    if (size & (size-1)) {
700
        fprintf(stderr, "ERROR: PCI region size must be pow2 "
701
                    "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);
702
        exit(1);
703
    }
704

    
705
    r = &pci_dev->io_regions[region_num];
706
    r->addr = PCI_BAR_UNMAPPED;
707
    r->size = size;
708
    r->filtered_size = size;
709
    r->type = type;
710
    r->map_func = map_func;
711

    
712
    wmask = ~(size - 1);
713
    addr = pci_bar(pci_dev, region_num);
714
    if (region_num == PCI_ROM_SLOT) {
715
        /* ROM enable bit is writeable */
716
        wmask |= PCI_ROM_ADDRESS_ENABLE;
717
    }
718
    pci_set_long(pci_dev->config + addr, type);
719
    if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&
720
        r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {
721
        pci_set_quad(pci_dev->wmask + addr, wmask);
722
        pci_set_quad(pci_dev->cmask + addr, ~0ULL);
723
    } else {
724
        pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);
725
        pci_set_long(pci_dev->cmask + addr, 0xffffffff);
726
    }
727
}
728

    
729
static uint32_t pci_config_get_io_base(PCIDevice *d,
730
                                       uint32_t base, uint32_t base_upper16)
731
{
732
    uint32_t val;
733

    
734
    val = ((uint32_t)d->config[base] & PCI_IO_RANGE_MASK) << 8;
735
    if (d->config[base] & PCI_IO_RANGE_TYPE_32) {
736
        val |= (uint32_t)pci_get_word(d->config + base_upper16) << 16;
737
    }
738
    return val;
739
}
740

    
741
static pcibus_t pci_config_get_memory_base(PCIDevice *d, uint32_t base)
742
{
743
    return ((pcibus_t)pci_get_word(d->config + base) & PCI_MEMORY_RANGE_MASK)
744
        << 16;
745
}
746

    
747
static pcibus_t pci_config_get_pref_base(PCIDevice *d,
748
                                         uint32_t base, uint32_t upper)
749
{
750
    pcibus_t tmp;
751
    pcibus_t val;
752

    
753
    tmp = (pcibus_t)pci_get_word(d->config + base);
754
    val = (tmp & PCI_PREF_RANGE_MASK) << 16;
755
    if (tmp & PCI_PREF_RANGE_TYPE_64) {
756
        val |= (pcibus_t)pci_get_long(d->config + upper) << 32;
757
    }
758
    return val;
759
}
760

    
761
static pcibus_t pci_bridge_get_base(PCIDevice *bridge, uint8_t type)
762
{
763
    pcibus_t base;
764
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
765
        base = pci_config_get_io_base(bridge,
766
                                      PCI_IO_BASE, PCI_IO_BASE_UPPER16);
767
    } else {
768
        if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
769
            base = pci_config_get_pref_base(
770
                bridge, PCI_PREF_MEMORY_BASE, PCI_PREF_BASE_UPPER32);
771
        } else {
772
            base = pci_config_get_memory_base(bridge, PCI_MEMORY_BASE);
773
        }
774
    }
775

    
776
    return base;
777
}
778

    
779
static pcibus_t pci_bridge_get_limit(PCIDevice *bridge, uint8_t type)
780
{
781
    pcibus_t limit;
782
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
783
        limit = pci_config_get_io_base(bridge,
784
                                      PCI_IO_LIMIT, PCI_IO_LIMIT_UPPER16);
785
        limit |= 0xfff;         /* PCI bridge spec 3.2.5.6. */
786
    } else {
787
        if (type & PCI_BASE_ADDRESS_MEM_PREFETCH) {
788
            limit = pci_config_get_pref_base(
789
                bridge, PCI_PREF_MEMORY_LIMIT, PCI_PREF_LIMIT_UPPER32);
790
        } else {
791
            limit = pci_config_get_memory_base(bridge, PCI_MEMORY_LIMIT);
792
        }
793
        limit |= 0xfffff;       /* PCI bridge spec 3.2.5.{1, 8}. */
794
    }
795
    return limit;
796
}
797

    
798
static void pci_bridge_filter(PCIDevice *d, pcibus_t *addr, pcibus_t *size,
799
                              uint8_t type)
800
{
801
    pcibus_t base = *addr;
802
    pcibus_t limit = *addr + *size - 1;
803
    PCIDevice *br;
804

    
805
    for (br = d->bus->parent_dev; br; br = br->bus->parent_dev) {
806
        uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
807

    
808
        if (type & PCI_BASE_ADDRESS_SPACE_IO) {
809
            if (!(cmd & PCI_COMMAND_IO)) {
810
                goto no_map;
811
            }
812
        } else {
813
            if (!(cmd & PCI_COMMAND_MEMORY)) {
814
                goto no_map;
815
            }
816
        }
817

    
818
        base = MAX(base, pci_bridge_get_base(br, type));
819
        limit = MIN(limit, pci_bridge_get_limit(br, type));
820
    }
821

    
822
    if (base > limit) {
823
        goto no_map;
824
    }
825
    *addr = base;
826
    *size = limit - base + 1;
827
    return;
828
no_map:
829
    *addr = PCI_BAR_UNMAPPED;
830
    *size = 0;
831
}
832

    
833
static pcibus_t pci_bar_address(PCIDevice *d,
834
                                int reg, uint8_t type, pcibus_t size)
835
{
836
    pcibus_t new_addr, last_addr;
837
    int bar = pci_bar(d, reg);
838
    uint16_t cmd = pci_get_word(d->config + PCI_COMMAND);
839

    
840
    if (type & PCI_BASE_ADDRESS_SPACE_IO) {
841
        if (!(cmd & PCI_COMMAND_IO)) {
842
            return PCI_BAR_UNMAPPED;
843
        }
844
        new_addr = pci_get_long(d->config + bar) & ~(size - 1);
845
        last_addr = new_addr + size - 1;
846
        /* NOTE: we have only 64K ioports on PC */
847
        if (last_addr <= new_addr || new_addr == 0 || last_addr > UINT16_MAX) {
848
            return PCI_BAR_UNMAPPED;
849
        }
850
        return new_addr;
851
    }
852

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

    
876
    /* Now pcibus_t is 64bit.
877
     * Check if 32 bit BAR wraps around explicitly.
878
     * Without this, PC ide doesn't work well.
879
     * TODO: remove this work around.
880
     */
881
    if  (!(type & PCI_BASE_ADDRESS_MEM_TYPE_64) && last_addr >= UINT32_MAX) {
882
        return PCI_BAR_UNMAPPED;
883
    }
884

    
885
    /*
886
     * OS is allowed to set BAR beyond its addressable
887
     * bits. For example, 32 bit OS can set 64bit bar
888
     * to >4G. Check it. TODO: we might need to support
889
     * it in the future for e.g. PAE.
890
     */
891
    if (last_addr >= TARGET_PHYS_ADDR_MAX) {
892
        return PCI_BAR_UNMAPPED;
893
    }
894

    
895
    return new_addr;
896
}
897

    
898
static void pci_update_mappings(PCIDevice *d)
899
{
900
    PCIIORegion *r;
901
    int i;
902
    pcibus_t new_addr, filtered_size;
903

    
904
    for(i = 0; i < PCI_NUM_REGIONS; i++) {
905
        r = &d->io_regions[i];
906

    
907
        /* this region isn't registered */
908
        if (!r->size)
909
            continue;
910

    
911
        new_addr = pci_bar_address(d, i, r->type, r->size);
912

    
913
        /* bridge filtering */
914
        filtered_size = r->size;
915
        if (new_addr != PCI_BAR_UNMAPPED) {
916
            pci_bridge_filter(d, &new_addr, &filtered_size, r->type);
917
        }
918

    
919
        /* This bar isn't changed */
920
        if (new_addr == r->addr && filtered_size == r->filtered_size)
921
            continue;
922

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

    
957
uint32_t pci_default_read_config(PCIDevice *d,
958
                                 uint32_t address, int len)
959
{
960
    uint32_t val = 0;
961
    assert(len == 1 || len == 2 || len == 4);
962
    len = MIN(len, pci_config_size(d) - address);
963
    memcpy(&val, d->config + address, len);
964
    return le32_to_cpu(val);
965
}
966

    
967
void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)
968
{
969
    int i;
970
    uint32_t config_size = pci_config_size(d);
971

    
972
    for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {
973
        uint8_t wmask = d->wmask[addr + i];
974
        d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);
975
    }
976
    if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||
977
        ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||
978
        ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||
979
        range_covers_byte(addr, l, PCI_COMMAND))
980
        pci_update_mappings(d);
981
}
982

    
983
/***********************************************************/
984
/* generic PCI irq support */
985

    
986
/* 0 <= irq_num <= 3. level must be 0 or 1 */
987
static void pci_set_irq(void *opaque, int irq_num, int level)
988
{
989
    PCIDevice *pci_dev = opaque;
990
    int change;
991

    
992
    change = level - pci_irq_state(pci_dev, irq_num);
993
    if (!change)
994
        return;
995

    
996
    pci_set_irq_state(pci_dev, irq_num, level);
997
    pci_update_irq_status(pci_dev);
998
    pci_change_irq_level(pci_dev, irq_num, change);
999
}
1000

    
1001
/***********************************************************/
1002
/* monitor info on PCI */
1003

    
1004
typedef struct {
1005
    uint16_t class;
1006
    const char *desc;
1007
} pci_class_desc;
1008

    
1009
static const pci_class_desc pci_class_descriptions[] =
1010
{
1011
    { 0x0100, "SCSI controller"},
1012
    { 0x0101, "IDE controller"},
1013
    { 0x0102, "Floppy controller"},
1014
    { 0x0103, "IPI controller"},
1015
    { 0x0104, "RAID controller"},
1016
    { 0x0106, "SATA controller"},
1017
    { 0x0107, "SAS controller"},
1018
    { 0x0180, "Storage controller"},
1019
    { 0x0200, "Ethernet controller"},
1020
    { 0x0201, "Token Ring controller"},
1021
    { 0x0202, "FDDI controller"},
1022
    { 0x0203, "ATM controller"},
1023
    { 0x0280, "Network controller"},
1024
    { 0x0300, "VGA controller"},
1025
    { 0x0301, "XGA controller"},
1026
    { 0x0302, "3D controller"},
1027
    { 0x0380, "Display controller"},
1028
    { 0x0400, "Video controller"},
1029
    { 0x0401, "Audio controller"},
1030
    { 0x0402, "Phone"},
1031
    { 0x0480, "Multimedia controller"},
1032
    { 0x0500, "RAM controller"},
1033
    { 0x0501, "Flash controller"},
1034
    { 0x0580, "Memory controller"},
1035
    { 0x0600, "Host bridge"},
1036
    { 0x0601, "ISA bridge"},
1037
    { 0x0602, "EISA bridge"},
1038
    { 0x0603, "MC bridge"},
1039
    { 0x0604, "PCI bridge"},
1040
    { 0x0605, "PCMCIA bridge"},
1041
    { 0x0606, "NUBUS bridge"},
1042
    { 0x0607, "CARDBUS bridge"},
1043
    { 0x0608, "RACEWAY bridge"},
1044
    { 0x0680, "Bridge"},
1045
    { 0x0c03, "USB controller"},
1046
    { 0, NULL}
1047
};
1048

    
1049
static void pci_info_device(PCIBus *bus, PCIDevice *d)
1050
{
1051
    Monitor *mon = cur_mon;
1052
    int i, class;
1053
    PCIIORegion *r;
1054
    const pci_class_desc *desc;
1055

    
1056
    monitor_printf(mon, "  Bus %2d, device %3d, function %d:\n",
1057
                   pci_bus_num(d->bus),
1058
                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn));
1059
    class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1060
    monitor_printf(mon, "    ");
1061
    desc = pci_class_descriptions;
1062
    while (desc->desc && class != desc->class)
1063
        desc++;
1064
    if (desc->desc) {
1065
        monitor_printf(mon, "%s", desc->desc);
1066
    } else {
1067
        monitor_printf(mon, "Class %04x", class);
1068
    }
1069
    monitor_printf(mon, ": PCI device %04x:%04x\n",
1070
           pci_get_word(d->config + PCI_VENDOR_ID),
1071
           pci_get_word(d->config + PCI_DEVICE_ID));
1072

    
1073
    if (d->config[PCI_INTERRUPT_PIN] != 0) {
1074
        monitor_printf(mon, "      IRQ %d.\n",
1075
                       d->config[PCI_INTERRUPT_LINE]);
1076
    }
1077
    if (class == 0x0604) {
1078
        uint64_t base;
1079
        uint64_t limit;
1080

    
1081
        monitor_printf(mon, "      BUS %d.\n", d->config[0x19]);
1082
        monitor_printf(mon, "      secondary bus %d.\n",
1083
                       d->config[PCI_SECONDARY_BUS]);
1084
        monitor_printf(mon, "      subordinate bus %d.\n",
1085
                       d->config[PCI_SUBORDINATE_BUS]);
1086

    
1087
        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_IO);
1088
        limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_IO);
1089
        monitor_printf(mon, "      IO range [0x%04"PRIx64", 0x%04"PRIx64"]\n",
1090
                       base, limit);
1091

    
1092
        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY);
1093
        limit= pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_MEMORY);
1094
        monitor_printf(mon,
1095
                       "      memory range [0x%08"PRIx64", 0x%08"PRIx64"]\n",
1096
                       base, limit);
1097

    
1098
        base = pci_bridge_get_base(d, PCI_BASE_ADDRESS_SPACE_MEMORY |
1099
                                   PCI_BASE_ADDRESS_MEM_PREFETCH);
1100
        limit = pci_bridge_get_limit(d, PCI_BASE_ADDRESS_SPACE_MEMORY |
1101
                                     PCI_BASE_ADDRESS_MEM_PREFETCH);
1102
        monitor_printf(mon, "      prefetchable memory range "
1103
                       "[0x%08"PRIx64", 0x%08"PRIx64"]\n", base, limit);
1104
    }
1105
    for(i = 0;i < PCI_NUM_REGIONS; i++) {
1106
        r = &d->io_regions[i];
1107
        if (r->size != 0) {
1108
            monitor_printf(mon, "      BAR%d: ", i);
1109
            if (r->type & PCI_BASE_ADDRESS_SPACE_IO) {
1110
                monitor_printf(mon, "I/O at 0x%04"FMT_PCIBUS
1111
                               " [0x%04"FMT_PCIBUS"].\n",
1112
                               r->addr, r->addr + r->size - 1);
1113
            } else {
1114
                const char *type = r->type & PCI_BASE_ADDRESS_MEM_TYPE_64 ?
1115
                    "64 bit" : "32 bit";
1116
                const char *prefetch =
1117
                    r->type & PCI_BASE_ADDRESS_MEM_PREFETCH ?
1118
                    " prefetchable" : "";
1119

    
1120
                monitor_printf(mon, "%s%s memory at 0x%08"FMT_PCIBUS
1121
                               " [0x%08"FMT_PCIBUS"].\n",
1122
                               type, prefetch,
1123
                               r->addr, r->addr + r->size - 1);
1124
            }
1125
        }
1126
    }
1127
    monitor_printf(mon, "      id \"%s\"\n", d->qdev.id ? d->qdev.id : "");
1128
    if (class == 0x0604 && d->config[0x19] != 0) {
1129
        pci_for_each_device(bus, d->config[0x19], pci_info_device);
1130
    }
1131
}
1132

    
1133
static void pci_for_each_device_under_bus(PCIBus *bus,
1134
                                          void (*fn)(PCIBus *b, PCIDevice *d))
1135
{
1136
    PCIDevice *d;
1137
    int devfn;
1138

    
1139
    for(devfn = 0; devfn < ARRAY_SIZE(bus->devices); devfn++) {
1140
        d = bus->devices[devfn];
1141
        if (d)
1142
            fn(bus, d);
1143
    }
1144
}
1145

    
1146
void pci_for_each_device(PCIBus *bus, int bus_num,
1147
                         void (*fn)(PCIBus *b, PCIDevice *d))
1148
{
1149
    bus = pci_find_bus(bus, bus_num);
1150

    
1151
    if (bus) {
1152
        pci_for_each_device_under_bus(bus, fn);
1153
    }
1154
}
1155

    
1156
void pci_info(Monitor *mon)
1157
{
1158
    struct PCIHostBus *host;
1159
    QLIST_FOREACH(host, &host_buses, next) {
1160
        pci_for_each_device(host->bus, 0, pci_info_device);
1161
    }
1162
}
1163

    
1164
static const char * const pci_nic_models[] = {
1165
    "ne2k_pci",
1166
    "i82551",
1167
    "i82557b",
1168
    "i82559er",
1169
    "rtl8139",
1170
    "e1000",
1171
    "pcnet",
1172
    "virtio",
1173
    NULL
1174
};
1175

    
1176
static const char * const pci_nic_names[] = {
1177
    "ne2k_pci",
1178
    "i82551",
1179
    "i82557b",
1180
    "i82559er",
1181
    "rtl8139",
1182
    "e1000",
1183
    "pcnet",
1184
    "virtio-net-pci",
1185
    NULL
1186
};
1187

    
1188
/* Initialize a PCI NIC.  */
1189
/* FIXME callers should check for failure, but don't */
1190
PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,
1191
                        const char *default_devaddr)
1192
{
1193
    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;
1194
    PCIBus *bus;
1195
    int devfn;
1196
    PCIDevice *pci_dev;
1197
    DeviceState *dev;
1198
    int i;
1199

    
1200
    i = qemu_find_nic_model(nd, pci_nic_models, default_model);
1201
    if (i < 0)
1202
        return NULL;
1203

    
1204
    bus = pci_get_bus_devfn(&devfn, devaddr);
1205
    if (!bus) {
1206
        qemu_error("Invalid PCI device address %s for device %s\n",
1207
                   devaddr, pci_nic_names[i]);
1208
        return NULL;
1209
    }
1210

    
1211
    pci_dev = pci_create(bus, devfn, pci_nic_names[i]);
1212
    dev = &pci_dev->qdev;
1213
    if (nd->name)
1214
        dev->id = qemu_strdup(nd->name);
1215
    qdev_set_nic_properties(dev, nd);
1216
    if (qdev_init(dev) < 0)
1217
        return NULL;
1218
    return pci_dev;
1219
}
1220

    
1221
PCIDevice *pci_nic_init_nofail(NICInfo *nd, const char *default_model,
1222
                               const char *default_devaddr)
1223
{
1224
    PCIDevice *res;
1225

    
1226
    if (qemu_show_nic_models(nd->model, pci_nic_models))
1227
        exit(0);
1228

    
1229
    res = pci_nic_init(nd, default_model, default_devaddr);
1230
    if (!res)
1231
        exit(1);
1232
    return res;
1233
}
1234

    
1235
typedef struct {
1236
    PCIDevice dev;
1237
    PCIBus bus;
1238
    uint32_t vid;
1239
    uint32_t did;
1240
} PCIBridge;
1241

    
1242

    
1243
static void pci_bridge_update_mappings_fn(PCIBus *b, PCIDevice *d)
1244
{
1245
    pci_update_mappings(d);
1246
}
1247

    
1248
static void pci_bridge_update_mappings(PCIBus *b)
1249
{
1250
    PCIBus *child;
1251

    
1252
    pci_for_each_device_under_bus(b, pci_bridge_update_mappings_fn);
1253

    
1254
    QLIST_FOREACH(child, &b->child, sibling) {
1255
        pci_bridge_update_mappings(child);
1256
    }
1257
}
1258

    
1259
static void pci_bridge_write_config(PCIDevice *d,
1260
                             uint32_t address, uint32_t val, int len)
1261
{
1262
    pci_default_write_config(d, address, val, len);
1263

    
1264
    if (/* io base/limit */
1265
        ranges_overlap(address, len, PCI_IO_BASE, 2) ||
1266

    
1267
        /* memory base/limit, prefetchable base/limit and
1268
           io base/limit upper 16 */
1269
        ranges_overlap(address, len, PCI_MEMORY_BASE, 20)) {
1270
        pci_bridge_update_mappings(d->bus);
1271
    }
1272
}
1273

    
1274
PCIBus *pci_find_bus(PCIBus *bus, int bus_num)
1275
{
1276
    PCIBus *sec;
1277

    
1278
    if (!bus)
1279
        return NULL;
1280

    
1281
    if (pci_bus_num(bus) == bus_num) {
1282
        return bus;
1283
    }
1284

    
1285
    /* try child bus */
1286
    QLIST_FOREACH(sec, &bus->child, sibling) {
1287

    
1288
        if (!bus->parent_dev /* pci host bridge */
1289
            || (pci_bus_num(sec) <= bus_num &&
1290
                bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {
1291
            return pci_find_bus(sec, bus_num);
1292
        }
1293
    }
1294

    
1295
    return NULL;
1296
}
1297

    
1298
PCIDevice *pci_find_device(PCIBus *bus, int bus_num, int slot, int function)
1299
{
1300
    bus = pci_find_bus(bus, bus_num);
1301

    
1302
    if (!bus)
1303
        return NULL;
1304

    
1305
    return bus->devices[PCI_DEVFN(slot, function)];
1306
}
1307

    
1308
static int pci_bridge_initfn(PCIDevice *dev)
1309
{
1310
    PCIBridge *s = DO_UPCAST(PCIBridge, dev, dev);
1311

    
1312
    pci_config_set_vendor_id(s->dev.config, s->vid);
1313
    pci_config_set_device_id(s->dev.config, s->did);
1314

    
1315
    pci_set_word(dev->config + PCI_STATUS,
1316
                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1317
    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_PCI);
1318
    dev->config[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_BRIDGE;
1319
    pci_set_word(dev->config + PCI_SEC_STATUS,
1320
                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);
1321
    return 0;
1322
}
1323

    
1324
static int pci_bridge_exitfn(PCIDevice *pci_dev)
1325
{
1326
    PCIBridge *s = DO_UPCAST(PCIBridge, dev, pci_dev);
1327
    PCIBus *bus = &s->bus;
1328
    pci_unregister_secondary_bus(bus);
1329
    return 0;
1330
}
1331

    
1332
PCIBus *pci_bridge_init(PCIBus *bus, int devfn, uint16_t vid, uint16_t did,
1333
                        pci_map_irq_fn map_irq, const char *name)
1334
{
1335
    PCIDevice *dev;
1336
    PCIBridge *s;
1337

    
1338
    dev = pci_create(bus, devfn, "pci-bridge");
1339
    qdev_prop_set_uint32(&dev->qdev, "vendorid", vid);
1340
    qdev_prop_set_uint32(&dev->qdev, "deviceid", did);
1341
    qdev_init_nofail(&dev->qdev);
1342

    
1343
    s = DO_UPCAST(PCIBridge, dev, dev);
1344
    pci_register_secondary_bus(bus, &s->bus, &s->dev, map_irq, name);
1345
    return &s->bus;
1346
}
1347

    
1348
PCIDevice *pci_bridge_get_device(PCIBus *bus)
1349
{
1350
    return bus->parent_dev;
1351
}
1352

    
1353
static int pci_qdev_init(DeviceState *qdev, DeviceInfo *base)
1354
{
1355
    PCIDevice *pci_dev = (PCIDevice *)qdev;
1356
    PCIDeviceInfo *info = container_of(base, PCIDeviceInfo, qdev);
1357
    PCIBus *bus;
1358
    int devfn, rc;
1359

    
1360
    /* initialize cap_present for pci_is_express() and pci_config_size() */
1361
    if (info->is_express) {
1362
        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
1363
    }
1364

    
1365
    bus = FROM_QBUS(PCIBus, qdev_get_parent_bus(qdev));
1366
    devfn = pci_dev->devfn;
1367
    pci_dev = do_pci_register_device(pci_dev, bus, base->name, devfn,
1368
                                     info->config_read, info->config_write,
1369
                                     info->header_type);
1370
    if (pci_dev == NULL)
1371
        return -1;
1372
    rc = info->init(pci_dev);
1373
    if (rc != 0)
1374
        return rc;
1375

    
1376
    /* rom loading */
1377
    if (pci_dev->romfile == NULL && info->romfile != NULL)
1378
        pci_dev->romfile = qemu_strdup(info->romfile);
1379
    pci_add_option_rom(pci_dev);
1380

    
1381
    if (qdev->hotplugged)
1382
        bus->hotplug(pci_dev, 1);
1383
    return 0;
1384
}
1385

    
1386
static int pci_unplug_device(DeviceState *qdev)
1387
{
1388
    PCIDevice *dev = DO_UPCAST(PCIDevice, qdev, qdev);
1389

    
1390
    dev->bus->hotplug(dev, 0);
1391
    return 0;
1392
}
1393

    
1394
void pci_qdev_register(PCIDeviceInfo *info)
1395
{
1396
    info->qdev.init = pci_qdev_init;
1397
    info->qdev.unplug = pci_unplug_device;
1398
    info->qdev.exit = pci_unregister_device;
1399
    info->qdev.bus_info = &pci_bus_info;
1400
    qdev_register(&info->qdev);
1401
}
1402

    
1403
void pci_qdev_register_many(PCIDeviceInfo *info)
1404
{
1405
    while (info->qdev.name) {
1406
        pci_qdev_register(info);
1407
        info++;
1408
    }
1409
}
1410

    
1411
PCIDevice *pci_create(PCIBus *bus, int devfn, const char *name)
1412
{
1413
    DeviceState *dev;
1414

    
1415
    dev = qdev_create(&bus->qbus, name);
1416
    qdev_prop_set_uint32(dev, "addr", devfn);
1417
    return DO_UPCAST(PCIDevice, qdev, dev);
1418
}
1419

    
1420
PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)
1421
{
1422
    PCIDevice *dev = pci_create(bus, devfn, name);
1423
    qdev_init_nofail(&dev->qdev);
1424
    return dev;
1425
}
1426

    
1427
static int pci_find_space(PCIDevice *pdev, uint8_t size)
1428
{
1429
    int config_size = pci_config_size(pdev);
1430
    int offset = PCI_CONFIG_HEADER_SIZE;
1431
    int i;
1432
    for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)
1433
        if (pdev->used[i])
1434
            offset = i + 1;
1435
        else if (i - offset + 1 == size)
1436
            return offset;
1437
    return 0;
1438
}
1439

    
1440
static uint8_t pci_find_capability_list(PCIDevice *pdev, uint8_t cap_id,
1441
                                        uint8_t *prev_p)
1442
{
1443
    uint8_t next, prev;
1444

    
1445
    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST))
1446
        return 0;
1447

    
1448
    for (prev = PCI_CAPABILITY_LIST; (next = pdev->config[prev]);
1449
         prev = next + PCI_CAP_LIST_NEXT)
1450
        if (pdev->config[next + PCI_CAP_LIST_ID] == cap_id)
1451
            break;
1452

    
1453
    if (prev_p)
1454
        *prev_p = prev;
1455
    return next;
1456
}
1457

    
1458
static void pci_map_option_rom(PCIDevice *pdev, int region_num, pcibus_t addr, pcibus_t size, int type)
1459
{
1460
    cpu_register_physical_memory(addr, size, pdev->rom_offset);
1461
}
1462

    
1463
/* Add an option rom for the device */
1464
static int pci_add_option_rom(PCIDevice *pdev)
1465
{
1466
    int size;
1467
    char *path;
1468
    void *ptr;
1469

    
1470
    if (!pdev->romfile)
1471
        return 0;
1472
    if (strlen(pdev->romfile) == 0)
1473
        return 0;
1474

    
1475
    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);
1476
    if (path == NULL) {
1477
        path = qemu_strdup(pdev->romfile);
1478
    }
1479

    
1480
    size = get_image_size(path);
1481
    if (size < 0) {
1482
        qemu_error("%s: failed to find romfile \"%s\"\n", __FUNCTION__,
1483
                   pdev->romfile);
1484
        return -1;
1485
    }
1486
    if (size & (size - 1)) {
1487
        size = 1 << qemu_fls(size);
1488
    }
1489

    
1490
    pdev->rom_offset = qemu_ram_alloc(size);
1491

    
1492
    ptr = qemu_get_ram_ptr(pdev->rom_offset);
1493
    load_image(path, ptr);
1494
    qemu_free(path);
1495

    
1496
    pci_register_bar(pdev, PCI_ROM_SLOT, size,
1497
                     0, pci_map_option_rom);
1498

    
1499
    return 0;
1500
}
1501

    
1502
/* Reserve space and add capability to the linked list in pci config space */
1503
int pci_add_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1504
{
1505
    uint8_t offset = pci_find_space(pdev, size);
1506
    uint8_t *config = pdev->config + offset;
1507
    if (!offset)
1508
        return -ENOSPC;
1509
    config[PCI_CAP_LIST_ID] = cap_id;
1510
    config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];
1511
    pdev->config[PCI_CAPABILITY_LIST] = offset;
1512
    pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1513
    memset(pdev->used + offset, 0xFF, size);
1514
    /* Make capability read-only by default */
1515
    memset(pdev->wmask + offset, 0, size);
1516
    /* Check capability by default */
1517
    memset(pdev->cmask + offset, 0xFF, size);
1518
    return offset;
1519
}
1520

    
1521
/* Unlink capability from the pci config space. */
1522
void pci_del_capability(PCIDevice *pdev, uint8_t cap_id, uint8_t size)
1523
{
1524
    uint8_t prev, offset = pci_find_capability_list(pdev, cap_id, &prev);
1525
    if (!offset)
1526
        return;
1527
    pdev->config[prev] = pdev->config[offset + PCI_CAP_LIST_NEXT];
1528
    /* Make capability writeable again */
1529
    memset(pdev->wmask + offset, 0xff, size);
1530
    /* Clear cmask as device-specific registers can't be checked */
1531
    memset(pdev->cmask + offset, 0, size);
1532
    memset(pdev->used + offset, 0, size);
1533

    
1534
    if (!pdev->config[PCI_CAPABILITY_LIST])
1535
        pdev->config[PCI_STATUS] &= ~PCI_STATUS_CAP_LIST;
1536
}
1537

    
1538
/* Reserve space for capability at a known offset (to call after load). */
1539
void pci_reserve_capability(PCIDevice *pdev, uint8_t offset, uint8_t size)
1540
{
1541
    memset(pdev->used + offset, 0xff, size);
1542
}
1543

    
1544
uint8_t pci_find_capability(PCIDevice *pdev, uint8_t cap_id)
1545
{
1546
    return pci_find_capability_list(pdev, cap_id, NULL);
1547
}
1548

    
1549
static void pcibus_dev_print(Monitor *mon, DeviceState *dev, int indent)
1550
{
1551
    PCIDevice *d = (PCIDevice *)dev;
1552
    const pci_class_desc *desc;
1553
    char ctxt[64];
1554
    PCIIORegion *r;
1555
    int i, class;
1556

    
1557
    class = pci_get_word(d->config + PCI_CLASS_DEVICE);
1558
    desc = pci_class_descriptions;
1559
    while (desc->desc && class != desc->class)
1560
        desc++;
1561
    if (desc->desc) {
1562
        snprintf(ctxt, sizeof(ctxt), "%s", desc->desc);
1563
    } else {
1564
        snprintf(ctxt, sizeof(ctxt), "Class %04x", class);
1565
    }
1566

    
1567
    monitor_printf(mon, "%*sclass %s, addr %02x:%02x.%x, "
1568
                   "pci id %04x:%04x (sub %04x:%04x)\n",
1569
                   indent, "", ctxt,
1570
                   d->config[PCI_SECONDARY_BUS],
1571
                   PCI_SLOT(d->devfn), PCI_FUNC(d->devfn),
1572
                   pci_get_word(d->config + PCI_VENDOR_ID),
1573
                   pci_get_word(d->config + PCI_DEVICE_ID),
1574
                   pci_get_word(d->config + PCI_SUBSYSTEM_VENDOR_ID),
1575
                   pci_get_word(d->config + PCI_SUBSYSTEM_ID));
1576
    for (i = 0; i < PCI_NUM_REGIONS; i++) {
1577
        r = &d->io_regions[i];
1578
        if (!r->size)
1579
            continue;
1580
        monitor_printf(mon, "%*sbar %d: %s at 0x%"FMT_PCIBUS
1581
                       " [0x%"FMT_PCIBUS"]\n",
1582
                       indent, "",
1583
                       i, r->type & PCI_BASE_ADDRESS_SPACE_IO ? "i/o" : "mem",
1584
                       r->addr, r->addr + r->size - 1);
1585
    }
1586
}
1587

    
1588
static PCIDeviceInfo bridge_info = {
1589
    .qdev.name    = "pci-bridge",
1590
    .qdev.size    = sizeof(PCIBridge),
1591
    .init         = pci_bridge_initfn,
1592
    .exit         = pci_bridge_exitfn,
1593
    .config_write = pci_bridge_write_config,
1594
    .qdev.props   = (Property[]) {
1595
        DEFINE_PROP_HEX32("vendorid", PCIBridge, vid, 0),
1596
        DEFINE_PROP_HEX32("deviceid", PCIBridge, did, 0),
1597
        DEFINE_PROP_END_OF_LIST(),
1598
    }
1599
};
1600

    
1601
static void pci_register_devices(void)
1602
{
1603
    pci_qdev_register(&bridge_info);
1604
}
1605

    
1606
device_init(pci_register_devices)