Statistics
| Branch: | Revision:

root / hw / misc / vfio.c @ 1d5bf692

History | View | Annotate | Download (116.1 kB)

1
/*
2
 * vfio based device assignment support
3
 *
4
 * Copyright Red Hat, Inc. 2012
5
 *
6
 * Authors:
7
 *  Alex Williamson <alex.williamson@redhat.com>
8
 *
9
 * This work is licensed under the terms of the GNU GPL, version 2.  See
10
 * the COPYING file in the top-level directory.
11
 *
12
 * Based on qemu-kvm device-assignment:
13
 *  Adapted for KVM by Qumranet.
14
 *  Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
15
 *  Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
16
 *  Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
17
 *  Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
18
 *  Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
19
 */
20

    
21
#include <dirent.h>
22
#include <linux/vfio.h>
23
#include <sys/ioctl.h>
24
#include <sys/mman.h>
25
#include <sys/stat.h>
26
#include <sys/types.h>
27
#include <unistd.h>
28

    
29
#include "config.h"
30
#include "exec/address-spaces.h"
31
#include "exec/memory.h"
32
#include "hw/pci/msi.h"
33
#include "hw/pci/msix.h"
34
#include "hw/pci/pci.h"
35
#include "qemu-common.h"
36
#include "qemu/error-report.h"
37
#include "qemu/event_notifier.h"
38
#include "qemu/queue.h"
39
#include "qemu/range.h"
40
#include "sysemu/kvm.h"
41
#include "sysemu/sysemu.h"
42

    
43
/* #define DEBUG_VFIO */
44
#ifdef DEBUG_VFIO
45
#define DPRINTF(fmt, ...) \
46
    do { fprintf(stderr, "vfio: " fmt, ## __VA_ARGS__); } while (0)
47
#else
48
#define DPRINTF(fmt, ...) \
49
    do { } while (0)
50
#endif
51

    
52
/* Extra debugging, trap acceleration paths for more logging */
53
#define VFIO_ALLOW_MMAP 1
54
#define VFIO_ALLOW_KVM_INTX 1
55

    
56
struct VFIODevice;
57

    
58
typedef struct VFIOQuirk {
59
    MemoryRegion mem;
60
    struct VFIODevice *vdev;
61
    QLIST_ENTRY(VFIOQuirk) next;
62
    struct {
63
        uint32_t base_offset:TARGET_PAGE_BITS;
64
        uint32_t address_offset:TARGET_PAGE_BITS;
65
        uint32_t address_size:3;
66
        uint32_t bar:3;
67

    
68
        uint32_t address_match;
69
        uint32_t address_mask;
70

    
71
        uint32_t address_val:TARGET_PAGE_BITS;
72
        uint32_t data_offset:TARGET_PAGE_BITS;
73
        uint32_t data_size:3;
74

    
75
        uint8_t flags;
76
        uint8_t read_flags;
77
        uint8_t write_flags;
78
    } data;
79
} VFIOQuirk;
80

    
81
typedef struct VFIOBAR {
82
    off_t fd_offset; /* offset of BAR within device fd */
83
    int fd; /* device fd, allows us to pass VFIOBAR as opaque data */
84
    MemoryRegion mem; /* slow, read/write access */
85
    MemoryRegion mmap_mem; /* direct mapped access */
86
    void *mmap;
87
    size_t size;
88
    uint32_t flags; /* VFIO region flags (rd/wr/mmap) */
89
    uint8_t nr; /* cache the BAR number for debug */
90
    bool ioport;
91
    bool mem64;
92
    QLIST_HEAD(, VFIOQuirk) quirks;
93
} VFIOBAR;
94

    
95
typedef struct VFIOVGARegion {
96
    MemoryRegion mem;
97
    off_t offset;
98
    int nr;
99
    QLIST_HEAD(, VFIOQuirk) quirks;
100
} VFIOVGARegion;
101

    
102
typedef struct VFIOVGA {
103
    off_t fd_offset;
104
    int fd;
105
    VFIOVGARegion region[QEMU_PCI_VGA_NUM_REGIONS];
106
} VFIOVGA;
107

    
108
typedef struct VFIOINTx {
109
    bool pending; /* interrupt pending */
110
    bool kvm_accel; /* set when QEMU bypass through KVM enabled */
111
    uint8_t pin; /* which pin to pull for qemu_set_irq */
112
    EventNotifier interrupt; /* eventfd triggered on interrupt */
113
    EventNotifier unmask; /* eventfd for unmask on QEMU bypass */
114
    PCIINTxRoute route; /* routing info for QEMU bypass */
115
    uint32_t mmap_timeout; /* delay to re-enable mmaps after interrupt */
116
    QEMUTimer *mmap_timer; /* enable mmaps after periods w/o interrupts */
117
} VFIOINTx;
118

    
119
typedef struct VFIOMSIVector {
120
    EventNotifier interrupt; /* eventfd triggered on interrupt */
121
    struct VFIODevice *vdev; /* back pointer to device */
122
    MSIMessage msg; /* cache the MSI message so we know when it changes */
123
    int virq; /* KVM irqchip route for QEMU bypass */
124
    bool use;
125
} VFIOMSIVector;
126

    
127
enum {
128
    VFIO_INT_NONE = 0,
129
    VFIO_INT_INTx = 1,
130
    VFIO_INT_MSI  = 2,
131
    VFIO_INT_MSIX = 3,
132
};
133

    
134
struct VFIOGroup;
135

    
136
typedef struct VFIOContainer {
137
    int fd; /* /dev/vfio/vfio, empowered by the attached groups */
138
    struct {
139
        /* enable abstraction to support various iommu backends */
140
        union {
141
            MemoryListener listener; /* Used by type1 iommu */
142
        };
143
        void (*release)(struct VFIOContainer *);
144
    } iommu_data;
145
    QLIST_HEAD(, VFIOGroup) group_list;
146
    QLIST_ENTRY(VFIOContainer) next;
147
} VFIOContainer;
148

    
149
/* Cache of MSI-X setup plus extra mmap and memory region for split BAR map */
150
typedef struct VFIOMSIXInfo {
151
    uint8_t table_bar;
152
    uint8_t pba_bar;
153
    uint16_t entries;
154
    uint32_t table_offset;
155
    uint32_t pba_offset;
156
    MemoryRegion mmap_mem;
157
    void *mmap;
158
} VFIOMSIXInfo;
159

    
160
typedef struct VFIODevice {
161
    PCIDevice pdev;
162
    int fd;
163
    VFIOINTx intx;
164
    unsigned int config_size;
165
    uint8_t *emulated_config_bits; /* QEMU emulated bits, little-endian */
166
    off_t config_offset; /* Offset of config space region within device fd */
167
    unsigned int rom_size;
168
    off_t rom_offset; /* Offset of ROM region within device fd */
169
    void *rom;
170
    int msi_cap_size;
171
    VFIOMSIVector *msi_vectors;
172
    VFIOMSIXInfo *msix;
173
    int nr_vectors; /* Number of MSI/MSIX vectors currently in use */
174
    int interrupt; /* Current interrupt type */
175
    VFIOBAR bars[PCI_NUM_REGIONS - 1]; /* No ROM */
176
    VFIOVGA vga; /* 0xa0000, 0x3b0, 0x3c0 */
177
    PCIHostDeviceAddress host;
178
    QLIST_ENTRY(VFIODevice) next;
179
    struct VFIOGroup *group;
180
    EventNotifier err_notifier;
181
    uint32_t features;
182
#define VFIO_FEATURE_ENABLE_VGA_BIT 0
183
#define VFIO_FEATURE_ENABLE_VGA (1 << VFIO_FEATURE_ENABLE_VGA_BIT)
184
    int32_t bootindex;
185
    uint8_t pm_cap;
186
    bool reset_works;
187
    bool has_vga;
188
    bool pci_aer;
189
    bool has_flr;
190
    bool has_pm_reset;
191
    bool needs_reset;
192
} VFIODevice;
193

    
194
typedef struct VFIOGroup {
195
    int fd;
196
    int groupid;
197
    VFIOContainer *container;
198
    QLIST_HEAD(, VFIODevice) device_list;
199
    QLIST_ENTRY(VFIOGroup) next;
200
    QLIST_ENTRY(VFIOGroup) container_next;
201
} VFIOGroup;
202

    
203
#define MSIX_CAP_LENGTH 12
204

    
205
static QLIST_HEAD(, VFIOContainer)
206
    container_list = QLIST_HEAD_INITIALIZER(container_list);
207

    
208
static QLIST_HEAD(, VFIOGroup)
209
    group_list = QLIST_HEAD_INITIALIZER(group_list);
210

    
211
static void vfio_disable_interrupts(VFIODevice *vdev);
212
static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len);
213
static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
214
                                  uint32_t val, int len);
215
static void vfio_mmap_set_enabled(VFIODevice *vdev, bool enabled);
216

    
217
/*
218
 * Common VFIO interrupt disable
219
 */
220
static void vfio_disable_irqindex(VFIODevice *vdev, int index)
221
{
222
    struct vfio_irq_set irq_set = {
223
        .argsz = sizeof(irq_set),
224
        .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_TRIGGER,
225
        .index = index,
226
        .start = 0,
227
        .count = 0,
228
    };
229

    
230
    ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
231
}
232

    
233
/*
234
 * INTx
235
 */
236
static void vfio_unmask_intx(VFIODevice *vdev)
237
{
238
    struct vfio_irq_set irq_set = {
239
        .argsz = sizeof(irq_set),
240
        .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
241
        .index = VFIO_PCI_INTX_IRQ_INDEX,
242
        .start = 0,
243
        .count = 1,
244
    };
245

    
246
    ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
247
}
248

    
249
#ifdef CONFIG_KVM /* Unused outside of CONFIG_KVM code */
250
static void vfio_mask_intx(VFIODevice *vdev)
251
{
252
    struct vfio_irq_set irq_set = {
253
        .argsz = sizeof(irq_set),
254
        .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_MASK,
255
        .index = VFIO_PCI_INTX_IRQ_INDEX,
256
        .start = 0,
257
        .count = 1,
258
    };
259

    
260
    ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set);
261
}
262
#endif
263

    
264
/*
265
 * Disabling BAR mmaping can be slow, but toggling it around INTx can
266
 * also be a huge overhead.  We try to get the best of both worlds by
267
 * waiting until an interrupt to disable mmaps (subsequent transitions
268
 * to the same state are effectively no overhead).  If the interrupt has
269
 * been serviced and the time gap is long enough, we re-enable mmaps for
270
 * performance.  This works well for things like graphics cards, which
271
 * may not use their interrupt at all and are penalized to an unusable
272
 * level by read/write BAR traps.  Other devices, like NICs, have more
273
 * regular interrupts and see much better latency by staying in non-mmap
274
 * mode.  We therefore set the default mmap_timeout such that a ping
275
 * is just enough to keep the mmap disabled.  Users can experiment with
276
 * other options with the x-intx-mmap-timeout-ms parameter (a value of
277
 * zero disables the timer).
278
 */
279
static void vfio_intx_mmap_enable(void *opaque)
280
{
281
    VFIODevice *vdev = opaque;
282

    
283
    if (vdev->intx.pending) {
284
        timer_mod(vdev->intx.mmap_timer,
285
                       qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
286
        return;
287
    }
288

    
289
    vfio_mmap_set_enabled(vdev, true);
290
}
291

    
292
static void vfio_intx_interrupt(void *opaque)
293
{
294
    VFIODevice *vdev = opaque;
295

    
296
    if (!event_notifier_test_and_clear(&vdev->intx.interrupt)) {
297
        return;
298
    }
299

    
300
    DPRINTF("%s(%04x:%02x:%02x.%x) Pin %c\n", __func__, vdev->host.domain,
301
            vdev->host.bus, vdev->host.slot, vdev->host.function,
302
            'A' + vdev->intx.pin);
303

    
304
    vdev->intx.pending = true;
305
    qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 1);
306
    vfio_mmap_set_enabled(vdev, false);
307
    if (vdev->intx.mmap_timeout) {
308
        timer_mod(vdev->intx.mmap_timer,
309
                       qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + vdev->intx.mmap_timeout);
310
    }
311
}
312

    
313
static void vfio_eoi(VFIODevice *vdev)
314
{
315
    if (!vdev->intx.pending) {
316
        return;
317
    }
318

    
319
    DPRINTF("%s(%04x:%02x:%02x.%x) EOI\n", __func__, vdev->host.domain,
320
            vdev->host.bus, vdev->host.slot, vdev->host.function);
321

    
322
    vdev->intx.pending = false;
323
    qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
324
    vfio_unmask_intx(vdev);
325
}
326

    
327
static void vfio_enable_intx_kvm(VFIODevice *vdev)
328
{
329
#ifdef CONFIG_KVM
330
    struct kvm_irqfd irqfd = {
331
        .fd = event_notifier_get_fd(&vdev->intx.interrupt),
332
        .gsi = vdev->intx.route.irq,
333
        .flags = KVM_IRQFD_FLAG_RESAMPLE,
334
    };
335
    struct vfio_irq_set *irq_set;
336
    int ret, argsz;
337
    int32_t *pfd;
338

    
339
    if (!VFIO_ALLOW_KVM_INTX || !kvm_irqfds_enabled() ||
340
        vdev->intx.route.mode != PCI_INTX_ENABLED ||
341
        !kvm_check_extension(kvm_state, KVM_CAP_IRQFD_RESAMPLE)) {
342
        return;
343
    }
344

    
345
    /* Get to a known interrupt state */
346
    qemu_set_fd_handler(irqfd.fd, NULL, NULL, vdev);
347
    vfio_mask_intx(vdev);
348
    vdev->intx.pending = false;
349
    qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
350

    
351
    /* Get an eventfd for resample/unmask */
352
    if (event_notifier_init(&vdev->intx.unmask, 0)) {
353
        error_report("vfio: Error: event_notifier_init failed eoi");
354
        goto fail;
355
    }
356

    
357
    /* KVM triggers it, VFIO listens for it */
358
    irqfd.resamplefd = event_notifier_get_fd(&vdev->intx.unmask);
359

    
360
    if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
361
        error_report("vfio: Error: Failed to setup resample irqfd: %m");
362
        goto fail_irqfd;
363
    }
364

    
365
    argsz = sizeof(*irq_set) + sizeof(*pfd);
366

    
367
    irq_set = g_malloc0(argsz);
368
    irq_set->argsz = argsz;
369
    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK;
370
    irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
371
    irq_set->start = 0;
372
    irq_set->count = 1;
373
    pfd = (int32_t *)&irq_set->data;
374

    
375
    *pfd = irqfd.resamplefd;
376

    
377
    ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
378
    g_free(irq_set);
379
    if (ret) {
380
        error_report("vfio: Error: Failed to setup INTx unmask fd: %m");
381
        goto fail_vfio;
382
    }
383

    
384
    /* Let'em rip */
385
    vfio_unmask_intx(vdev);
386

    
387
    vdev->intx.kvm_accel = true;
388

    
389
    DPRINTF("%s(%04x:%02x:%02x.%x) KVM INTx accel enabled\n",
390
            __func__, vdev->host.domain, vdev->host.bus,
391
            vdev->host.slot, vdev->host.function);
392

    
393
    return;
394

    
395
fail_vfio:
396
    irqfd.flags = KVM_IRQFD_FLAG_DEASSIGN;
397
    kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd);
398
fail_irqfd:
399
    event_notifier_cleanup(&vdev->intx.unmask);
400
fail:
401
    qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
402
    vfio_unmask_intx(vdev);
403
#endif
404
}
405

    
406
static void vfio_disable_intx_kvm(VFIODevice *vdev)
407
{
408
#ifdef CONFIG_KVM
409
    struct kvm_irqfd irqfd = {
410
        .fd = event_notifier_get_fd(&vdev->intx.interrupt),
411
        .gsi = vdev->intx.route.irq,
412
        .flags = KVM_IRQFD_FLAG_DEASSIGN,
413
    };
414

    
415
    if (!vdev->intx.kvm_accel) {
416
        return;
417
    }
418

    
419
    /*
420
     * Get to a known state, hardware masked, QEMU ready to accept new
421
     * interrupts, QEMU IRQ de-asserted.
422
     */
423
    vfio_mask_intx(vdev);
424
    vdev->intx.pending = false;
425
    qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
426

    
427
    /* Tell KVM to stop listening for an INTx irqfd */
428
    if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {
429
        error_report("vfio: Error: Failed to disable INTx irqfd: %m");
430
    }
431

    
432
    /* We only need to close the eventfd for VFIO to cleanup the kernel side */
433
    event_notifier_cleanup(&vdev->intx.unmask);
434

    
435
    /* QEMU starts listening for interrupt events. */
436
    qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);
437

    
438
    vdev->intx.kvm_accel = false;
439

    
440
    /* If we've missed an event, let it re-fire through QEMU */
441
    vfio_unmask_intx(vdev);
442

    
443
    DPRINTF("%s(%04x:%02x:%02x.%x) KVM INTx accel disabled\n",
444
            __func__, vdev->host.domain, vdev->host.bus,
445
            vdev->host.slot, vdev->host.function);
446
#endif
447
}
448

    
449
static void vfio_update_irq(PCIDevice *pdev)
450
{
451
    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
452
    PCIINTxRoute route;
453

    
454
    if (vdev->interrupt != VFIO_INT_INTx) {
455
        return;
456
    }
457

    
458
    route = pci_device_route_intx_to_irq(&vdev->pdev, vdev->intx.pin);
459

    
460
    if (!pci_intx_route_changed(&vdev->intx.route, &route)) {
461
        return; /* Nothing changed */
462
    }
463

    
464
    DPRINTF("%s(%04x:%02x:%02x.%x) IRQ moved %d -> %d\n", __func__,
465
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
466
            vdev->host.function, vdev->intx.route.irq, route.irq);
467

    
468
    vfio_disable_intx_kvm(vdev);
469

    
470
    vdev->intx.route = route;
471

    
472
    if (route.mode != PCI_INTX_ENABLED) {
473
        return;
474
    }
475

    
476
    vfio_enable_intx_kvm(vdev);
477

    
478
    /* Re-enable the interrupt in cased we missed an EOI */
479
    vfio_eoi(vdev);
480
}
481

    
482
static int vfio_enable_intx(VFIODevice *vdev)
483
{
484
    uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);
485
    int ret, argsz;
486
    struct vfio_irq_set *irq_set;
487
    int32_t *pfd;
488

    
489
    if (!pin) {
490
        return 0;
491
    }
492

    
493
    vfio_disable_interrupts(vdev);
494

    
495
    vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */
496

    
497
#ifdef CONFIG_KVM
498
    /*
499
     * Only conditional to avoid generating error messages on platforms
500
     * where we won't actually use the result anyway.
501
     */
502
    if (kvm_irqfds_enabled() &&
503
        kvm_check_extension(kvm_state, KVM_CAP_IRQFD_RESAMPLE)) {
504
        vdev->intx.route = pci_device_route_intx_to_irq(&vdev->pdev,
505
                                                        vdev->intx.pin);
506
    }
507
#endif
508

    
509
    ret = event_notifier_init(&vdev->intx.interrupt, 0);
510
    if (ret) {
511
        error_report("vfio: Error: event_notifier_init failed");
512
        return ret;
513
    }
514

    
515
    argsz = sizeof(*irq_set) + sizeof(*pfd);
516

    
517
    irq_set = g_malloc0(argsz);
518
    irq_set->argsz = argsz;
519
    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
520
    irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
521
    irq_set->start = 0;
522
    irq_set->count = 1;
523
    pfd = (int32_t *)&irq_set->data;
524

    
525
    *pfd = event_notifier_get_fd(&vdev->intx.interrupt);
526
    qemu_set_fd_handler(*pfd, vfio_intx_interrupt, NULL, vdev);
527

    
528
    ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
529
    g_free(irq_set);
530
    if (ret) {
531
        error_report("vfio: Error: Failed to setup INTx fd: %m");
532
        qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
533
        event_notifier_cleanup(&vdev->intx.interrupt);
534
        return -errno;
535
    }
536

    
537
    vfio_enable_intx_kvm(vdev);
538

    
539
    vdev->interrupt = VFIO_INT_INTx;
540

    
541
    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
542
            vdev->host.bus, vdev->host.slot, vdev->host.function);
543

    
544
    return 0;
545
}
546

    
547
static void vfio_disable_intx(VFIODevice *vdev)
548
{
549
    int fd;
550

    
551
    timer_del(vdev->intx.mmap_timer);
552
    vfio_disable_intx_kvm(vdev);
553
    vfio_disable_irqindex(vdev, VFIO_PCI_INTX_IRQ_INDEX);
554
    vdev->intx.pending = false;
555
    qemu_set_irq(vdev->pdev.irq[vdev->intx.pin], 0);
556
    vfio_mmap_set_enabled(vdev, true);
557

    
558
    fd = event_notifier_get_fd(&vdev->intx.interrupt);
559
    qemu_set_fd_handler(fd, NULL, NULL, vdev);
560
    event_notifier_cleanup(&vdev->intx.interrupt);
561

    
562
    vdev->interrupt = VFIO_INT_NONE;
563

    
564
    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
565
            vdev->host.bus, vdev->host.slot, vdev->host.function);
566
}
567

    
568
/*
569
 * MSI/X
570
 */
571
static void vfio_msi_interrupt(void *opaque)
572
{
573
    VFIOMSIVector *vector = opaque;
574
    VFIODevice *vdev = vector->vdev;
575
    int nr = vector - vdev->msi_vectors;
576

    
577
    if (!event_notifier_test_and_clear(&vector->interrupt)) {
578
        return;
579
    }
580

    
581
    DPRINTF("%s(%04x:%02x:%02x.%x) vector %d\n", __func__,
582
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
583
            vdev->host.function, nr);
584

    
585
    if (vdev->interrupt == VFIO_INT_MSIX) {
586
        msix_notify(&vdev->pdev, nr);
587
    } else if (vdev->interrupt == VFIO_INT_MSI) {
588
        msi_notify(&vdev->pdev, nr);
589
    } else {
590
        error_report("vfio: MSI interrupt receieved, but not enabled?");
591
    }
592
}
593

    
594
static int vfio_enable_vectors(VFIODevice *vdev, bool msix)
595
{
596
    struct vfio_irq_set *irq_set;
597
    int ret = 0, i, argsz;
598
    int32_t *fds;
599

    
600
    argsz = sizeof(*irq_set) + (vdev->nr_vectors * sizeof(*fds));
601

    
602
    irq_set = g_malloc0(argsz);
603
    irq_set->argsz = argsz;
604
    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
605
    irq_set->index = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX;
606
    irq_set->start = 0;
607
    irq_set->count = vdev->nr_vectors;
608
    fds = (int32_t *)&irq_set->data;
609

    
610
    for (i = 0; i < vdev->nr_vectors; i++) {
611
        if (!vdev->msi_vectors[i].use) {
612
            fds[i] = -1;
613
            continue;
614
        }
615

    
616
        fds[i] = event_notifier_get_fd(&vdev->msi_vectors[i].interrupt);
617
    }
618

    
619
    ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
620

    
621
    g_free(irq_set);
622

    
623
    return ret;
624
}
625

    
626
static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,
627
                                   MSIMessage *msg, IOHandler *handler)
628
{
629
    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
630
    VFIOMSIVector *vector;
631
    int ret;
632

    
633
    DPRINTF("%s(%04x:%02x:%02x.%x) vector %d used\n", __func__,
634
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
635
            vdev->host.function, nr);
636

    
637
    vector = &vdev->msi_vectors[nr];
638
    vector->vdev = vdev;
639
    vector->use = true;
640

    
641
    msix_vector_use(pdev, nr);
642

    
643
    if (event_notifier_init(&vector->interrupt, 0)) {
644
        error_report("vfio: Error: event_notifier_init failed");
645
    }
646

    
647
    /*
648
     * Attempt to enable route through KVM irqchip,
649
     * default to userspace handling if unavailable.
650
     */
651
    vector->virq = msg ? kvm_irqchip_add_msi_route(kvm_state, *msg) : -1;
652
    if (vector->virq < 0 ||
653
        kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
654
                                       NULL, vector->virq) < 0) {
655
        if (vector->virq >= 0) {
656
            kvm_irqchip_release_virq(kvm_state, vector->virq);
657
            vector->virq = -1;
658
        }
659
        qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
660
                            handler, NULL, vector);
661
    }
662

    
663
    /*
664
     * We don't want to have the host allocate all possible MSI vectors
665
     * for a device if they're not in use, so we shutdown and incrementally
666
     * increase them as needed.
667
     */
668
    if (vdev->nr_vectors < nr + 1) {
669
        vfio_disable_irqindex(vdev, VFIO_PCI_MSIX_IRQ_INDEX);
670
        vdev->nr_vectors = nr + 1;
671
        ret = vfio_enable_vectors(vdev, true);
672
        if (ret) {
673
            error_report("vfio: failed to enable vectors, %d", ret);
674
        }
675
    } else {
676
        int argsz;
677
        struct vfio_irq_set *irq_set;
678
        int32_t *pfd;
679

    
680
        argsz = sizeof(*irq_set) + sizeof(*pfd);
681

    
682
        irq_set = g_malloc0(argsz);
683
        irq_set->argsz = argsz;
684
        irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
685
                         VFIO_IRQ_SET_ACTION_TRIGGER;
686
        irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
687
        irq_set->start = nr;
688
        irq_set->count = 1;
689
        pfd = (int32_t *)&irq_set->data;
690

    
691
        *pfd = event_notifier_get_fd(&vector->interrupt);
692

    
693
        ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
694
        g_free(irq_set);
695
        if (ret) {
696
            error_report("vfio: failed to modify vector, %d", ret);
697
        }
698
    }
699

    
700
    return 0;
701
}
702

    
703
static int vfio_msix_vector_use(PCIDevice *pdev,
704
                                unsigned int nr, MSIMessage msg)
705
{
706
    return vfio_msix_vector_do_use(pdev, nr, &msg, vfio_msi_interrupt);
707
}
708

    
709
static void vfio_msix_vector_release(PCIDevice *pdev, unsigned int nr)
710
{
711
    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
712
    VFIOMSIVector *vector = &vdev->msi_vectors[nr];
713
    int argsz;
714
    struct vfio_irq_set *irq_set;
715
    int32_t *pfd;
716

    
717
    DPRINTF("%s(%04x:%02x:%02x.%x) vector %d released\n", __func__,
718
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
719
            vdev->host.function, nr);
720

    
721
    /*
722
     * XXX What's the right thing to do here?  This turns off the interrupt
723
     * completely, but do we really just want to switch the interrupt to
724
     * bouncing through userspace and let msix.c drop it?  Not sure.
725
     */
726
    msix_vector_unuse(pdev, nr);
727

    
728
    argsz = sizeof(*irq_set) + sizeof(*pfd);
729

    
730
    irq_set = g_malloc0(argsz);
731
    irq_set->argsz = argsz;
732
    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
733
                     VFIO_IRQ_SET_ACTION_TRIGGER;
734
    irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;
735
    irq_set->start = nr;
736
    irq_set->count = 1;
737
    pfd = (int32_t *)&irq_set->data;
738

    
739
    *pfd = -1;
740

    
741
    ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
742

    
743
    g_free(irq_set);
744

    
745
    if (vector->virq < 0) {
746
        qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
747
                            NULL, NULL, NULL);
748
    } else {
749
        kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
750
                                          vector->virq);
751
        kvm_irqchip_release_virq(kvm_state, vector->virq);
752
        vector->virq = -1;
753
    }
754

    
755
    event_notifier_cleanup(&vector->interrupt);
756
    vector->use = false;
757
}
758

    
759
static void vfio_enable_msix(VFIODevice *vdev)
760
{
761
    vfio_disable_interrupts(vdev);
762

    
763
    vdev->msi_vectors = g_malloc0(vdev->msix->entries * sizeof(VFIOMSIVector));
764

    
765
    vdev->interrupt = VFIO_INT_MSIX;
766

    
767
    /*
768
     * Some communication channels between VF & PF or PF & fw rely on the
769
     * physical state of the device and expect that enabling MSI-X from the
770
     * guest enables the same on the host.  When our guest is Linux, the
771
     * guest driver call to pci_enable_msix() sets the enabling bit in the
772
     * MSI-X capability, but leaves the vector table masked.  We therefore
773
     * can't rely on a vector_use callback (from request_irq() in the guest)
774
     * to switch the physical device into MSI-X mode because that may come a
775
     * long time after pci_enable_msix().  This code enables vector 0 with
776
     * triggering to userspace, then immediately release the vector, leaving
777
     * the physical device with no vectors enabled, but MSI-X enabled, just
778
     * like the guest view.
779
     */
780
    vfio_msix_vector_do_use(&vdev->pdev, 0, NULL, NULL);
781
    vfio_msix_vector_release(&vdev->pdev, 0);
782

    
783
    if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,
784
                                  vfio_msix_vector_release, NULL)) {
785
        error_report("vfio: msix_set_vector_notifiers failed");
786
    }
787

    
788
    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
789
            vdev->host.bus, vdev->host.slot, vdev->host.function);
790
}
791

    
792
static void vfio_enable_msi(VFIODevice *vdev)
793
{
794
    int ret, i;
795

    
796
    vfio_disable_interrupts(vdev);
797

    
798
    vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);
799
retry:
800
    vdev->msi_vectors = g_malloc0(vdev->nr_vectors * sizeof(VFIOMSIVector));
801

    
802
    for (i = 0; i < vdev->nr_vectors; i++) {
803
        VFIOMSIVector *vector = &vdev->msi_vectors[i];
804

    
805
        vector->vdev = vdev;
806
        vector->use = true;
807

    
808
        if (event_notifier_init(&vector->interrupt, 0)) {
809
            error_report("vfio: Error: event_notifier_init failed");
810
        }
811

    
812
        vector->msg = msi_get_message(&vdev->pdev, i);
813

    
814
        /*
815
         * Attempt to enable route through KVM irqchip,
816
         * default to userspace handling if unavailable.
817
         */
818
        vector->virq = kvm_irqchip_add_msi_route(kvm_state, vector->msg);
819
        if (vector->virq < 0 ||
820
            kvm_irqchip_add_irqfd_notifier(kvm_state, &vector->interrupt,
821
                                           NULL, vector->virq) < 0) {
822
            qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
823
                                vfio_msi_interrupt, NULL, vector);
824
        }
825
    }
826

    
827
    ret = vfio_enable_vectors(vdev, false);
828
    if (ret) {
829
        if (ret < 0) {
830
            error_report("vfio: Error: Failed to setup MSI fds: %m");
831
        } else if (ret != vdev->nr_vectors) {
832
            error_report("vfio: Error: Failed to enable %d "
833
                         "MSI vectors, retry with %d", vdev->nr_vectors, ret);
834
        }
835

    
836
        for (i = 0; i < vdev->nr_vectors; i++) {
837
            VFIOMSIVector *vector = &vdev->msi_vectors[i];
838
            if (vector->virq >= 0) {
839
                kvm_irqchip_remove_irqfd_notifier(kvm_state, &vector->interrupt,
840
                                                  vector->virq);
841
                kvm_irqchip_release_virq(kvm_state, vector->virq);
842
                vector->virq = -1;
843
            } else {
844
                qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
845
                                    NULL, NULL, NULL);
846
            }
847
            event_notifier_cleanup(&vector->interrupt);
848
        }
849

    
850
        g_free(vdev->msi_vectors);
851

    
852
        if (ret > 0 && ret != vdev->nr_vectors) {
853
            vdev->nr_vectors = ret;
854
            goto retry;
855
        }
856
        vdev->nr_vectors = 0;
857

    
858
        return;
859
    }
860

    
861
    vdev->interrupt = VFIO_INT_MSI;
862

    
863
    DPRINTF("%s(%04x:%02x:%02x.%x) Enabled %d MSI vectors\n", __func__,
864
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
865
            vdev->host.function, vdev->nr_vectors);
866
}
867

    
868
static void vfio_disable_msi_common(VFIODevice *vdev)
869
{
870
    g_free(vdev->msi_vectors);
871
    vdev->msi_vectors = NULL;
872
    vdev->nr_vectors = 0;
873
    vdev->interrupt = VFIO_INT_NONE;
874

    
875
    vfio_enable_intx(vdev);
876
}
877

    
878
static void vfio_disable_msix(VFIODevice *vdev)
879
{
880
    msix_unset_vector_notifiers(&vdev->pdev);
881

    
882
    if (vdev->nr_vectors) {
883
        vfio_disable_irqindex(vdev, VFIO_PCI_MSIX_IRQ_INDEX);
884
    }
885

    
886
    vfio_disable_msi_common(vdev);
887

    
888
    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
889
            vdev->host.bus, vdev->host.slot, vdev->host.function);
890
}
891

    
892
static void vfio_disable_msi(VFIODevice *vdev)
893
{
894
    int i;
895

    
896
    vfio_disable_irqindex(vdev, VFIO_PCI_MSI_IRQ_INDEX);
897

    
898
    for (i = 0; i < vdev->nr_vectors; i++) {
899
        VFIOMSIVector *vector = &vdev->msi_vectors[i];
900

    
901
        if (!vector->use) {
902
            continue;
903
        }
904

    
905
        if (vector->virq >= 0) {
906
            kvm_irqchip_remove_irqfd_notifier(kvm_state,
907
                                              &vector->interrupt, vector->virq);
908
            kvm_irqchip_release_virq(kvm_state, vector->virq);
909
            vector->virq = -1;
910
        } else {
911
            qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),
912
                                NULL, NULL, NULL);
913
        }
914

    
915
        event_notifier_cleanup(&vector->interrupt);
916
    }
917

    
918
    vfio_disable_msi_common(vdev);
919

    
920
    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
921
            vdev->host.bus, vdev->host.slot, vdev->host.function);
922
}
923

    
924
static void vfio_update_msi(VFIODevice *vdev)
925
{
926
    int i;
927

    
928
    for (i = 0; i < vdev->nr_vectors; i++) {
929
        VFIOMSIVector *vector = &vdev->msi_vectors[i];
930
        MSIMessage msg;
931

    
932
        if (!vector->use || vector->virq < 0) {
933
            continue;
934
        }
935

    
936
        msg = msi_get_message(&vdev->pdev, i);
937

    
938
        if (msg.address != vector->msg.address ||
939
            msg.data != vector->msg.data) {
940

    
941
            DPRINTF("%s(%04x:%02x:%02x.%x) MSI vector %d changed\n",
942
                    __func__, vdev->host.domain, vdev->host.bus,
943
                    vdev->host.slot, vdev->host.function, i);
944

    
945
            kvm_irqchip_update_msi_route(kvm_state, vector->virq, msg);
946
            vector->msg = msg;
947
        }
948
    }
949
}
950

    
951
/*
952
 * IO Port/MMIO - Beware of the endians, VFIO is always little endian
953
 */
954
static void vfio_bar_write(void *opaque, hwaddr addr,
955
                           uint64_t data, unsigned size)
956
{
957
    VFIOBAR *bar = opaque;
958
    union {
959
        uint8_t byte;
960
        uint16_t word;
961
        uint32_t dword;
962
        uint64_t qword;
963
    } buf;
964

    
965
    switch (size) {
966
    case 1:
967
        buf.byte = data;
968
        break;
969
    case 2:
970
        buf.word = cpu_to_le16(data);
971
        break;
972
    case 4:
973
        buf.dword = cpu_to_le32(data);
974
        break;
975
    default:
976
        hw_error("vfio: unsupported write size, %d bytes\n", size);
977
        break;
978
    }
979

    
980
    if (pwrite(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
981
        error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
982
                     __func__, addr, data, size);
983
    }
984

    
985
#ifdef DEBUG_VFIO
986
    {
987
        VFIODevice *vdev = container_of(bar, VFIODevice, bars[bar->nr]);
988

    
989
        DPRINTF("%s(%04x:%02x:%02x.%x:BAR%d+0x%"HWADDR_PRIx", 0x%"PRIx64
990
                ", %d)\n", __func__, vdev->host.domain, vdev->host.bus,
991
                vdev->host.slot, vdev->host.function, bar->nr, addr,
992
                data, size);
993
    }
994
#endif
995

    
996
    /*
997
     * A read or write to a BAR always signals an INTx EOI.  This will
998
     * do nothing if not pending (including not in INTx mode).  We assume
999
     * that a BAR access is in response to an interrupt and that BAR
1000
     * accesses will service the interrupt.  Unfortunately, we don't know
1001
     * which access will service the interrupt, so we're potentially
1002
     * getting quite a few host interrupts per guest interrupt.
1003
     */
1004
    vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));
1005
}
1006

    
1007
static uint64_t vfio_bar_read(void *opaque,
1008
                              hwaddr addr, unsigned size)
1009
{
1010
    VFIOBAR *bar = opaque;
1011
    union {
1012
        uint8_t byte;
1013
        uint16_t word;
1014
        uint32_t dword;
1015
        uint64_t qword;
1016
    } buf;
1017
    uint64_t data = 0;
1018

    
1019
    if (pread(bar->fd, &buf, size, bar->fd_offset + addr) != size) {
1020
        error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
1021
                     __func__, addr, size);
1022
        return (uint64_t)-1;
1023
    }
1024

    
1025
    switch (size) {
1026
    case 1:
1027
        data = buf.byte;
1028
        break;
1029
    case 2:
1030
        data = le16_to_cpu(buf.word);
1031
        break;
1032
    case 4:
1033
        data = le32_to_cpu(buf.dword);
1034
        break;
1035
    default:
1036
        hw_error("vfio: unsupported read size, %d bytes\n", size);
1037
        break;
1038
    }
1039

    
1040
#ifdef DEBUG_VFIO
1041
    {
1042
        VFIODevice *vdev = container_of(bar, VFIODevice, bars[bar->nr]);
1043

    
1044
        DPRINTF("%s(%04x:%02x:%02x.%x:BAR%d+0x%"HWADDR_PRIx
1045
                ", %d) = 0x%"PRIx64"\n", __func__, vdev->host.domain,
1046
                vdev->host.bus, vdev->host.slot, vdev->host.function,
1047
                bar->nr, addr, size, data);
1048
    }
1049
#endif
1050

    
1051
    /* Same as write above */
1052
    vfio_eoi(container_of(bar, VFIODevice, bars[bar->nr]));
1053

    
1054
    return data;
1055
}
1056

    
1057
static const MemoryRegionOps vfio_bar_ops = {
1058
    .read = vfio_bar_read,
1059
    .write = vfio_bar_write,
1060
    .endianness = DEVICE_LITTLE_ENDIAN,
1061
};
1062

    
1063
static void vfio_pci_load_rom(VFIODevice *vdev)
1064
{
1065
    struct vfio_region_info reg_info = {
1066
        .argsz = sizeof(reg_info),
1067
        .index = VFIO_PCI_ROM_REGION_INDEX
1068
    };
1069
    uint64_t size;
1070
    off_t off = 0;
1071
    size_t bytes;
1072

    
1073
    if (ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info)) {
1074
        error_report("vfio: Error getting ROM info: %m");
1075
        return;
1076
    }
1077

    
1078
    DPRINTF("Device %04x:%02x:%02x.%x ROM:\n", vdev->host.domain,
1079
            vdev->host.bus, vdev->host.slot, vdev->host.function);
1080
    DPRINTF("  size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
1081
            (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
1082
            (unsigned long)reg_info.flags);
1083

    
1084
    vdev->rom_size = size = reg_info.size;
1085
    vdev->rom_offset = reg_info.offset;
1086

    
1087
    if (!vdev->rom_size) {
1088
        return;
1089
    }
1090

    
1091
    vdev->rom = g_malloc(size);
1092
    memset(vdev->rom, 0xff, size);
1093

    
1094
    while (size) {
1095
        bytes = pread(vdev->fd, vdev->rom + off, size, vdev->rom_offset + off);
1096
        if (bytes == 0) {
1097
            break;
1098
        } else if (bytes > 0) {
1099
            off += bytes;
1100
            size -= bytes;
1101
        } else {
1102
            if (errno == EINTR || errno == EAGAIN) {
1103
                continue;
1104
            }
1105
            error_report("vfio: Error reading device ROM: %m");
1106
            break;
1107
        }
1108
    }
1109
}
1110

    
1111
static uint64_t vfio_rom_read(void *opaque, hwaddr addr, unsigned size)
1112
{
1113
    VFIODevice *vdev = opaque;
1114
    uint64_t val = ((uint64_t)1 << (size * 8)) - 1;
1115

    
1116
    /* Load the ROM lazily when the guest tries to read it */
1117
    if (unlikely(!vdev->rom)) {
1118
        vfio_pci_load_rom(vdev);
1119
    }
1120

    
1121
    memcpy(&val, vdev->rom + addr,
1122
           (addr < vdev->rom_size) ? MIN(size, vdev->rom_size - addr) : 0);
1123

    
1124
    DPRINTF("%s(%04x:%02x:%02x.%x, 0x%"HWADDR_PRIx", 0x%x) = 0x%"PRIx64"\n",
1125
            __func__, vdev->host.domain, vdev->host.bus, vdev->host.slot,
1126
            vdev->host.function, addr, size, val);
1127

    
1128
    return val;
1129
}
1130

    
1131
static const MemoryRegionOps vfio_rom_ops = {
1132
    .read = vfio_rom_read,
1133
    .endianness = DEVICE_LITTLE_ENDIAN,
1134
};
1135

    
1136
static void vfio_pci_size_rom(VFIODevice *vdev)
1137
{
1138
    uint32_t orig, size = (uint32_t)PCI_ROM_ADDRESS_MASK;
1139
    off_t offset = vdev->config_offset + PCI_ROM_ADDRESS;
1140
    char name[32];
1141

    
1142
    if (vdev->pdev.romfile || !vdev->pdev.rom_bar) {
1143
        return;
1144
    }
1145

    
1146
    /*
1147
     * Use the same size ROM BAR as the physical device.  The contents
1148
     * will get filled in later when the guest tries to read it.
1149
     */
1150
    if (pread(vdev->fd, &orig, 4, offset) != 4 ||
1151
        pwrite(vdev->fd, &size, 4, offset) != 4 ||
1152
        pread(vdev->fd, &size, 4, offset) != 4 ||
1153
        pwrite(vdev->fd, &orig, 4, offset) != 4) {
1154
        error_report("%s(%04x:%02x:%02x.%x) failed: %m",
1155
                     __func__, vdev->host.domain, vdev->host.bus,
1156
                     vdev->host.slot, vdev->host.function);
1157
        return;
1158
    }
1159

    
1160
    size = ~(size & PCI_ROM_ADDRESS_MASK) + 1;
1161

    
1162
    if (!size) {
1163
        return;
1164
    }
1165

    
1166
    DPRINTF("%04x:%02x:%02x.%x ROM size 0x%x\n", vdev->host.domain,
1167
            vdev->host.bus, vdev->host.slot, vdev->host.function, size);
1168

    
1169
    snprintf(name, sizeof(name), "vfio[%04x:%02x:%02x.%x].rom",
1170
             vdev->host.domain, vdev->host.bus, vdev->host.slot,
1171
             vdev->host.function);
1172

    
1173
    memory_region_init_io(&vdev->pdev.rom, OBJECT(vdev),
1174
                          &vfio_rom_ops, vdev, name, size);
1175

    
1176
    pci_register_bar(&vdev->pdev, PCI_ROM_SLOT,
1177
                     PCI_BASE_ADDRESS_SPACE_MEMORY, &vdev->pdev.rom);
1178

    
1179
    vdev->pdev.has_rom = true;
1180
}
1181

    
1182
static void vfio_vga_write(void *opaque, hwaddr addr,
1183
                           uint64_t data, unsigned size)
1184
{
1185
    VFIOVGARegion *region = opaque;
1186
    VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1187
    union {
1188
        uint8_t byte;
1189
        uint16_t word;
1190
        uint32_t dword;
1191
        uint64_t qword;
1192
    } buf;
1193
    off_t offset = vga->fd_offset + region->offset + addr;
1194

    
1195
    switch (size) {
1196
    case 1:
1197
        buf.byte = data;
1198
        break;
1199
    case 2:
1200
        buf.word = cpu_to_le16(data);
1201
        break;
1202
    case 4:
1203
        buf.dword = cpu_to_le32(data);
1204
        break;
1205
    default:
1206
        hw_error("vfio: unsupported write size, %d bytes\n", size);
1207
        break;
1208
    }
1209

    
1210
    if (pwrite(vga->fd, &buf, size, offset) != size) {
1211
        error_report("%s(,0x%"HWADDR_PRIx", 0x%"PRIx64", %d) failed: %m",
1212
                     __func__, region->offset + addr, data, size);
1213
    }
1214

    
1215
    DPRINTF("%s(0x%"HWADDR_PRIx", 0x%"PRIx64", %d)\n",
1216
            __func__, region->offset + addr, data, size);
1217
}
1218

    
1219
static uint64_t vfio_vga_read(void *opaque, hwaddr addr, unsigned size)
1220
{
1221
    VFIOVGARegion *region = opaque;
1222
    VFIOVGA *vga = container_of(region, VFIOVGA, region[region->nr]);
1223
    union {
1224
        uint8_t byte;
1225
        uint16_t word;
1226
        uint32_t dword;
1227
        uint64_t qword;
1228
    } buf;
1229
    uint64_t data = 0;
1230
    off_t offset = vga->fd_offset + region->offset + addr;
1231

    
1232
    if (pread(vga->fd, &buf, size, offset) != size) {
1233
        error_report("%s(,0x%"HWADDR_PRIx", %d) failed: %m",
1234
                     __func__, region->offset + addr, size);
1235
        return (uint64_t)-1;
1236
    }
1237

    
1238
    switch (size) {
1239
    case 1:
1240
        data = buf.byte;
1241
        break;
1242
    case 2:
1243
        data = le16_to_cpu(buf.word);
1244
        break;
1245
    case 4:
1246
        data = le32_to_cpu(buf.dword);
1247
        break;
1248
    default:
1249
        hw_error("vfio: unsupported read size, %d bytes\n", size);
1250
        break;
1251
    }
1252

    
1253
    DPRINTF("%s(0x%"HWADDR_PRIx", %d) = 0x%"PRIx64"\n",
1254
            __func__, region->offset + addr, size, data);
1255

    
1256
    return data;
1257
}
1258

    
1259
static const MemoryRegionOps vfio_vga_ops = {
1260
    .read = vfio_vga_read,
1261
    .write = vfio_vga_write,
1262
    .endianness = DEVICE_LITTLE_ENDIAN,
1263
};
1264

    
1265
/*
1266
 * Device specific quirks
1267
 */
1268

    
1269
/* Is range1 fully contained within range2?  */
1270
static bool vfio_range_contained(uint64_t first1, uint64_t len1,
1271
                                 uint64_t first2, uint64_t len2) {
1272
    return (first1 >= first2 && first1 + len1 <= first2 + len2);
1273
}
1274

    
1275
static bool vfio_flags_enabled(uint8_t flags, uint8_t mask)
1276
{
1277
    return (mask && (flags & mask) == mask);
1278
}
1279

    
1280
static uint64_t vfio_generic_window_quirk_read(void *opaque,
1281
                                               hwaddr addr, unsigned size)
1282
{
1283
    VFIOQuirk *quirk = opaque;
1284
    VFIODevice *vdev = quirk->vdev;
1285
    uint64_t data;
1286

    
1287
    if (vfio_flags_enabled(quirk->data.flags, quirk->data.read_flags) &&
1288
        ranges_overlap(addr, size,
1289
                       quirk->data.data_offset, quirk->data.data_size)) {
1290
        hwaddr offset = addr - quirk->data.data_offset;
1291

    
1292
        if (!vfio_range_contained(addr, size, quirk->data.data_offset,
1293
                                  quirk->data.data_size)) {
1294
            hw_error("%s: window data read not fully contained: %s\n",
1295
                     __func__, memory_region_name(&quirk->mem));
1296
        }
1297

    
1298
        data = vfio_pci_read_config(&vdev->pdev,
1299
                                    quirk->data.address_val + offset, size);
1300

    
1301
        DPRINTF("%s read(%04x:%02x:%02x.%x:BAR%d+0x%"HWADDR_PRIx", %d) = 0x%"
1302
                PRIx64"\n", memory_region_name(&quirk->mem), vdev->host.domain,
1303
                vdev->host.bus, vdev->host.slot, vdev->host.function,
1304
                quirk->data.bar, addr, size, data);
1305
    } else {
1306
        data = vfio_bar_read(&vdev->bars[quirk->data.bar],
1307
                             addr + quirk->data.base_offset, size);
1308
    }
1309

    
1310
    return data;
1311
}
1312

    
1313
static void vfio_generic_window_quirk_write(void *opaque, hwaddr addr,
1314
                                            uint64_t data, unsigned size)
1315
{
1316
    VFIOQuirk *quirk = opaque;
1317
    VFIODevice *vdev = quirk->vdev;
1318

    
1319
    if (ranges_overlap(addr, size,
1320
                       quirk->data.address_offset, quirk->data.address_size)) {
1321

    
1322
        if (addr != quirk->data.address_offset) {
1323
            hw_error("%s: offset write into address window: %s\n",
1324
                     __func__, memory_region_name(&quirk->mem));
1325
        }
1326

    
1327
        if ((data & ~quirk->data.address_mask) == quirk->data.address_match) {
1328
            quirk->data.flags |= quirk->data.write_flags |
1329
                                 quirk->data.read_flags;
1330
            quirk->data.address_val = data & quirk->data.address_mask;
1331
        } else {
1332
            quirk->data.flags &= ~(quirk->data.write_flags |
1333
                                   quirk->data.read_flags);
1334
        }
1335
    }
1336

    
1337
    if (vfio_flags_enabled(quirk->data.flags, quirk->data.write_flags) &&
1338
        ranges_overlap(addr, size,
1339
                       quirk->data.data_offset, quirk->data.data_size)) {
1340
        hwaddr offset = addr - quirk->data.data_offset;
1341

    
1342
        if (!vfio_range_contained(addr, size, quirk->data.data_offset,
1343
                                  quirk->data.data_size)) {
1344
            hw_error("%s: window data write not fully contained: %s\n",
1345
                     __func__, memory_region_name(&quirk->mem));
1346
        }
1347

    
1348
        vfio_pci_write_config(&vdev->pdev,
1349
                              quirk->data.address_val + offset, data, size);
1350
        DPRINTF("%s write(%04x:%02x:%02x.%x:BAR%d+0x%"HWADDR_PRIx", 0x%"
1351
                PRIx64", %d)\n", memory_region_name(&quirk->mem),
1352
                vdev->host.domain, vdev->host.bus, vdev->host.slot,
1353
                vdev->host.function, quirk->data.bar, addr, data, size);
1354
        return;
1355
    }
1356

    
1357
    vfio_bar_write(&vdev->bars[quirk->data.bar],
1358
                   addr + quirk->data.base_offset, data, size);
1359
}
1360

    
1361
static const MemoryRegionOps vfio_generic_window_quirk = {
1362
    .read = vfio_generic_window_quirk_read,
1363
    .write = vfio_generic_window_quirk_write,
1364
    .endianness = DEVICE_LITTLE_ENDIAN,
1365
};
1366

    
1367
static uint64_t vfio_generic_quirk_read(void *opaque,
1368
                                        hwaddr addr, unsigned size)
1369
{
1370
    VFIOQuirk *quirk = opaque;
1371
    VFIODevice *vdev = quirk->vdev;
1372
    hwaddr base = quirk->data.address_match & TARGET_PAGE_MASK;
1373
    hwaddr offset = quirk->data.address_match & ~TARGET_PAGE_MASK;
1374
    uint64_t data;
1375

    
1376
    if (vfio_flags_enabled(quirk->data.flags, quirk->data.read_flags) &&
1377
        ranges_overlap(addr, size, offset, quirk->data.address_mask + 1)) {
1378
        if (!vfio_range_contained(addr, size, offset,
1379
                                  quirk->data.address_mask + 1)) {
1380
            hw_error("%s: read not fully contained: %s\n",
1381
                     __func__, memory_region_name(&quirk->mem));
1382
        }
1383

    
1384
        data = vfio_pci_read_config(&vdev->pdev, addr - offset, size);
1385

    
1386
        DPRINTF("%s read(%04x:%02x:%02x.%x:BAR%d+0x%"HWADDR_PRIx", %d) = 0x%"
1387
                PRIx64"\n", memory_region_name(&quirk->mem), vdev->host.domain,
1388
                vdev->host.bus, vdev->host.slot, vdev->host.function,
1389
                quirk->data.bar, addr + base, size, data);
1390
    } else {
1391
        data = vfio_bar_read(&vdev->bars[quirk->data.bar], addr + base, size);
1392
    }
1393

    
1394
    return data;
1395
}
1396

    
1397
static void vfio_generic_quirk_write(void *opaque, hwaddr addr,
1398
                                     uint64_t data, unsigned size)
1399
{
1400
    VFIOQuirk *quirk = opaque;
1401
    VFIODevice *vdev = quirk->vdev;
1402
    hwaddr base = quirk->data.address_match & TARGET_PAGE_MASK;
1403
    hwaddr offset = quirk->data.address_match & ~TARGET_PAGE_MASK;
1404

    
1405
    if (vfio_flags_enabled(quirk->data.flags, quirk->data.write_flags) &&
1406
        ranges_overlap(addr, size, offset, quirk->data.address_mask + 1)) {
1407
        if (!vfio_range_contained(addr, size, offset,
1408
                                  quirk->data.address_mask + 1)) {
1409
            hw_error("%s: write not fully contained: %s\n",
1410
                     __func__, memory_region_name(&quirk->mem));
1411
        }
1412

    
1413
        vfio_pci_write_config(&vdev->pdev, addr - offset, data, size);
1414

    
1415
        DPRINTF("%s write(%04x:%02x:%02x.%x:BAR%d+0x%"HWADDR_PRIx", 0x%"
1416
                PRIx64", %d)\n", memory_region_name(&quirk->mem),
1417
                vdev->host.domain, vdev->host.bus, vdev->host.slot,
1418
                vdev->host.function, quirk->data.bar, addr + base, data, size);
1419
    } else {
1420
        vfio_bar_write(&vdev->bars[quirk->data.bar], addr + base, data, size);
1421
    }
1422
}
1423

    
1424
static const MemoryRegionOps vfio_generic_quirk = {
1425
    .read = vfio_generic_quirk_read,
1426
    .write = vfio_generic_quirk_write,
1427
    .endianness = DEVICE_LITTLE_ENDIAN,
1428
};
1429

    
1430
#define PCI_VENDOR_ID_ATI               0x1002
1431

    
1432
/*
1433
 * Radeon HD cards (HD5450 & HD7850) report the upper byte of the I/O port BAR
1434
 * through VGA register 0x3c3.  On newer cards, the I/O port BAR is always
1435
 * BAR4 (older cards like the X550 used BAR1, but we don't care to support
1436
 * those).  Note that on bare metal, a read of 0x3c3 doesn't always return the
1437
 * I/O port BAR address.  Originally this was coded to return the virtual BAR
1438
 * address only if the physical register read returns the actual BAR address,
1439
 * but users have reported greater success if we return the virtual address
1440
 * unconditionally.
1441
 */
1442
static uint64_t vfio_ati_3c3_quirk_read(void *opaque,
1443
                                        hwaddr addr, unsigned size)
1444
{
1445
    VFIOQuirk *quirk = opaque;
1446
    VFIODevice *vdev = quirk->vdev;
1447
    uint64_t data = vfio_pci_read_config(&vdev->pdev,
1448
                                         PCI_BASE_ADDRESS_0 + (4 * 4) + 1,
1449
                                         size);
1450
    DPRINTF("%s(0x3c3, 1) = 0x%"PRIx64"\n", __func__, data);
1451

    
1452
    return data;
1453
}
1454

    
1455
static const MemoryRegionOps vfio_ati_3c3_quirk = {
1456
    .read = vfio_ati_3c3_quirk_read,
1457
    .endianness = DEVICE_LITTLE_ENDIAN,
1458
};
1459

    
1460
static void vfio_vga_probe_ati_3c3_quirk(VFIODevice *vdev)
1461
{
1462
    PCIDevice *pdev = &vdev->pdev;
1463
    VFIOQuirk *quirk;
1464

    
1465
    if (pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_ATI) {
1466
        return;
1467
    }
1468

    
1469
    /*
1470
     * As long as the BAR is >= 256 bytes it will be aligned such that the
1471
     * lower byte is always zero.  Filter out anything else, if it exists.
1472
     */
1473
    if (!vdev->bars[4].ioport || vdev->bars[4].size < 256) {
1474
        return;
1475
    }
1476

    
1477
    quirk = g_malloc0(sizeof(*quirk));
1478
    quirk->vdev = vdev;
1479

    
1480
    memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_ati_3c3_quirk, quirk,
1481
                          "vfio-ati-3c3-quirk", 1);
1482
    memory_region_add_subregion(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
1483
                                3 /* offset 3 bytes from 0x3c0 */, &quirk->mem);
1484

    
1485
    QLIST_INSERT_HEAD(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks,
1486
                      quirk, next);
1487

    
1488
    DPRINTF("Enabled ATI/AMD quirk 0x3c3 BAR4for device %04x:%02x:%02x.%x\n",
1489
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1490
            vdev->host.function);
1491
}
1492

    
1493
/*
1494
 * Newer ATI/AMD devices, including HD5450 and HD7850, have a window to PCI
1495
 * config space through MMIO BAR2 at offset 0x4000.  Nothing seems to access
1496
 * the MMIO space directly, but a window to this space is provided through
1497
 * I/O port BAR4.  Offset 0x0 is the address register and offset 0x4 is the
1498
 * data register.  When the address is programmed to a range of 0x4000-0x4fff
1499
 * PCI configuration space is available.  Experimentation seems to indicate
1500
 * that only read-only access is provided, but we drop writes when the window
1501
 * is enabled to config space nonetheless.
1502
 */
1503
static void vfio_probe_ati_bar4_window_quirk(VFIODevice *vdev, int nr)
1504
{
1505
    PCIDevice *pdev = &vdev->pdev;
1506
    VFIOQuirk *quirk;
1507

    
1508
    if (!vdev->has_vga || nr != 4 ||
1509
        pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_ATI) {
1510
        return;
1511
    }
1512

    
1513
    quirk = g_malloc0(sizeof(*quirk));
1514
    quirk->vdev = vdev;
1515
    quirk->data.address_size = 4;
1516
    quirk->data.data_offset = 4;
1517
    quirk->data.data_size = 4;
1518
    quirk->data.address_match = 0x4000;
1519
    quirk->data.address_mask = PCIE_CONFIG_SPACE_SIZE - 1;
1520
    quirk->data.bar = nr;
1521
    quirk->data.read_flags = quirk->data.write_flags = 1;
1522

    
1523
    memory_region_init_io(&quirk->mem, OBJECT(vdev),
1524
                          &vfio_generic_window_quirk, quirk,
1525
                          "vfio-ati-bar4-window-quirk", 8);
1526
    memory_region_add_subregion_overlap(&vdev->bars[nr].mem,
1527
                          quirk->data.base_offset, &quirk->mem, 1);
1528

    
1529
    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1530

    
1531
    DPRINTF("Enabled ATI/AMD BAR4 window quirk for device %04x:%02x:%02x.%x\n",
1532
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1533
            vdev->host.function);
1534
}
1535

    
1536
/*
1537
 * Trap the BAR2 MMIO window to config space as well.
1538
 */
1539
static void vfio_probe_ati_bar2_4000_quirk(VFIODevice *vdev, int nr)
1540
{
1541
    PCIDevice *pdev = &vdev->pdev;
1542
    VFIOQuirk *quirk;
1543

    
1544
    /* Only enable on newer devices where BAR2 is 64bit */
1545
    if (!vdev->has_vga || nr != 2 || !vdev->bars[2].mem64 ||
1546
        pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_ATI) {
1547
        return;
1548
    }
1549

    
1550
    quirk = g_malloc0(sizeof(*quirk));
1551
    quirk->vdev = vdev;
1552
    quirk->data.flags = quirk->data.read_flags = quirk->data.write_flags = 1;
1553
    quirk->data.address_match = 0x4000;
1554
    quirk->data.address_mask = PCIE_CONFIG_SPACE_SIZE - 1;
1555
    quirk->data.bar = nr;
1556

    
1557
    memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_generic_quirk, quirk,
1558
                          "vfio-ati-bar2-4000-quirk",
1559
                          TARGET_PAGE_ALIGN(quirk->data.address_mask + 1));
1560
    memory_region_add_subregion_overlap(&vdev->bars[nr].mem,
1561
                          quirk->data.address_match & TARGET_PAGE_MASK,
1562
                          &quirk->mem, 1);
1563

    
1564
    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1565

    
1566
    DPRINTF("Enabled ATI/AMD BAR2 0x4000 quirk for device %04x:%02x:%02x.%x\n",
1567
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1568
            vdev->host.function);
1569
}
1570

    
1571
/*
1572
 * Older ATI/AMD cards like the X550 have a similar window to that above.
1573
 * I/O port BAR1 provides a window to a mirror of PCI config space located
1574
 * in BAR2 at offset 0xf00.  We don't care to support such older cards, but
1575
 * note it for future reference.
1576
 */
1577

    
1578
#define PCI_VENDOR_ID_NVIDIA                    0x10de
1579

    
1580
/*
1581
 * Nvidia has several different methods to get to config space, the
1582
 * nouveu project has several of these documented here:
1583
 * https://github.com/pathscale/envytools/tree/master/hwdocs
1584
 *
1585
 * The first quirk is actually not documented in envytools and is found
1586
 * on 10de:01d1 (NVIDIA Corporation G72 [GeForce 7300 LE]).  This is an
1587
 * NV46 chipset.  The backdoor uses the legacy VGA I/O ports to access
1588
 * the mirror of PCI config space found at BAR0 offset 0x1800.  The access
1589
 * sequence first writes 0x338 to I/O port 0x3d4.  The target offset is
1590
 * then written to 0x3d0.  Finally 0x538 is written for a read and 0x738
1591
 * is written for a write to 0x3d4.  The BAR0 offset is then accessible
1592
 * through 0x3d0.  This quirk doesn't seem to be necessary on newer cards
1593
 * that use the I/O port BAR5 window but it doesn't hurt to leave it.
1594
 */
1595
enum {
1596
    NV_3D0_NONE = 0,
1597
    NV_3D0_SELECT,
1598
    NV_3D0_WINDOW,
1599
    NV_3D0_READ,
1600
    NV_3D0_WRITE,
1601
};
1602

    
1603
static uint64_t vfio_nvidia_3d0_quirk_read(void *opaque,
1604
                                           hwaddr addr, unsigned size)
1605
{
1606
    VFIOQuirk *quirk = opaque;
1607
    VFIODevice *vdev = quirk->vdev;
1608
    PCIDevice *pdev = &vdev->pdev;
1609
    uint64_t data = vfio_vga_read(&vdev->vga.region[QEMU_PCI_VGA_IO_HI],
1610
                                  addr + quirk->data.base_offset, size);
1611

    
1612
    if (quirk->data.flags == NV_3D0_READ && addr == quirk->data.data_offset) {
1613
        data = vfio_pci_read_config(pdev, quirk->data.address_val, size);
1614
        DPRINTF("%s(0x3d0, %d) = 0x%"PRIx64"\n", __func__, size, data);
1615
    }
1616

    
1617
    quirk->data.flags = NV_3D0_NONE;
1618

    
1619
    return data;
1620
}
1621

    
1622
static void vfio_nvidia_3d0_quirk_write(void *opaque, hwaddr addr,
1623
                                        uint64_t data, unsigned size)
1624
{
1625
    VFIOQuirk *quirk = opaque;
1626
    VFIODevice *vdev = quirk->vdev;
1627
    PCIDevice *pdev = &vdev->pdev;
1628

    
1629
    switch (quirk->data.flags) {
1630
    case NV_3D0_NONE:
1631
        if (addr == quirk->data.address_offset && data == 0x338) {
1632
            quirk->data.flags = NV_3D0_SELECT;
1633
        }
1634
        break;
1635
    case NV_3D0_SELECT:
1636
        quirk->data.flags = NV_3D0_NONE;
1637
        if (addr == quirk->data.data_offset &&
1638
            (data & ~quirk->data.address_mask) == quirk->data.address_match) {
1639
            quirk->data.flags = NV_3D0_WINDOW;
1640
            quirk->data.address_val = data & quirk->data.address_mask;
1641
        }
1642
        break;
1643
    case NV_3D0_WINDOW:
1644
        quirk->data.flags = NV_3D0_NONE;
1645
        if (addr == quirk->data.address_offset) {
1646
            if (data == 0x538) {
1647
                quirk->data.flags = NV_3D0_READ;
1648
            } else if (data == 0x738) {
1649
                quirk->data.flags = NV_3D0_WRITE;
1650
            }
1651
        }
1652
        break;
1653
    case NV_3D0_WRITE:
1654
        quirk->data.flags = NV_3D0_NONE;
1655
        if (addr == quirk->data.data_offset) {
1656
            vfio_pci_write_config(pdev, quirk->data.address_val, data, size);
1657
            DPRINTF("%s(0x3d0, 0x%"PRIx64", %d)\n", __func__, data, size);
1658
            return;
1659
        }
1660
        break;
1661
    }
1662

    
1663
    vfio_vga_write(&vdev->vga.region[QEMU_PCI_VGA_IO_HI],
1664
                   addr + quirk->data.base_offset, data, size);
1665
}
1666

    
1667
static const MemoryRegionOps vfio_nvidia_3d0_quirk = {
1668
    .read = vfio_nvidia_3d0_quirk_read,
1669
    .write = vfio_nvidia_3d0_quirk_write,
1670
    .endianness = DEVICE_LITTLE_ENDIAN,
1671
};
1672

    
1673
static void vfio_vga_probe_nvidia_3d0_quirk(VFIODevice *vdev)
1674
{
1675
    PCIDevice *pdev = &vdev->pdev;
1676
    VFIOQuirk *quirk;
1677

    
1678
    if (pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA ||
1679
        !vdev->bars[1].size) {
1680
        return;
1681
    }
1682

    
1683
    quirk = g_malloc0(sizeof(*quirk));
1684
    quirk->vdev = vdev;
1685
    quirk->data.base_offset = 0x10;
1686
    quirk->data.address_offset = 4;
1687
    quirk->data.address_size = 2;
1688
    quirk->data.address_match = 0x1800;
1689
    quirk->data.address_mask = PCI_CONFIG_SPACE_SIZE - 1;
1690
    quirk->data.data_offset = 0;
1691
    quirk->data.data_size = 4;
1692

    
1693
    memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_nvidia_3d0_quirk,
1694
                          quirk, "vfio-nvidia-3d0-quirk", 6);
1695
    memory_region_add_subregion(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
1696
                                quirk->data.base_offset, &quirk->mem);
1697

    
1698
    QLIST_INSERT_HEAD(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks,
1699
                      quirk, next);
1700

    
1701
    DPRINTF("Enabled NVIDIA VGA 0x3d0 quirk for device %04x:%02x:%02x.%x\n",
1702
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1703
            vdev->host.function);
1704
}
1705

    
1706
/*
1707
 * The second quirk is documented in envytools.  The I/O port BAR5 is just
1708
 * a set of address/data ports to the MMIO BARs.  The BAR we care about is
1709
 * again BAR0.  This backdoor is apparently a bit newer than the one above
1710
 * so we need to not only trap 256 bytes @0x1800, but all of PCI config
1711
 * space, including extended space is available at the 4k @0x88000.
1712
 */
1713
enum {
1714
    NV_BAR5_ADDRESS = 0x1,
1715
    NV_BAR5_ENABLE = 0x2,
1716
    NV_BAR5_MASTER = 0x4,
1717
    NV_BAR5_VALID = 0x7,
1718
};
1719

    
1720
static void vfio_nvidia_bar5_window_quirk_write(void *opaque, hwaddr addr,
1721
                                                uint64_t data, unsigned size)
1722
{
1723
    VFIOQuirk *quirk = opaque;
1724

    
1725
    switch (addr) {
1726
    case 0x0:
1727
        if (data & 0x1) {
1728
            quirk->data.flags |= NV_BAR5_MASTER;
1729
        } else {
1730
            quirk->data.flags &= ~NV_BAR5_MASTER;
1731
        }
1732
        break;
1733
    case 0x4:
1734
        if (data & 0x1) {
1735
            quirk->data.flags |= NV_BAR5_ENABLE;
1736
        } else {
1737
            quirk->data.flags &= ~NV_BAR5_ENABLE;
1738
        }
1739
        break;
1740
    case 0x8:
1741
        if (quirk->data.flags & NV_BAR5_MASTER) {
1742
            if ((data & ~0xfff) == 0x88000) {
1743
                quirk->data.flags |= NV_BAR5_ADDRESS;
1744
                quirk->data.address_val = data & 0xfff;
1745
            } else if ((data & ~0xff) == 0x1800) {
1746
                quirk->data.flags |= NV_BAR5_ADDRESS;
1747
                quirk->data.address_val = data & 0xff;
1748
            } else {
1749
                quirk->data.flags &= ~NV_BAR5_ADDRESS;
1750
            }
1751
        }
1752
        break;
1753
    }
1754

    
1755
    vfio_generic_window_quirk_write(opaque, addr, data, size);
1756
}
1757

    
1758
static const MemoryRegionOps vfio_nvidia_bar5_window_quirk = {
1759
    .read = vfio_generic_window_quirk_read,
1760
    .write = vfio_nvidia_bar5_window_quirk_write,
1761
    .valid.min_access_size = 4,
1762
    .endianness = DEVICE_LITTLE_ENDIAN,
1763
};
1764

    
1765
static void vfio_probe_nvidia_bar5_window_quirk(VFIODevice *vdev, int nr)
1766
{
1767
    PCIDevice *pdev = &vdev->pdev;
1768
    VFIOQuirk *quirk;
1769

    
1770
    if (!vdev->has_vga || nr != 5 ||
1771
        pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA) {
1772
        return;
1773
    }
1774

    
1775
    quirk = g_malloc0(sizeof(*quirk));
1776
    quirk->vdev = vdev;
1777
    quirk->data.read_flags = quirk->data.write_flags = NV_BAR5_VALID;
1778
    quirk->data.address_offset = 0x8;
1779
    quirk->data.address_size = 0; /* actually 4, but avoids generic code */
1780
    quirk->data.data_offset = 0xc;
1781
    quirk->data.data_size = 4;
1782
    quirk->data.bar = nr;
1783

    
1784
    memory_region_init_io(&quirk->mem, OBJECT(vdev),
1785
                          &vfio_nvidia_bar5_window_quirk, quirk,
1786
                          "vfio-nvidia-bar5-window-quirk", 16);
1787
    memory_region_add_subregion_overlap(&vdev->bars[nr].mem, 0, &quirk->mem, 1);
1788

    
1789
    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1790

    
1791
    DPRINTF("Enabled NVIDIA BAR5 window quirk for device %04x:%02x:%02x.%x\n",
1792
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1793
            vdev->host.function);
1794
}
1795

    
1796
/*
1797
 * Finally, BAR0 itself.  We want to redirect any accesses to either
1798
 * 0x1800 or 0x88000 through the PCI config space access functions.
1799
 *
1800
 * NB - quirk at a page granularity or else they don't seem to work when
1801
 *      BARs are mmap'd
1802
 *
1803
 * Here's offset 0x88000...
1804
 */
1805
static void vfio_probe_nvidia_bar0_88000_quirk(VFIODevice *vdev, int nr)
1806
{
1807
    PCIDevice *pdev = &vdev->pdev;
1808
    VFIOQuirk *quirk;
1809

    
1810
    if (!vdev->has_vga || nr != 0 ||
1811
        pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA) {
1812
        return;
1813
    }
1814

    
1815
    quirk = g_malloc0(sizeof(*quirk));
1816
    quirk->vdev = vdev;
1817
    quirk->data.flags = quirk->data.read_flags = quirk->data.write_flags = 1;
1818
    quirk->data.address_match = 0x88000;
1819
    quirk->data.address_mask = PCIE_CONFIG_SPACE_SIZE - 1;
1820
    quirk->data.bar = nr;
1821

    
1822
    memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_generic_quirk,
1823
                          quirk, "vfio-nvidia-bar0-88000-quirk",
1824
                          TARGET_PAGE_ALIGN(quirk->data.address_mask + 1));
1825
    memory_region_add_subregion_overlap(&vdev->bars[nr].mem,
1826
                          quirk->data.address_match & TARGET_PAGE_MASK,
1827
                          &quirk->mem, 1);
1828

    
1829
    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1830

    
1831
    DPRINTF("Enabled NVIDIA BAR0 0x88000 quirk for device %04x:%02x:%02x.%x\n",
1832
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1833
            vdev->host.function);
1834
}
1835

    
1836
/*
1837
 * And here's the same for BAR0 offset 0x1800...
1838
 */
1839
static void vfio_probe_nvidia_bar0_1800_quirk(VFIODevice *vdev, int nr)
1840
{
1841
    PCIDevice *pdev = &vdev->pdev;
1842
    VFIOQuirk *quirk;
1843

    
1844
    if (!vdev->has_vga || nr != 0 ||
1845
        pci_get_word(pdev->config + PCI_VENDOR_ID) != PCI_VENDOR_ID_NVIDIA) {
1846
        return;
1847
    }
1848

    
1849
    /* Log the chipset ID */
1850
    DPRINTF("Nvidia NV%02x\n",
1851
            (unsigned int)(vfio_bar_read(&vdev->bars[0], 0, 4) >> 20) & 0xff);
1852

    
1853
    quirk = g_malloc0(sizeof(*quirk));
1854
    quirk->vdev = vdev;
1855
    quirk->data.flags = quirk->data.read_flags = quirk->data.write_flags = 1;
1856
    quirk->data.address_match = 0x1800;
1857
    quirk->data.address_mask = PCI_CONFIG_SPACE_SIZE - 1;
1858
    quirk->data.bar = nr;
1859

    
1860
    memory_region_init_io(&quirk->mem, OBJECT(vdev), &vfio_generic_quirk, quirk,
1861
                          "vfio-nvidia-bar0-1800-quirk",
1862
                          TARGET_PAGE_ALIGN(quirk->data.address_mask + 1));
1863
    memory_region_add_subregion_overlap(&vdev->bars[nr].mem,
1864
                          quirk->data.address_match & TARGET_PAGE_MASK,
1865
                          &quirk->mem, 1);
1866

    
1867
    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1868

    
1869
    DPRINTF("Enabled NVIDIA BAR0 0x1800 quirk for device %04x:%02x:%02x.%x\n",
1870
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1871
            vdev->host.function);
1872
}
1873

    
1874
/*
1875
 * TODO - Some Nvidia devices provide config access to their companion HDA
1876
 * device and even to their parent bridge via these config space mirrors.
1877
 * Add quirks for those regions.
1878
 */
1879

    
1880
/*
1881
 * Common quirk probe entry points.
1882
 */
1883
static void vfio_vga_quirk_setup(VFIODevice *vdev)
1884
{
1885
    vfio_vga_probe_ati_3c3_quirk(vdev);
1886
    vfio_vga_probe_nvidia_3d0_quirk(vdev);
1887
}
1888

    
1889
static void vfio_vga_quirk_teardown(VFIODevice *vdev)
1890
{
1891
    int i;
1892

    
1893
    for (i = 0; i < ARRAY_SIZE(vdev->vga.region); i++) {
1894
        while (!QLIST_EMPTY(&vdev->vga.region[i].quirks)) {
1895
            VFIOQuirk *quirk = QLIST_FIRST(&vdev->vga.region[i].quirks);
1896
            memory_region_del_subregion(&vdev->vga.region[i].mem, &quirk->mem);
1897
            QLIST_REMOVE(quirk, next);
1898
            g_free(quirk);
1899
        }
1900
    }
1901
}
1902

    
1903
static void vfio_bar_quirk_setup(VFIODevice *vdev, int nr)
1904
{
1905
    vfio_probe_ati_bar4_window_quirk(vdev, nr);
1906
    vfio_probe_ati_bar2_4000_quirk(vdev, nr);
1907
    vfio_probe_nvidia_bar5_window_quirk(vdev, nr);
1908
    vfio_probe_nvidia_bar0_88000_quirk(vdev, nr);
1909
    vfio_probe_nvidia_bar0_1800_quirk(vdev, nr);
1910
}
1911

    
1912
static void vfio_bar_quirk_teardown(VFIODevice *vdev, int nr)
1913
{
1914
    VFIOBAR *bar = &vdev->bars[nr];
1915

    
1916
    while (!QLIST_EMPTY(&bar->quirks)) {
1917
        VFIOQuirk *quirk = QLIST_FIRST(&bar->quirks);
1918
        memory_region_del_subregion(&bar->mem, &quirk->mem);
1919
        QLIST_REMOVE(quirk, next);
1920
        g_free(quirk);
1921
    }
1922
}
1923

    
1924
/*
1925
 * PCI config space
1926
 */
1927
static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)
1928
{
1929
    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
1930
    uint32_t emu_bits = 0, emu_val = 0, phys_val = 0, val;
1931

    
1932
    memcpy(&emu_bits, vdev->emulated_config_bits + addr, len);
1933
    emu_bits = le32_to_cpu(emu_bits);
1934

    
1935
    if (emu_bits) {
1936
        emu_val = pci_default_read_config(pdev, addr, len);
1937
    }
1938

    
1939
    if (~emu_bits & (0xffffffffU >> (32 - len * 8))) {
1940
        ssize_t ret;
1941

    
1942
        ret = pread(vdev->fd, &phys_val, len, vdev->config_offset + addr);
1943
        if (ret != len) {
1944
            error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m",
1945
                         __func__, vdev->host.domain, vdev->host.bus,
1946
                         vdev->host.slot, vdev->host.function, addr, len);
1947
            return -errno;
1948
        }
1949
        phys_val = le32_to_cpu(phys_val);
1950
    }
1951

    
1952
    val = (emu_val & emu_bits) | (phys_val & ~emu_bits);
1953

    
1954
    DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, len=0x%x) %x\n", __func__,
1955
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1956
            vdev->host.function, addr, len, val);
1957

    
1958
    return val;
1959
}
1960

    
1961
static void vfio_pci_write_config(PCIDevice *pdev, uint32_t addr,
1962
                                  uint32_t val, int len)
1963
{
1964
    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
1965
    uint32_t val_le = cpu_to_le32(val);
1966

    
1967
    DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, 0x%x, len=0x%x)\n", __func__,
1968
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
1969
            vdev->host.function, addr, val, len);
1970

    
1971
    /* Write everything to VFIO, let it filter out what we can't write */
1972
    if (pwrite(vdev->fd, &val_le, len, vdev->config_offset + addr) != len) {
1973
        error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x, 0x%x) failed: %m",
1974
                     __func__, vdev->host.domain, vdev->host.bus,
1975
                     vdev->host.slot, vdev->host.function, addr, val, len);
1976
    }
1977

    
1978
    /* MSI/MSI-X Enabling/Disabling */
1979
    if (pdev->cap_present & QEMU_PCI_CAP_MSI &&
1980
        ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size)) {
1981
        int is_enabled, was_enabled = msi_enabled(pdev);
1982

    
1983
        pci_default_write_config(pdev, addr, val, len);
1984

    
1985
        is_enabled = msi_enabled(pdev);
1986

    
1987
        if (!was_enabled) {
1988
            if (is_enabled) {
1989
                vfio_enable_msi(vdev);
1990
            }
1991
        } else {
1992
            if (!is_enabled) {
1993
                vfio_disable_msi(vdev);
1994
            } else {
1995
                vfio_update_msi(vdev);
1996
            }
1997
        }
1998
    } else if (pdev->cap_present & QEMU_PCI_CAP_MSIX &&
1999
        ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) {
2000
        int is_enabled, was_enabled = msix_enabled(pdev);
2001

    
2002
        pci_default_write_config(pdev, addr, val, len);
2003

    
2004
        is_enabled = msix_enabled(pdev);
2005

    
2006
        if (!was_enabled && is_enabled) {
2007
            vfio_enable_msix(vdev);
2008
        } else if (was_enabled && !is_enabled) {
2009
            vfio_disable_msix(vdev);
2010
        }
2011
    } else {
2012
        /* Write everything to QEMU to keep emulated bits correct */
2013
        pci_default_write_config(pdev, addr, val, len);
2014
    }
2015
}
2016

    
2017
/*
2018
 * DMA - Mapping and unmapping for the "type1" IOMMU interface used on x86
2019
 */
2020
static int vfio_dma_unmap(VFIOContainer *container,
2021
                          hwaddr iova, ram_addr_t size)
2022
{
2023
    struct vfio_iommu_type1_dma_unmap unmap = {
2024
        .argsz = sizeof(unmap),
2025
        .flags = 0,
2026
        .iova = iova,
2027
        .size = size,
2028
    };
2029

    
2030
    if (ioctl(container->fd, VFIO_IOMMU_UNMAP_DMA, &unmap)) {
2031
        DPRINTF("VFIO_UNMAP_DMA: %d\n", -errno);
2032
        return -errno;
2033
    }
2034

    
2035
    return 0;
2036
}
2037

    
2038
static int vfio_dma_map(VFIOContainer *container, hwaddr iova,
2039
                        ram_addr_t size, void *vaddr, bool readonly)
2040
{
2041
    struct vfio_iommu_type1_dma_map map = {
2042
        .argsz = sizeof(map),
2043
        .flags = VFIO_DMA_MAP_FLAG_READ,
2044
        .vaddr = (__u64)(uintptr_t)vaddr,
2045
        .iova = iova,
2046
        .size = size,
2047
    };
2048

    
2049
    if (!readonly) {
2050
        map.flags |= VFIO_DMA_MAP_FLAG_WRITE;
2051
    }
2052

    
2053
    /*
2054
     * Try the mapping, if it fails with EBUSY, unmap the region and try
2055
     * again.  This shouldn't be necessary, but we sometimes see it in
2056
     * the the VGA ROM space.
2057
     */
2058
    if (ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0 ||
2059
        (errno == EBUSY && vfio_dma_unmap(container, iova, size) == 0 &&
2060
         ioctl(container->fd, VFIO_IOMMU_MAP_DMA, &map) == 0)) {
2061
        return 0;
2062
    }
2063

    
2064
    DPRINTF("VFIO_MAP_DMA: %d\n", -errno);
2065
    return -errno;
2066
}
2067

    
2068
static bool vfio_listener_skipped_section(MemoryRegionSection *section)
2069
{
2070
    return !memory_region_is_ram(section->mr);
2071
}
2072

    
2073
static void vfio_listener_region_add(MemoryListener *listener,
2074
                                     MemoryRegionSection *section)
2075
{
2076
    VFIOContainer *container = container_of(listener, VFIOContainer,
2077
                                            iommu_data.listener);
2078
    hwaddr iova, end;
2079
    void *vaddr;
2080
    int ret;
2081

    
2082
    assert(!memory_region_is_iommu(section->mr));
2083

    
2084
    if (vfio_listener_skipped_section(section)) {
2085
        DPRINTF("SKIPPING region_add %"HWADDR_PRIx" - %"PRIx64"\n",
2086
                section->offset_within_address_space,
2087
                section->offset_within_address_space +
2088
                int128_get64(int128_sub(section->size, int128_one())));
2089
        return;
2090
    }
2091

    
2092
    if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
2093
                 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
2094
        error_report("%s received unaligned region", __func__);
2095
        return;
2096
    }
2097

    
2098
    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
2099
    end = (section->offset_within_address_space + int128_get64(section->size)) &
2100
          TARGET_PAGE_MASK;
2101

    
2102
    if (iova >= end) {
2103
        return;
2104
    }
2105

    
2106
    vaddr = memory_region_get_ram_ptr(section->mr) +
2107
            section->offset_within_region +
2108
            (iova - section->offset_within_address_space);
2109

    
2110
    DPRINTF("region_add %"HWADDR_PRIx" - %"HWADDR_PRIx" [%p]\n",
2111
            iova, end - 1, vaddr);
2112

    
2113
    memory_region_ref(section->mr);
2114
    ret = vfio_dma_map(container, iova, end - iova, vaddr, section->readonly);
2115
    if (ret) {
2116
        error_report("vfio_dma_map(%p, 0x%"HWADDR_PRIx", "
2117
                     "0x%"HWADDR_PRIx", %p) = %d (%m)",
2118
                     container, iova, end - iova, vaddr, ret);
2119
    }
2120
}
2121

    
2122
static void vfio_listener_region_del(MemoryListener *listener,
2123
                                     MemoryRegionSection *section)
2124
{
2125
    VFIOContainer *container = container_of(listener, VFIOContainer,
2126
                                            iommu_data.listener);
2127
    hwaddr iova, end;
2128
    int ret;
2129

    
2130
    if (vfio_listener_skipped_section(section)) {
2131
        DPRINTF("SKIPPING region_del %"HWADDR_PRIx" - %"PRIx64"\n",
2132
                section->offset_within_address_space,
2133
                section->offset_within_address_space +
2134
                int128_get64(int128_sub(section->size, int128_one())));
2135
        return;
2136
    }
2137

    
2138
    if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
2139
                 (section->offset_within_region & ~TARGET_PAGE_MASK))) {
2140
        error_report("%s received unaligned region", __func__);
2141
        return;
2142
    }
2143

    
2144
    iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
2145
    end = (section->offset_within_address_space + int128_get64(section->size)) &
2146
          TARGET_PAGE_MASK;
2147

    
2148
    if (iova >= end) {
2149
        return;
2150
    }
2151

    
2152
    DPRINTF("region_del %"HWADDR_PRIx" - %"HWADDR_PRIx"\n",
2153
            iova, end - 1);
2154

    
2155
    ret = vfio_dma_unmap(container, iova, end - iova);
2156
    memory_region_unref(section->mr);
2157
    if (ret) {
2158
        error_report("vfio_dma_unmap(%p, 0x%"HWADDR_PRIx", "
2159
                     "0x%"HWADDR_PRIx") = %d (%m)",
2160
                     container, iova, end - iova, ret);
2161
    }
2162
}
2163

    
2164
static MemoryListener vfio_memory_listener = {
2165
    .region_add = vfio_listener_region_add,
2166
    .region_del = vfio_listener_region_del,
2167
};
2168

    
2169
static void vfio_listener_release(VFIOContainer *container)
2170
{
2171
    memory_listener_unregister(&container->iommu_data.listener);
2172
}
2173

    
2174
/*
2175
 * Interrupt setup
2176
 */
2177
static void vfio_disable_interrupts(VFIODevice *vdev)
2178
{
2179
    switch (vdev->interrupt) {
2180
    case VFIO_INT_INTx:
2181
        vfio_disable_intx(vdev);
2182
        break;
2183
    case VFIO_INT_MSI:
2184
        vfio_disable_msi(vdev);
2185
        break;
2186
    case VFIO_INT_MSIX:
2187
        vfio_disable_msix(vdev);
2188
        break;
2189
    }
2190
}
2191

    
2192
static int vfio_setup_msi(VFIODevice *vdev, int pos)
2193
{
2194
    uint16_t ctrl;
2195
    bool msi_64bit, msi_maskbit;
2196
    int ret, entries;
2197

    
2198
    if (pread(vdev->fd, &ctrl, sizeof(ctrl),
2199
              vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
2200
        return -errno;
2201
    }
2202
    ctrl = le16_to_cpu(ctrl);
2203

    
2204
    msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);
2205
    msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);
2206
    entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);
2207

    
2208
    DPRINTF("%04x:%02x:%02x.%x PCI MSI CAP @0x%x\n", vdev->host.domain,
2209
            vdev->host.bus, vdev->host.slot, vdev->host.function, pos);
2210

    
2211
    ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit);
2212
    if (ret < 0) {
2213
        if (ret == -ENOTSUP) {
2214
            return 0;
2215
        }
2216
        error_report("vfio: msi_init failed");
2217
        return ret;
2218
    }
2219
    vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);
2220

    
2221
    return 0;
2222
}
2223

    
2224
/*
2225
 * We don't have any control over how pci_add_capability() inserts
2226
 * capabilities into the chain.  In order to setup MSI-X we need a
2227
 * MemoryRegion for the BAR.  In order to setup the BAR and not
2228
 * attempt to mmap the MSI-X table area, which VFIO won't allow, we
2229
 * need to first look for where the MSI-X table lives.  So we
2230
 * unfortunately split MSI-X setup across two functions.
2231
 */
2232
static int vfio_early_setup_msix(VFIODevice *vdev)
2233
{
2234
    uint8_t pos;
2235
    uint16_t ctrl;
2236
    uint32_t table, pba;
2237

    
2238
    pos = pci_find_capability(&vdev->pdev, PCI_CAP_ID_MSIX);
2239
    if (!pos) {
2240
        return 0;
2241
    }
2242

    
2243
    if (pread(vdev->fd, &ctrl, sizeof(ctrl),
2244
              vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {
2245
        return -errno;
2246
    }
2247

    
2248
    if (pread(vdev->fd, &table, sizeof(table),
2249
              vdev->config_offset + pos + PCI_MSIX_TABLE) != sizeof(table)) {
2250
        return -errno;
2251
    }
2252

    
2253
    if (pread(vdev->fd, &pba, sizeof(pba),
2254
              vdev->config_offset + pos + PCI_MSIX_PBA) != sizeof(pba)) {
2255
        return -errno;
2256
    }
2257

    
2258
    ctrl = le16_to_cpu(ctrl);
2259
    table = le32_to_cpu(table);
2260
    pba = le32_to_cpu(pba);
2261

    
2262
    vdev->msix = g_malloc0(sizeof(*(vdev->msix)));
2263
    vdev->msix->table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
2264
    vdev->msix->table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
2265
    vdev->msix->pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
2266
    vdev->msix->pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
2267
    vdev->msix->entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
2268

    
2269
    DPRINTF("%04x:%02x:%02x.%x "
2270
            "PCI MSI-X CAP @0x%x, BAR %d, offset 0x%x, entries %d\n",
2271
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
2272
            vdev->host.function, pos, vdev->msix->table_bar,
2273
            vdev->msix->table_offset, vdev->msix->entries);
2274

    
2275
    return 0;
2276
}
2277

    
2278
static int vfio_setup_msix(VFIODevice *vdev, int pos)
2279
{
2280
    int ret;
2281

    
2282
    ret = msix_init(&vdev->pdev, vdev->msix->entries,
2283
                    &vdev->bars[vdev->msix->table_bar].mem,
2284
                    vdev->msix->table_bar, vdev->msix->table_offset,
2285
                    &vdev->bars[vdev->msix->pba_bar].mem,
2286
                    vdev->msix->pba_bar, vdev->msix->pba_offset, pos);
2287
    if (ret < 0) {
2288
        if (ret == -ENOTSUP) {
2289
            return 0;
2290
        }
2291
        error_report("vfio: msix_init failed");
2292
        return ret;
2293
    }
2294

    
2295
    return 0;
2296
}
2297

    
2298
static void vfio_teardown_msi(VFIODevice *vdev)
2299
{
2300
    msi_uninit(&vdev->pdev);
2301

    
2302
    if (vdev->msix) {
2303
        msix_uninit(&vdev->pdev, &vdev->bars[vdev->msix->table_bar].mem,
2304
                    &vdev->bars[vdev->msix->pba_bar].mem);
2305
    }
2306
}
2307

    
2308
/*
2309
 * Resource setup
2310
 */
2311
static void vfio_mmap_set_enabled(VFIODevice *vdev, bool enabled)
2312
{
2313
    int i;
2314

    
2315
    for (i = 0; i < PCI_ROM_SLOT; i++) {
2316
        VFIOBAR *bar = &vdev->bars[i];
2317

    
2318
        if (!bar->size) {
2319
            continue;
2320
        }
2321

    
2322
        memory_region_set_enabled(&bar->mmap_mem, enabled);
2323
        if (vdev->msix && vdev->msix->table_bar == i) {
2324
            memory_region_set_enabled(&vdev->msix->mmap_mem, enabled);
2325
        }
2326
    }
2327
}
2328

    
2329
static void vfio_unmap_bar(VFIODevice *vdev, int nr)
2330
{
2331
    VFIOBAR *bar = &vdev->bars[nr];
2332

    
2333
    if (!bar->size) {
2334
        return;
2335
    }
2336

    
2337
    vfio_bar_quirk_teardown(vdev, nr);
2338

    
2339
    memory_region_del_subregion(&bar->mem, &bar->mmap_mem);
2340
    munmap(bar->mmap, memory_region_size(&bar->mmap_mem));
2341

    
2342
    if (vdev->msix && vdev->msix->table_bar == nr) {
2343
        memory_region_del_subregion(&bar->mem, &vdev->msix->mmap_mem);
2344
        munmap(vdev->msix->mmap, memory_region_size(&vdev->msix->mmap_mem));
2345
    }
2346

    
2347
    memory_region_destroy(&bar->mem);
2348
}
2349

    
2350
static int vfio_mmap_bar(VFIODevice *vdev, VFIOBAR *bar,
2351
                         MemoryRegion *mem, MemoryRegion *submem,
2352
                         void **map, size_t size, off_t offset,
2353
                         const char *name)
2354
{
2355
    int ret = 0;
2356

    
2357
    if (VFIO_ALLOW_MMAP && size && bar->flags & VFIO_REGION_INFO_FLAG_MMAP) {
2358
        int prot = 0;
2359

    
2360
        if (bar->flags & VFIO_REGION_INFO_FLAG_READ) {
2361
            prot |= PROT_READ;
2362
        }
2363

    
2364
        if (bar->flags & VFIO_REGION_INFO_FLAG_WRITE) {
2365
            prot |= PROT_WRITE;
2366
        }
2367

    
2368
        *map = mmap(NULL, size, prot, MAP_SHARED,
2369
                    bar->fd, bar->fd_offset + offset);
2370
        if (*map == MAP_FAILED) {
2371
            *map = NULL;
2372
            ret = -errno;
2373
            goto empty_region;
2374
        }
2375

    
2376
        memory_region_init_ram_ptr(submem, OBJECT(vdev), name, size, *map);
2377
    } else {
2378
empty_region:
2379
        /* Create a zero sized sub-region to make cleanup easy. */
2380
        memory_region_init(submem, OBJECT(vdev), name, 0);
2381
    }
2382

    
2383
    memory_region_add_subregion(mem, offset, submem);
2384

    
2385
    return ret;
2386
}
2387

    
2388
static void vfio_map_bar(VFIODevice *vdev, int nr)
2389
{
2390
    VFIOBAR *bar = &vdev->bars[nr];
2391
    unsigned size = bar->size;
2392
    char name[64];
2393
    uint32_t pci_bar;
2394
    uint8_t type;
2395
    int ret;
2396

    
2397
    /* Skip both unimplemented BARs and the upper half of 64bit BARS. */
2398
    if (!size) {
2399
        return;
2400
    }
2401

    
2402
    snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",
2403
             vdev->host.domain, vdev->host.bus, vdev->host.slot,
2404
             vdev->host.function, nr);
2405

    
2406
    /* Determine what type of BAR this is for registration */
2407
    ret = pread(vdev->fd, &pci_bar, sizeof(pci_bar),
2408
                vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));
2409
    if (ret != sizeof(pci_bar)) {
2410
        error_report("vfio: Failed to read BAR %d (%m)", nr);
2411
        return;
2412
    }
2413

    
2414
    pci_bar = le32_to_cpu(pci_bar);
2415
    bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);
2416
    bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);
2417
    type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :
2418
                                    ~PCI_BASE_ADDRESS_MEM_MASK);
2419

    
2420
    /* A "slow" read/write mapping underlies all BARs */
2421
    memory_region_init_io(&bar->mem, OBJECT(vdev), &vfio_bar_ops,
2422
                          bar, name, size);
2423
    pci_register_bar(&vdev->pdev, nr, type, &bar->mem);
2424

    
2425
    /*
2426
     * We can't mmap areas overlapping the MSIX vector table, so we
2427
     * potentially insert a direct-mapped subregion before and after it.
2428
     */
2429
    if (vdev->msix && vdev->msix->table_bar == nr) {
2430
        size = vdev->msix->table_offset & TARGET_PAGE_MASK;
2431
    }
2432

    
2433
    strncat(name, " mmap", sizeof(name) - strlen(name) - 1);
2434
    if (vfio_mmap_bar(vdev, bar, &bar->mem,
2435
                      &bar->mmap_mem, &bar->mmap, size, 0, name)) {
2436
        error_report("%s unsupported. Performance may be slow", name);
2437
    }
2438

    
2439
    if (vdev->msix && vdev->msix->table_bar == nr) {
2440
        unsigned start;
2441

    
2442
        start = TARGET_PAGE_ALIGN(vdev->msix->table_offset +
2443
                                  (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));
2444

    
2445
        size = start < bar->size ? bar->size - start : 0;
2446
        strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);
2447
        /* VFIOMSIXInfo contains another MemoryRegion for this mapping */
2448
        if (vfio_mmap_bar(vdev, bar, &bar->mem, &vdev->msix->mmap_mem,
2449
                          &vdev->msix->mmap, size, start, name)) {
2450
            error_report("%s unsupported. Performance may be slow", name);
2451
        }
2452
    }
2453

    
2454
    vfio_bar_quirk_setup(vdev, nr);
2455
}
2456

    
2457
static void vfio_map_bars(VFIODevice *vdev)
2458
{
2459
    int i;
2460

    
2461
    for (i = 0; i < PCI_ROM_SLOT; i++) {
2462
        vfio_map_bar(vdev, i);
2463
    }
2464

    
2465
    if (vdev->has_vga) {
2466
        memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
2467
                              OBJECT(vdev), &vfio_vga_ops,
2468
                              &vdev->vga.region[QEMU_PCI_VGA_MEM],
2469
                              "vfio-vga-mmio@0xa0000",
2470
                              QEMU_PCI_VGA_MEM_SIZE);
2471
        memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
2472
                              OBJECT(vdev), &vfio_vga_ops,
2473
                              &vdev->vga.region[QEMU_PCI_VGA_IO_LO],
2474
                              "vfio-vga-io@0x3b0",
2475
                              QEMU_PCI_VGA_IO_LO_SIZE);
2476
        memory_region_init_io(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem,
2477
                              OBJECT(vdev), &vfio_vga_ops,
2478
                              &vdev->vga.region[QEMU_PCI_VGA_IO_HI],
2479
                              "vfio-vga-io@0x3c0",
2480
                              QEMU_PCI_VGA_IO_HI_SIZE);
2481

    
2482
        pci_register_vga(&vdev->pdev, &vdev->vga.region[QEMU_PCI_VGA_MEM].mem,
2483
                         &vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem,
2484
                         &vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem);
2485
        vfio_vga_quirk_setup(vdev);
2486
    }
2487
}
2488

    
2489
static void vfio_unmap_bars(VFIODevice *vdev)
2490
{
2491
    int i;
2492

    
2493
    for (i = 0; i < PCI_ROM_SLOT; i++) {
2494
        vfio_unmap_bar(vdev, i);
2495
    }
2496

    
2497
    if (vdev->has_vga) {
2498
        vfio_vga_quirk_teardown(vdev);
2499
        pci_unregister_vga(&vdev->pdev);
2500
        memory_region_destroy(&vdev->vga.region[QEMU_PCI_VGA_MEM].mem);
2501
        memory_region_destroy(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].mem);
2502
        memory_region_destroy(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].mem);
2503
    }
2504
}
2505

    
2506
/*
2507
 * General setup
2508
 */
2509
static uint8_t vfio_std_cap_max_size(PCIDevice *pdev, uint8_t pos)
2510
{
2511
    uint8_t tmp, next = 0xff;
2512

    
2513
    for (tmp = pdev->config[PCI_CAPABILITY_LIST]; tmp;
2514
         tmp = pdev->config[tmp + 1]) {
2515
        if (tmp > pos && tmp < next) {
2516
            next = tmp;
2517
        }
2518
    }
2519

    
2520
    return next - pos;
2521
}
2522

    
2523
static void vfio_set_word_bits(uint8_t *buf, uint16_t val, uint16_t mask)
2524
{
2525
    pci_set_word(buf, (pci_get_word(buf) & ~mask) | val);
2526
}
2527

    
2528
static void vfio_add_emulated_word(VFIODevice *vdev, int pos,
2529
                                   uint16_t val, uint16_t mask)
2530
{
2531
    vfio_set_word_bits(vdev->pdev.config + pos, val, mask);
2532
    vfio_set_word_bits(vdev->pdev.wmask + pos, ~mask, mask);
2533
    vfio_set_word_bits(vdev->emulated_config_bits + pos, mask, mask);
2534
}
2535

    
2536
static void vfio_set_long_bits(uint8_t *buf, uint32_t val, uint32_t mask)
2537
{
2538
    pci_set_long(buf, (pci_get_long(buf) & ~mask) | val);
2539
}
2540

    
2541
static void vfio_add_emulated_long(VFIODevice *vdev, int pos,
2542
                                   uint32_t val, uint32_t mask)
2543
{
2544
    vfio_set_long_bits(vdev->pdev.config + pos, val, mask);
2545
    vfio_set_long_bits(vdev->pdev.wmask + pos, ~mask, mask);
2546
    vfio_set_long_bits(vdev->emulated_config_bits + pos, mask, mask);
2547
}
2548

    
2549
static int vfio_setup_pcie_cap(VFIODevice *vdev, int pos, uint8_t size)
2550
{
2551
    uint16_t flags;
2552
    uint8_t type;
2553

    
2554
    flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
2555
    type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
2556

    
2557
    if (type != PCI_EXP_TYPE_ENDPOINT &&
2558
        type != PCI_EXP_TYPE_LEG_END &&
2559
        type != PCI_EXP_TYPE_RC_END) {
2560

    
2561
        error_report("vfio: Assignment of PCIe type 0x%x "
2562
                     "devices is not currently supported", type);
2563
        return -EINVAL;
2564
    }
2565

    
2566
    if (!pci_bus_is_express(vdev->pdev.bus)) {
2567
        /*
2568
         * Use express capability as-is on PCI bus.  It doesn't make much
2569
         * sense to even expose, but some drivers (ex. tg3) depend on it
2570
         * and guests don't seem to be particular about it.  We'll need
2571
         * to revist this or force express devices to express buses if we
2572
         * ever expose an IOMMU to the guest.
2573
         */
2574
    } else if (pci_bus_is_root(vdev->pdev.bus)) {
2575
        /*
2576
         * On a Root Complex bus Endpoints become Root Complex Integrated
2577
         * Endpoints, which changes the type and clears the LNK & LNK2 fields.
2578
         */
2579
        if (type == PCI_EXP_TYPE_ENDPOINT) {
2580
            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
2581
                                   PCI_EXP_TYPE_RC_END << 4,
2582
                                   PCI_EXP_FLAGS_TYPE);
2583

    
2584
            /* Link Capabilities, Status, and Control goes away */
2585
            if (size > PCI_EXP_LNKCTL) {
2586
                vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
2587
                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
2588
                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
2589

    
2590
#ifndef PCI_EXP_LNKCAP2
2591
#define PCI_EXP_LNKCAP2 44
2592
#endif
2593
#ifndef PCI_EXP_LNKSTA2
2594
#define PCI_EXP_LNKSTA2 50
2595
#endif
2596
                /* Link 2 Capabilities, Status, and Control goes away */
2597
                if (size > PCI_EXP_LNKCAP2) {
2598
                    vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
2599
                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
2600
                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
2601
                }
2602
            }
2603

    
2604
        } else if (type == PCI_EXP_TYPE_LEG_END) {
2605
            /*
2606
             * Legacy endpoints don't belong on the root complex.  Windows
2607
             * seems to be happier with devices if we skip the capability.
2608
             */
2609
            return 0;
2610
        }
2611

    
2612
    } else {
2613
        /*
2614
         * Convert Root Complex Integrated Endpoints to regular endpoints.
2615
         * These devices don't support LNK/LNK2 capabilities, so make them up.
2616
         */
2617
        if (type == PCI_EXP_TYPE_RC_END) {
2618
            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,
2619
                                   PCI_EXP_TYPE_ENDPOINT << 4,
2620
                                   PCI_EXP_FLAGS_TYPE);
2621
            vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
2622
                                   PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);
2623
            vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
2624
        }
2625

    
2626
        /* Mark the Link Status bits as emulated to allow virtual negotiation */
2627
        vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,
2628
                               pci_get_word(vdev->pdev.config + pos +
2629
                                            PCI_EXP_LNKSTA),
2630
                               PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);
2631
    }
2632

    
2633
    pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size);
2634
    if (pos >= 0) {
2635
        vdev->pdev.exp.exp_cap = pos;
2636
    }
2637

    
2638
    return pos;
2639
}
2640

    
2641
static void vfio_check_pcie_flr(VFIODevice *vdev, uint8_t pos)
2642
{
2643
    uint32_t cap = pci_get_long(vdev->pdev.config + pos + PCI_EXP_DEVCAP);
2644

    
2645
    if (cap & PCI_EXP_DEVCAP_FLR) {
2646
        DPRINTF("%04x:%02x:%02x.%x Supports FLR via PCIe cap\n",
2647
                vdev->host.domain, vdev->host.bus, vdev->host.slot,
2648
                vdev->host.function);
2649
        vdev->has_flr = true;
2650
    }
2651
}
2652

    
2653
static void vfio_check_pm_reset(VFIODevice *vdev, uint8_t pos)
2654
{
2655
    uint16_t csr = pci_get_word(vdev->pdev.config + pos + PCI_PM_CTRL);
2656

    
2657
    if (!(csr & PCI_PM_CTRL_NO_SOFT_RESET)) {
2658
        DPRINTF("%04x:%02x:%02x.%x Supports PM reset\n",
2659
                vdev->host.domain, vdev->host.bus, vdev->host.slot,
2660
                vdev->host.function);
2661
        vdev->has_pm_reset = true;
2662
    }
2663
}
2664

    
2665
static void vfio_check_af_flr(VFIODevice *vdev, uint8_t pos)
2666
{
2667
    uint8_t cap = pci_get_byte(vdev->pdev.config + pos + PCI_AF_CAP);
2668

    
2669
    if ((cap & PCI_AF_CAP_TP) && (cap & PCI_AF_CAP_FLR)) {
2670
        DPRINTF("%04x:%02x:%02x.%x Supports FLR via AF cap\n",
2671
                vdev->host.domain, vdev->host.bus, vdev->host.slot,
2672
                vdev->host.function);
2673
        vdev->has_flr = true;
2674
    }
2675
}
2676

    
2677
static int vfio_add_std_cap(VFIODevice *vdev, uint8_t pos)
2678
{
2679
    PCIDevice *pdev = &vdev->pdev;
2680
    uint8_t cap_id, next, size;
2681
    int ret;
2682

    
2683
    cap_id = pdev->config[pos];
2684
    next = pdev->config[pos + 1];
2685

    
2686
    /*
2687
     * If it becomes important to configure capabilities to their actual
2688
     * size, use this as the default when it's something we don't recognize.
2689
     * Since QEMU doesn't actually handle many of the config accesses,
2690
     * exact size doesn't seem worthwhile.
2691
     */
2692
    size = vfio_std_cap_max_size(pdev, pos);
2693

    
2694
    /*
2695
     * pci_add_capability always inserts the new capability at the head
2696
     * of the chain.  Therefore to end up with a chain that matches the
2697
     * physical device, we insert from the end by making this recursive.
2698
     * This is also why we pre-caclulate size above as cached config space
2699
     * will be changed as we unwind the stack.
2700
     */
2701
    if (next) {
2702
        ret = vfio_add_std_cap(vdev, next);
2703
        if (ret) {
2704
            return ret;
2705
        }
2706
    } else {
2707
        /* Begin the rebuild, use QEMU emulated list bits */
2708
        pdev->config[PCI_CAPABILITY_LIST] = 0;
2709
        vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;
2710
        vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
2711
    }
2712

    
2713
    /* Use emulated next pointer to allow dropping caps */
2714
    pci_set_byte(vdev->emulated_config_bits + pos + 1, 0xff);
2715

    
2716
    switch (cap_id) {
2717
    case PCI_CAP_ID_MSI:
2718
        ret = vfio_setup_msi(vdev, pos);
2719
        break;
2720
    case PCI_CAP_ID_EXP:
2721
        vfio_check_pcie_flr(vdev, pos);
2722
        ret = vfio_setup_pcie_cap(vdev, pos, size);
2723
        break;
2724
    case PCI_CAP_ID_MSIX:
2725
        ret = vfio_setup_msix(vdev, pos);
2726
        break;
2727
    case PCI_CAP_ID_PM:
2728
        vfio_check_pm_reset(vdev, pos);
2729
        vdev->pm_cap = pos;
2730
        ret = pci_add_capability(pdev, cap_id, pos, size);
2731
        break;
2732
    case PCI_CAP_ID_AF:
2733
        vfio_check_af_flr(vdev, pos);
2734
        ret = pci_add_capability(pdev, cap_id, pos, size);
2735
        break;
2736
    default:
2737
        ret = pci_add_capability(pdev, cap_id, pos, size);
2738
        break;
2739
    }
2740

    
2741
    if (ret < 0) {
2742
        error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "
2743
                     "0x%x[0x%x]@0x%x: %d", vdev->host.domain,
2744
                     vdev->host.bus, vdev->host.slot, vdev->host.function,
2745
                     cap_id, size, pos, ret);
2746
        return ret;
2747
    }
2748

    
2749
    return 0;
2750
}
2751

    
2752
static int vfio_add_capabilities(VFIODevice *vdev)
2753
{
2754
    PCIDevice *pdev = &vdev->pdev;
2755

    
2756
    if (!(pdev->config[PCI_STATUS] & PCI_STATUS_CAP_LIST) ||
2757
        !pdev->config[PCI_CAPABILITY_LIST]) {
2758
        return 0; /* Nothing to add */
2759
    }
2760

    
2761
    return vfio_add_std_cap(vdev, pdev->config[PCI_CAPABILITY_LIST]);
2762
}
2763

    
2764
static void vfio_pci_pre_reset(VFIODevice *vdev)
2765
{
2766
    PCIDevice *pdev = &vdev->pdev;
2767
    uint16_t cmd;
2768

    
2769
    vfio_disable_interrupts(vdev);
2770

    
2771
    /* Make sure the device is in D0 */
2772
    if (vdev->pm_cap) {
2773
        uint16_t pmcsr;
2774
        uint8_t state;
2775

    
2776
        pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2777
        state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2778
        if (state) {
2779
            pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
2780
            vfio_pci_write_config(pdev, vdev->pm_cap + PCI_PM_CTRL, pmcsr, 2);
2781
            /* vfio handles the necessary delay here */
2782
            pmcsr = vfio_pci_read_config(pdev, vdev->pm_cap + PCI_PM_CTRL, 2);
2783
            state = pmcsr & PCI_PM_CTRL_STATE_MASK;
2784
            if (state) {
2785
                error_report("vfio: Unable to power on device, stuck in D%d\n",
2786
                             state);
2787
            }
2788
        }
2789
    }
2790

    
2791
    /*
2792
     * Stop any ongoing DMA by disconecting I/O, MMIO, and bus master.
2793
     * Also put INTx Disable in known state.
2794
     */
2795
    cmd = vfio_pci_read_config(pdev, PCI_COMMAND, 2);
2796
    cmd &= ~(PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
2797
             PCI_COMMAND_INTX_DISABLE);
2798
    vfio_pci_write_config(pdev, PCI_COMMAND, cmd, 2);
2799
}
2800

    
2801
static void vfio_pci_post_reset(VFIODevice *vdev)
2802
{
2803
    vfio_enable_intx(vdev);
2804
}
2805

    
2806
static bool vfio_pci_host_match(PCIHostDeviceAddress *host1,
2807
                                PCIHostDeviceAddress *host2)
2808
{
2809
    return (host1->domain == host2->domain && host1->bus == host2->bus &&
2810
            host1->slot == host2->slot && host1->function == host2->function);
2811
}
2812

    
2813
static int vfio_pci_hot_reset(VFIODevice *vdev, bool single)
2814
{
2815
    VFIOGroup *group;
2816
    struct vfio_pci_hot_reset_info *info;
2817
    struct vfio_pci_dependent_device *devices;
2818
    struct vfio_pci_hot_reset *reset;
2819
    int32_t *fds;
2820
    int ret, i, count;
2821
    bool multi = false;
2822

    
2823
    DPRINTF("%s(%04x:%02x:%02x.%x) %s\n", __func__, vdev->host.domain,
2824
            vdev->host.bus, vdev->host.slot, vdev->host.function,
2825
            single ? "one" : "multi");
2826

    
2827
    vfio_pci_pre_reset(vdev);
2828
    vdev->needs_reset = false;
2829

    
2830
    info = g_malloc0(sizeof(*info));
2831
    info->argsz = sizeof(*info);
2832

    
2833
    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2834
    if (ret && errno != ENOSPC) {
2835
        ret = -errno;
2836
        if (!vdev->has_pm_reset) {
2837
            error_report("vfio: Cannot reset device %04x:%02x:%02x.%x, "
2838
                         "no available reset mechanism.", vdev->host.domain,
2839
                         vdev->host.bus, vdev->host.slot, vdev->host.function);
2840
        }
2841
        goto out_single;
2842
    }
2843

    
2844
    count = info->count;
2845
    info = g_realloc(info, sizeof(*info) + (count * sizeof(*devices)));
2846
    info->argsz = sizeof(*info) + (count * sizeof(*devices));
2847
    devices = &info->devices[0];
2848

    
2849
    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_PCI_HOT_RESET_INFO, info);
2850
    if (ret) {
2851
        ret = -errno;
2852
        error_report("vfio: hot reset info failed: %m");
2853
        goto out_single;
2854
    }
2855

    
2856
    DPRINTF("%04x:%02x:%02x.%x: hot reset dependent devices:\n",
2857
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
2858
            vdev->host.function);
2859

    
2860
    /* Verify that we have all the groups required */
2861
    for (i = 0; i < info->count; i++) {
2862
        PCIHostDeviceAddress host;
2863
        VFIODevice *tmp;
2864

    
2865
        host.domain = devices[i].segment;
2866
        host.bus = devices[i].bus;
2867
        host.slot = PCI_SLOT(devices[i].devfn);
2868
        host.function = PCI_FUNC(devices[i].devfn);
2869

    
2870
        DPRINTF("\t%04x:%02x:%02x.%x group %d\n", host.domain,
2871
                host.bus, host.slot, host.function, devices[i].group_id);
2872

    
2873
        if (vfio_pci_host_match(&host, &vdev->host)) {
2874
            continue;
2875
        }
2876

    
2877
        QLIST_FOREACH(group, &group_list, next) {
2878
            if (group->groupid == devices[i].group_id) {
2879
                break;
2880
            }
2881
        }
2882

    
2883
        if (!group) {
2884
            if (!vdev->has_pm_reset) {
2885
                error_report("vfio: Cannot reset device %04x:%02x:%02x.%x, "
2886
                             "depends on group %d which is not owned.",
2887
                             vdev->host.domain, vdev->host.bus, vdev->host.slot,
2888
                             vdev->host.function, devices[i].group_id);
2889
            }
2890
            ret = -EPERM;
2891
            goto out;
2892
        }
2893

    
2894
        /* Prep dependent devices for reset and clear our marker. */
2895
        QLIST_FOREACH(tmp, &group->device_list, next) {
2896
            if (vfio_pci_host_match(&host, &tmp->host)) {
2897
                if (single) {
2898
                    DPRINTF("vfio: found another in-use device "
2899
                            "%04x:%02x:%02x.%x\n", host.domain, host.bus,
2900
                            host.slot, host.function);
2901
                    ret = -EINVAL;
2902
                    goto out_single;
2903
                }
2904
                vfio_pci_pre_reset(tmp);
2905
                tmp->needs_reset = false;
2906
                multi = true;
2907
                break;
2908
            }
2909
        }
2910
    }
2911

    
2912
    if (!single && !multi) {
2913
        DPRINTF("vfio: No other in-use devices for multi hot reset\n");
2914
        ret = -EINVAL;
2915
        goto out_single;
2916
    }
2917

    
2918
    /* Determine how many group fds need to be passed */
2919
    count = 0;
2920
    QLIST_FOREACH(group, &group_list, next) {
2921
        for (i = 0; i < info->count; i++) {
2922
            if (group->groupid == devices[i].group_id) {
2923
                count++;
2924
                break;
2925
            }
2926
        }
2927
    }
2928

    
2929
    reset = g_malloc0(sizeof(*reset) + (count * sizeof(*fds)));
2930
    reset->argsz = sizeof(*reset) + (count * sizeof(*fds));
2931
    fds = &reset->group_fds[0];
2932

    
2933
    /* Fill in group fds */
2934
    QLIST_FOREACH(group, &group_list, next) {
2935
        for (i = 0; i < info->count; i++) {
2936
            if (group->groupid == devices[i].group_id) {
2937
                fds[reset->count++] = group->fd;
2938
                break;
2939
            }
2940
        }
2941
    }
2942

    
2943
    /* Bus reset! */
2944
    ret = ioctl(vdev->fd, VFIO_DEVICE_PCI_HOT_RESET, reset);
2945
    g_free(reset);
2946

    
2947
    DPRINTF("%04x:%02x:%02x.%x hot reset: %s\n", vdev->host.domain,
2948
            vdev->host.bus, vdev->host.slot, vdev->host.function,
2949
            ret ? "%m" : "Success");
2950

    
2951
out:
2952
    /* Re-enable INTx on affected devices */
2953
    for (i = 0; i < info->count; i++) {
2954
        PCIHostDeviceAddress host;
2955
        VFIODevice *tmp;
2956

    
2957
        host.domain = devices[i].segment;
2958
        host.bus = devices[i].bus;
2959
        host.slot = PCI_SLOT(devices[i].devfn);
2960
        host.function = PCI_FUNC(devices[i].devfn);
2961

    
2962
        if (vfio_pci_host_match(&host, &vdev->host)) {
2963
            continue;
2964
        }
2965

    
2966
        QLIST_FOREACH(group, &group_list, next) {
2967
            if (group->groupid == devices[i].group_id) {
2968
                break;
2969
            }
2970
        }
2971

    
2972
        if (!group) {
2973
            break;
2974
        }
2975

    
2976
        QLIST_FOREACH(tmp, &group->device_list, next) {
2977
            if (vfio_pci_host_match(&host, &tmp->host)) {
2978
                vfio_pci_post_reset(tmp);
2979
                break;
2980
            }
2981
        }
2982
    }
2983
out_single:
2984
    vfio_pci_post_reset(vdev);
2985
    g_free(info);
2986

    
2987
    return ret;
2988
}
2989

    
2990
/*
2991
 * We want to differentiate hot reset of mulitple in-use devices vs hot reset
2992
 * of a single in-use device.  VFIO_DEVICE_RESET will already handle the case
2993
 * of doing hot resets when there is only a single device per bus.  The in-use
2994
 * here refers to how many VFIODevices are affected.  A hot reset that affects
2995
 * multiple devices, but only a single in-use device, means that we can call
2996
 * it from our bus ->reset() callback since the extent is effectively a single
2997
 * device.  This allows us to make use of it in the hotplug path.  When there
2998
 * are multiple in-use devices, we can only trigger the hot reset during a
2999
 * system reset and thus from our reset handler.  We separate _one vs _multi
3000
 * here so that we don't overlap and do a double reset on the system reset
3001
 * path where both our reset handler and ->reset() callback are used.  Calling
3002
 * _one() will only do a hot reset for the one in-use devices case, calling
3003
 * _multi() will do nothing if a _one() would have been sufficient.
3004
 */
3005
static int vfio_pci_hot_reset_one(VFIODevice *vdev)
3006
{
3007
    return vfio_pci_hot_reset(vdev, true);
3008
}
3009

    
3010
static int vfio_pci_hot_reset_multi(VFIODevice *vdev)
3011
{
3012
    return vfio_pci_hot_reset(vdev, false);
3013
}
3014

    
3015
static void vfio_pci_reset_handler(void *opaque)
3016
{
3017
    VFIOGroup *group;
3018
    VFIODevice *vdev;
3019

    
3020
    QLIST_FOREACH(group, &group_list, next) {
3021
        QLIST_FOREACH(vdev, &group->device_list, next) {
3022
            if (!vdev->reset_works || (!vdev->has_flr && vdev->has_pm_reset)) {
3023
                vdev->needs_reset = true;
3024
            }
3025
        }
3026
    }
3027

    
3028
    QLIST_FOREACH(group, &group_list, next) {
3029
        QLIST_FOREACH(vdev, &group->device_list, next) {
3030
            if (vdev->needs_reset) {
3031
                vfio_pci_hot_reset_multi(vdev);
3032
            }
3033
        }
3034
    }
3035
}
3036

    
3037
static int vfio_connect_container(VFIOGroup *group)
3038
{
3039
    VFIOContainer *container;
3040
    int ret, fd;
3041

    
3042
    if (group->container) {
3043
        return 0;
3044
    }
3045

    
3046
    QLIST_FOREACH(container, &container_list, next) {
3047
        if (!ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &container->fd)) {
3048
            group->container = container;
3049
            QLIST_INSERT_HEAD(&container->group_list, group, container_next);
3050
            return 0;
3051
        }
3052
    }
3053

    
3054
    fd = qemu_open("/dev/vfio/vfio", O_RDWR);
3055
    if (fd < 0) {
3056
        error_report("vfio: failed to open /dev/vfio/vfio: %m");
3057
        return -errno;
3058
    }
3059

    
3060
    ret = ioctl(fd, VFIO_GET_API_VERSION);
3061
    if (ret != VFIO_API_VERSION) {
3062
        error_report("vfio: supported vfio version: %d, "
3063
                     "reported version: %d", VFIO_API_VERSION, ret);
3064
        close(fd);
3065
        return -EINVAL;
3066
    }
3067

    
3068
    container = g_malloc0(sizeof(*container));
3069
    container->fd = fd;
3070

    
3071
    if (ioctl(fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU)) {
3072
        ret = ioctl(group->fd, VFIO_GROUP_SET_CONTAINER, &fd);
3073
        if (ret) {
3074
            error_report("vfio: failed to set group container: %m");
3075
            g_free(container);
3076
            close(fd);
3077
            return -errno;
3078
        }
3079

    
3080
        ret = ioctl(fd, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);
3081
        if (ret) {
3082
            error_report("vfio: failed to set iommu for container: %m");
3083
            g_free(container);
3084
            close(fd);
3085
            return -errno;
3086
        }
3087

    
3088
        container->iommu_data.listener = vfio_memory_listener;
3089
        container->iommu_data.release = vfio_listener_release;
3090

    
3091
        memory_listener_register(&container->iommu_data.listener, &address_space_memory);
3092
    } else {
3093
        error_report("vfio: No available IOMMU models");
3094
        g_free(container);
3095
        close(fd);
3096
        return -EINVAL;
3097
    }
3098

    
3099
    QLIST_INIT(&container->group_list);
3100
    QLIST_INSERT_HEAD(&container_list, container, next);
3101

    
3102
    group->container = container;
3103
    QLIST_INSERT_HEAD(&container->group_list, group, container_next);
3104

    
3105
    return 0;
3106
}
3107

    
3108
static void vfio_disconnect_container(VFIOGroup *group)
3109
{
3110
    VFIOContainer *container = group->container;
3111

    
3112
    if (ioctl(group->fd, VFIO_GROUP_UNSET_CONTAINER, &container->fd)) {
3113
        error_report("vfio: error disconnecting group %d from container",
3114
                     group->groupid);
3115
    }
3116

    
3117
    QLIST_REMOVE(group, container_next);
3118
    group->container = NULL;
3119

    
3120
    if (QLIST_EMPTY(&container->group_list)) {
3121
        if (container->iommu_data.release) {
3122
            container->iommu_data.release(container);
3123
        }
3124
        QLIST_REMOVE(container, next);
3125
        DPRINTF("vfio_disconnect_container: close container->fd\n");
3126
        close(container->fd);
3127
        g_free(container);
3128
    }
3129
}
3130

    
3131
static VFIOGroup *vfio_get_group(int groupid)
3132
{
3133
    VFIOGroup *group;
3134
    char path[32];
3135
    struct vfio_group_status status = { .argsz = sizeof(status) };
3136

    
3137
    QLIST_FOREACH(group, &group_list, next) {
3138
        if (group->groupid == groupid) {
3139
            return group;
3140
        }
3141
    }
3142

    
3143
    group = g_malloc0(sizeof(*group));
3144

    
3145
    snprintf(path, sizeof(path), "/dev/vfio/%d", groupid);
3146
    group->fd = qemu_open(path, O_RDWR);
3147
    if (group->fd < 0) {
3148
        error_report("vfio: error opening %s: %m", path);
3149
        g_free(group);
3150
        return NULL;
3151
    }
3152

    
3153
    if (ioctl(group->fd, VFIO_GROUP_GET_STATUS, &status)) {
3154
        error_report("vfio: error getting group status: %m");
3155
        close(group->fd);
3156
        g_free(group);
3157
        return NULL;
3158
    }
3159

    
3160
    if (!(status.flags & VFIO_GROUP_FLAGS_VIABLE)) {
3161
        error_report("vfio: error, group %d is not viable, please ensure "
3162
                     "all devices within the iommu_group are bound to their "
3163
                     "vfio bus driver.", groupid);
3164
        close(group->fd);
3165
        g_free(group);
3166
        return NULL;
3167
    }
3168

    
3169
    group->groupid = groupid;
3170
    QLIST_INIT(&group->device_list);
3171

    
3172
    if (vfio_connect_container(group)) {
3173
        error_report("vfio: failed to setup container for group %d", groupid);
3174
        close(group->fd);
3175
        g_free(group);
3176
        return NULL;
3177
    }
3178

    
3179
    if (QLIST_EMPTY(&group_list)) {
3180
        qemu_register_reset(vfio_pci_reset_handler, NULL);
3181
    }
3182

    
3183
    QLIST_INSERT_HEAD(&group_list, group, next);
3184

    
3185
    return group;
3186
}
3187

    
3188
static void vfio_put_group(VFIOGroup *group)
3189
{
3190
    if (!QLIST_EMPTY(&group->device_list)) {
3191
        return;
3192
    }
3193

    
3194
    vfio_disconnect_container(group);
3195
    QLIST_REMOVE(group, next);
3196
    DPRINTF("vfio_put_group: close group->fd\n");
3197
    close(group->fd);
3198
    g_free(group);
3199

    
3200
    if (QLIST_EMPTY(&group_list)) {
3201
        qemu_unregister_reset(vfio_pci_reset_handler, NULL);
3202
    }
3203
}
3204

    
3205
static int vfio_get_device(VFIOGroup *group, const char *name, VFIODevice *vdev)
3206
{
3207
    struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };
3208
    struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };
3209
    struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };
3210
    int ret, i;
3211

    
3212
    ret = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);
3213
    if (ret < 0) {
3214
        error_report("vfio: error getting device %s from group %d: %m",
3215
                     name, group->groupid);
3216
        error_printf("Verify all devices in group %d are bound to vfio-pci "
3217
                     "or pci-stub and not already in use\n", group->groupid);
3218
        return ret;
3219
    }
3220

    
3221
    vdev->fd = ret;
3222
    vdev->group = group;
3223
    QLIST_INSERT_HEAD(&group->device_list, vdev, next);
3224

    
3225
    /* Sanity check device */
3226
    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_INFO, &dev_info);
3227
    if (ret) {
3228
        error_report("vfio: error getting device info: %m");
3229
        goto error;
3230
    }
3231

    
3232
    DPRINTF("Device %s flags: %u, regions: %u, irgs: %u\n", name,
3233
            dev_info.flags, dev_info.num_regions, dev_info.num_irqs);
3234

    
3235
    if (!(dev_info.flags & VFIO_DEVICE_FLAGS_PCI)) {
3236
        error_report("vfio: Um, this isn't a PCI device");
3237
        goto error;
3238
    }
3239

    
3240
    vdev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);
3241

    
3242
    if (dev_info.num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {
3243
        error_report("vfio: unexpected number of io regions %u",
3244
                     dev_info.num_regions);
3245
        goto error;
3246
    }
3247

    
3248
    if (dev_info.num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {
3249
        error_report("vfio: unexpected number of irqs %u", dev_info.num_irqs);
3250
        goto error;
3251
    }
3252

    
3253
    for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {
3254
        reg_info.index = i;
3255

    
3256
        ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
3257
        if (ret) {
3258
            error_report("vfio: Error getting region %d info: %m", i);
3259
            goto error;
3260
        }
3261

    
3262
        DPRINTF("Device %s region %d:\n", name, i);
3263
        DPRINTF("  size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
3264
                (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
3265
                (unsigned long)reg_info.flags);
3266

    
3267
        vdev->bars[i].flags = reg_info.flags;
3268
        vdev->bars[i].size = reg_info.size;
3269
        vdev->bars[i].fd_offset = reg_info.offset;
3270
        vdev->bars[i].fd = vdev->fd;
3271
        vdev->bars[i].nr = i;
3272
        QLIST_INIT(&vdev->bars[i].quirks);
3273
    }
3274

    
3275
    reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;
3276

    
3277
    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);
3278
    if (ret) {
3279
        error_report("vfio: Error getting config info: %m");
3280
        goto error;
3281
    }
3282

    
3283
    DPRINTF("Device %s config:\n", name);
3284
    DPRINTF("  size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",
3285
            (unsigned long)reg_info.size, (unsigned long)reg_info.offset,
3286
            (unsigned long)reg_info.flags);
3287

    
3288
    vdev->config_size = reg_info.size;
3289
    if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {
3290
        vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;
3291
    }
3292
    vdev->config_offset = reg_info.offset;
3293

    
3294
    if ((vdev->features & VFIO_FEATURE_ENABLE_VGA) &&
3295
        dev_info.num_regions > VFIO_PCI_VGA_REGION_INDEX) {
3296
        struct vfio_region_info vga_info = {
3297
            .argsz = sizeof(vga_info),
3298
            .index = VFIO_PCI_VGA_REGION_INDEX,
3299
         };
3300

    
3301
        ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &vga_info);
3302
        if (ret) {
3303
            error_report(
3304
                "vfio: Device does not support requested feature x-vga");
3305
            goto error;
3306
        }
3307

    
3308
        if (!(vga_info.flags & VFIO_REGION_INFO_FLAG_READ) ||
3309
            !(vga_info.flags & VFIO_REGION_INFO_FLAG_WRITE) ||
3310
            vga_info.size < 0xbffff + 1) {
3311
            error_report("vfio: Unexpected VGA info, flags 0x%lx, size 0x%lx",
3312
                         (unsigned long)vga_info.flags,
3313
                         (unsigned long)vga_info.size);
3314
            goto error;
3315
        }
3316

    
3317
        vdev->vga.fd_offset = vga_info.offset;
3318
        vdev->vga.fd = vdev->fd;
3319

    
3320
        vdev->vga.region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;
3321
        vdev->vga.region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;
3322
        QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_MEM].quirks);
3323

    
3324
        vdev->vga.region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;
3325
        vdev->vga.region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;
3326
        QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].quirks);
3327

    
3328
        vdev->vga.region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;
3329
        vdev->vga.region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;
3330
        QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks);
3331

    
3332
        vdev->has_vga = true;
3333
    }
3334
    irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;
3335

    
3336
    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);
3337
    if (ret) {
3338
        /* This can fail for an old kernel or legacy PCI dev */
3339
        DPRINTF("VFIO_DEVICE_GET_IRQ_INFO failure: %m\n");
3340
        ret = 0;
3341
    } else if (irq_info.count == 1) {
3342
        vdev->pci_aer = true;
3343
    } else {
3344
        error_report("vfio: %04x:%02x:%02x.%x "
3345
                     "Could not enable error recovery for the device",
3346
                     vdev->host.domain, vdev->host.bus, vdev->host.slot,
3347
                     vdev->host.function);
3348
    }
3349

    
3350
error:
3351
    if (ret) {
3352
        QLIST_REMOVE(vdev, next);
3353
        vdev->group = NULL;
3354
        close(vdev->fd);
3355
    }
3356
    return ret;
3357
}
3358

    
3359
static void vfio_put_device(VFIODevice *vdev)
3360
{
3361
    QLIST_REMOVE(vdev, next);
3362
    vdev->group = NULL;
3363
    DPRINTF("vfio_put_device: close vdev->fd\n");
3364
    close(vdev->fd);
3365
    if (vdev->msix) {
3366
        g_free(vdev->msix);
3367
        vdev->msix = NULL;
3368
    }
3369
}
3370

    
3371
static void vfio_err_notifier_handler(void *opaque)
3372
{
3373
    VFIODevice *vdev = opaque;
3374

    
3375
    if (!event_notifier_test_and_clear(&vdev->err_notifier)) {
3376
        return;
3377
    }
3378

    
3379
    /*
3380
     * TBD. Retrieve the error details and decide what action
3381
     * needs to be taken. One of the actions could be to pass
3382
     * the error to the guest and have the guest driver recover
3383
     * from the error. This requires that PCIe capabilities be
3384
     * exposed to the guest. For now, we just terminate the
3385
     * guest to contain the error.
3386
     */
3387

    
3388
    error_report("%s(%04x:%02x:%02x.%x) Unrecoverable error detected.  "
3389
                 "Please collect any data possible and then kill the guest",
3390
                 __func__, vdev->host.domain, vdev->host.bus,
3391
                 vdev->host.slot, vdev->host.function);
3392

    
3393
    vm_stop(RUN_STATE_IO_ERROR);
3394
}
3395

    
3396
/*
3397
 * Registers error notifier for devices supporting error recovery.
3398
 * If we encounter a failure in this function, we report an error
3399
 * and continue after disabling error recovery support for the
3400
 * device.
3401
 */
3402
static void vfio_register_err_notifier(VFIODevice *vdev)
3403
{
3404
    int ret;
3405
    int argsz;
3406
    struct vfio_irq_set *irq_set;
3407
    int32_t *pfd;
3408

    
3409
    if (!vdev->pci_aer) {
3410
        return;
3411
    }
3412

    
3413
    if (event_notifier_init(&vdev->err_notifier, 0)) {
3414
        error_report("vfio: Unable to init event notifier for error detection");
3415
        vdev->pci_aer = false;
3416
        return;
3417
    }
3418

    
3419
    argsz = sizeof(*irq_set) + sizeof(*pfd);
3420

    
3421
    irq_set = g_malloc0(argsz);
3422
    irq_set->argsz = argsz;
3423
    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3424
                     VFIO_IRQ_SET_ACTION_TRIGGER;
3425
    irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
3426
    irq_set->start = 0;
3427
    irq_set->count = 1;
3428
    pfd = (int32_t *)&irq_set->data;
3429

    
3430
    *pfd = event_notifier_get_fd(&vdev->err_notifier);
3431
    qemu_set_fd_handler(*pfd, vfio_err_notifier_handler, NULL, vdev);
3432

    
3433
    ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
3434
    if (ret) {
3435
        error_report("vfio: Failed to set up error notification");
3436
        qemu_set_fd_handler(*pfd, NULL, NULL, vdev);
3437
        event_notifier_cleanup(&vdev->err_notifier);
3438
        vdev->pci_aer = false;
3439
    }
3440
    g_free(irq_set);
3441
}
3442

    
3443
static void vfio_unregister_err_notifier(VFIODevice *vdev)
3444
{
3445
    int argsz;
3446
    struct vfio_irq_set *irq_set;
3447
    int32_t *pfd;
3448
    int ret;
3449

    
3450
    if (!vdev->pci_aer) {
3451
        return;
3452
    }
3453

    
3454
    argsz = sizeof(*irq_set) + sizeof(*pfd);
3455

    
3456
    irq_set = g_malloc0(argsz);
3457
    irq_set->argsz = argsz;
3458
    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |
3459
                     VFIO_IRQ_SET_ACTION_TRIGGER;
3460
    irq_set->index = VFIO_PCI_ERR_IRQ_INDEX;
3461
    irq_set->start = 0;
3462
    irq_set->count = 1;
3463
    pfd = (int32_t *)&irq_set->data;
3464
    *pfd = -1;
3465

    
3466
    ret = ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, irq_set);
3467
    if (ret) {
3468
        error_report("vfio: Failed to de-assign error fd: %m");
3469
    }
3470
    g_free(irq_set);
3471
    qemu_set_fd_handler(event_notifier_get_fd(&vdev->err_notifier),
3472
                        NULL, NULL, vdev);
3473
    event_notifier_cleanup(&vdev->err_notifier);
3474
}
3475

    
3476
static int vfio_initfn(PCIDevice *pdev)
3477
{
3478
    VFIODevice *pvdev, *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
3479
    VFIOGroup *group;
3480
    char path[PATH_MAX], iommu_group_path[PATH_MAX], *group_name;
3481
    ssize_t len;
3482
    struct stat st;
3483
    int groupid;
3484
    int ret;
3485

    
3486
    /* Check that the host device exists */
3487
    snprintf(path, sizeof(path),
3488
             "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
3489
             vdev->host.domain, vdev->host.bus, vdev->host.slot,
3490
             vdev->host.function);
3491
    if (stat(path, &st) < 0) {
3492
        error_report("vfio: error: no such host device: %s", path);
3493
        return -errno;
3494
    }
3495

    
3496
    strncat(path, "iommu_group", sizeof(path) - strlen(path) - 1);
3497

    
3498
    len = readlink(path, iommu_group_path, PATH_MAX);
3499
    if (len <= 0) {
3500
        error_report("vfio: error no iommu_group for device");
3501
        return -errno;
3502
    }
3503

    
3504
    iommu_group_path[len] = 0;
3505
    group_name = basename(iommu_group_path);
3506

    
3507
    if (sscanf(group_name, "%d", &groupid) != 1) {
3508
        error_report("vfio: error reading %s: %m", path);
3509
        return -errno;
3510
    }
3511

    
3512
    DPRINTF("%s(%04x:%02x:%02x.%x) group %d\n", __func__, vdev->host.domain,
3513
            vdev->host.bus, vdev->host.slot, vdev->host.function, groupid);
3514

    
3515
    group = vfio_get_group(groupid);
3516
    if (!group) {
3517
        error_report("vfio: failed to get group %d", groupid);
3518
        return -ENOENT;
3519
    }
3520

    
3521
    snprintf(path, sizeof(path), "%04x:%02x:%02x.%01x",
3522
            vdev->host.domain, vdev->host.bus, vdev->host.slot,
3523
            vdev->host.function);
3524

    
3525
    QLIST_FOREACH(pvdev, &group->device_list, next) {
3526
        if (pvdev->host.domain == vdev->host.domain &&
3527
            pvdev->host.bus == vdev->host.bus &&
3528
            pvdev->host.slot == vdev->host.slot &&
3529
            pvdev->host.function == vdev->host.function) {
3530

    
3531
            error_report("vfio: error: device %s is already attached", path);
3532
            vfio_put_group(group);
3533
            return -EBUSY;
3534
        }
3535
    }
3536

    
3537
    ret = vfio_get_device(group, path, vdev);
3538
    if (ret) {
3539
        error_report("vfio: failed to get device %s", path);
3540
        vfio_put_group(group);
3541
        return ret;
3542
    }
3543

    
3544
    /* Get a copy of config space */
3545
    ret = pread(vdev->fd, vdev->pdev.config,
3546
                MIN(pci_config_size(&vdev->pdev), vdev->config_size),
3547
                vdev->config_offset);
3548
    if (ret < (int)MIN(pci_config_size(&vdev->pdev), vdev->config_size)) {
3549
        ret = ret < 0 ? -errno : -EFAULT;
3550
        error_report("vfio: Failed to read device config space");
3551
        goto out_put;
3552
    }
3553

    
3554
    /* vfio emulates a lot for us, but some bits need extra love */
3555
    vdev->emulated_config_bits = g_malloc0(vdev->config_size);
3556

    
3557
    /* QEMU can choose to expose the ROM or not */
3558
    memset(vdev->emulated_config_bits + PCI_ROM_ADDRESS, 0xff, 4);
3559

    
3560
    /* QEMU can change multi-function devices to single function, or reverse */
3561
    vdev->emulated_config_bits[PCI_HEADER_TYPE] =
3562
                                              PCI_HEADER_TYPE_MULTI_FUNCTION;
3563

    
3564
    /*
3565
     * Clear host resource mapping info.  If we choose not to register a
3566
     * BAR, such as might be the case with the option ROM, we can get
3567
     * confusing, unwritable, residual addresses from the host here.
3568
     */
3569
    memset(&vdev->pdev.config[PCI_BASE_ADDRESS_0], 0, 24);
3570
    memset(&vdev->pdev.config[PCI_ROM_ADDRESS], 0, 4);
3571

    
3572
    vfio_pci_size_rom(vdev);
3573

    
3574
    ret = vfio_early_setup_msix(vdev);
3575
    if (ret) {
3576
        goto out_put;
3577
    }
3578

    
3579
    vfio_map_bars(vdev);
3580

    
3581
    ret = vfio_add_capabilities(vdev);
3582
    if (ret) {
3583
        goto out_teardown;
3584
    }
3585

    
3586
    /* QEMU emulates all of MSI & MSIX */
3587
    if (pdev->cap_present & QEMU_PCI_CAP_MSIX) {
3588
        memset(vdev->emulated_config_bits + pdev->msix_cap, 0xff,
3589
               MSIX_CAP_LENGTH);
3590
    }
3591

    
3592
    if (pdev->cap_present & QEMU_PCI_CAP_MSI) {
3593
        memset(vdev->emulated_config_bits + pdev->msi_cap, 0xff,
3594
               vdev->msi_cap_size);
3595
    }
3596

    
3597
    if (vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1)) {
3598
        vdev->intx.mmap_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
3599
                                                  vfio_intx_mmap_enable, vdev);
3600
        pci_device_set_intx_routing_notifier(&vdev->pdev, vfio_update_irq);
3601
        ret = vfio_enable_intx(vdev);
3602
        if (ret) {
3603
            goto out_teardown;
3604
        }
3605
    }
3606

    
3607
    add_boot_device_path(vdev->bootindex, &pdev->qdev, NULL);
3608
    vfio_register_err_notifier(vdev);
3609

    
3610
    return 0;
3611

    
3612
out_teardown:
3613
    pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3614
    vfio_teardown_msi(vdev);
3615
    vfio_unmap_bars(vdev);
3616
out_put:
3617
    g_free(vdev->emulated_config_bits);
3618
    vfio_put_device(vdev);
3619
    vfio_put_group(group);
3620
    return ret;
3621
}
3622

    
3623
static void vfio_exitfn(PCIDevice *pdev)
3624
{
3625
    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
3626
    VFIOGroup *group = vdev->group;
3627

    
3628
    vfio_unregister_err_notifier(vdev);
3629
    pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);
3630
    vfio_disable_interrupts(vdev);
3631
    if (vdev->intx.mmap_timer) {
3632
        timer_free(vdev->intx.mmap_timer);
3633
    }
3634
    vfio_teardown_msi(vdev);
3635
    vfio_unmap_bars(vdev);
3636
    g_free(vdev->emulated_config_bits);
3637
    g_free(vdev->rom);
3638
    vfio_put_device(vdev);
3639
    vfio_put_group(group);
3640
}
3641

    
3642
static void vfio_pci_reset(DeviceState *dev)
3643
{
3644
    PCIDevice *pdev = DO_UPCAST(PCIDevice, qdev, dev);
3645
    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);
3646

    
3647
    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,
3648
            vdev->host.bus, vdev->host.slot, vdev->host.function);
3649

    
3650
    vfio_pci_pre_reset(vdev);
3651

    
3652
    if (vdev->reset_works && (vdev->has_flr || !vdev->has_pm_reset) &&
3653
        !ioctl(vdev->fd, VFIO_DEVICE_RESET)) {
3654
        DPRINTF("%04x:%02x:%02x.%x FLR/VFIO_DEVICE_RESET\n", vdev->host.domain,
3655
            vdev->host.bus, vdev->host.slot, vdev->host.function);
3656
        goto post_reset;
3657
    }
3658

    
3659
    /* See if we can do our own bus reset */
3660
    if (!vfio_pci_hot_reset_one(vdev)) {
3661
        goto post_reset;
3662
    }
3663

    
3664
    /* If nothing else works and the device supports PM reset, use it */
3665
    if (vdev->reset_works && vdev->has_pm_reset &&
3666
        !ioctl(vdev->fd, VFIO_DEVICE_RESET)) {
3667
        DPRINTF("%04x:%02x:%02x.%x PCI PM Reset\n", vdev->host.domain,
3668
            vdev->host.bus, vdev->host.slot, vdev->host.function);
3669
        goto post_reset;
3670
    }
3671

    
3672
post_reset:
3673
    vfio_pci_post_reset(vdev);
3674
}
3675

    
3676
static Property vfio_pci_dev_properties[] = {
3677
    DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIODevice, host),
3678
    DEFINE_PROP_UINT32("x-intx-mmap-timeout-ms", VFIODevice,
3679
                       intx.mmap_timeout, 1100),
3680
    DEFINE_PROP_BIT("x-vga", VFIODevice, features,
3681
                    VFIO_FEATURE_ENABLE_VGA_BIT, false),
3682
    DEFINE_PROP_INT32("bootindex", VFIODevice, bootindex, -1),
3683
    /*
3684
     * TODO - support passed fds... is this necessary?
3685
     * DEFINE_PROP_STRING("vfiofd", VFIODevice, vfiofd_name),
3686
     * DEFINE_PROP_STRING("vfiogroupfd, VFIODevice, vfiogroupfd_name),
3687
     */
3688
    DEFINE_PROP_END_OF_LIST(),
3689
};
3690

    
3691
static const VMStateDescription vfio_pci_vmstate = {
3692
    .name = "vfio-pci",
3693
    .unmigratable = 1,
3694
};
3695

    
3696
static void vfio_pci_dev_class_init(ObjectClass *klass, void *data)
3697
{
3698
    DeviceClass *dc = DEVICE_CLASS(klass);
3699
    PCIDeviceClass *pdc = PCI_DEVICE_CLASS(klass);
3700

    
3701
    dc->reset = vfio_pci_reset;
3702
    dc->props = vfio_pci_dev_properties;
3703
    dc->vmsd = &vfio_pci_vmstate;
3704
    dc->desc = "VFIO-based PCI device assignment";
3705
    set_bit(DEVICE_CATEGORY_MISC, dc->categories);
3706
    pdc->init = vfio_initfn;
3707
    pdc->exit = vfio_exitfn;
3708
    pdc->config_read = vfio_pci_read_config;
3709
    pdc->config_write = vfio_pci_write_config;
3710
    pdc->is_express = 1; /* We might be */
3711
}
3712

    
3713
static const TypeInfo vfio_pci_dev_info = {
3714
    .name = "vfio-pci",
3715
    .parent = TYPE_PCI_DEVICE,
3716
    .instance_size = sizeof(VFIODevice),
3717
    .class_init = vfio_pci_dev_class_init,
3718
};
3719

    
3720
static void register_vfio_pci_dev_type(void)
3721
{
3722
    type_register_static(&vfio_pci_dev_info);
3723
}
3724

    
3725
type_init(register_vfio_pci_dev_type)