pci-assign: Fix potential read beyond buffer on -EBUSY
[qemu/ar7.git] / hw / i386 / kvm / pci-assign.c
bloba825871d8a7c687fdf2feb2b1ae97fe17d89ce3b
1 /*
2 * Copyright (c) 2007, Neocleus Corporation.
4 * This work is licensed under the terms of the GNU GPL, version 2. See
5 * the COPYING file in the top-level directory.
8 * Assign a PCI device from the host to a guest VM.
10 * This implementation uses the classic device assignment interface of KVM
11 * and is only available on x86 hosts. It is expected to be obsoleted by VFIO
12 * based device assignment.
14 * Adapted for KVM (qemu-kvm) by Qumranet. QEMU version was based on qemu-kvm
15 * revision 4144fe9d48. See its repository for the history.
17 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
18 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
19 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
20 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
21 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
23 #include <stdio.h>
24 #include <unistd.h>
25 #include <sys/io.h>
26 #include <sys/mman.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include "hw/hw.h"
30 #include "hw/i386/pc.h"
31 #include "qemu/error-report.h"
32 #include "ui/console.h"
33 #include "hw/loader.h"
34 #include "monitor/monitor.h"
35 #include "qemu/range.h"
36 #include "sysemu/sysemu.h"
37 #include "hw/pci/pci.h"
38 #include "hw/pci/msi.h"
39 #include "kvm_i386.h"
41 #define MSIX_PAGE_SIZE 0x1000
43 /* From linux/ioport.h */
44 #define IORESOURCE_IO 0x00000100 /* Resource type */
45 #define IORESOURCE_MEM 0x00000200
46 #define IORESOURCE_IRQ 0x00000400
47 #define IORESOURCE_DMA 0x00000800
48 #define IORESOURCE_PREFETCH 0x00002000 /* No side effects */
49 #define IORESOURCE_MEM_64 0x00100000
51 //#define DEVICE_ASSIGNMENT_DEBUG
53 #ifdef DEVICE_ASSIGNMENT_DEBUG
54 #define DEBUG(fmt, ...) \
55 do { \
56 fprintf(stderr, "%s: " fmt, __func__ , __VA_ARGS__); \
57 } while (0)
58 #else
59 #define DEBUG(fmt, ...)
60 #endif
62 typedef struct PCIRegion {
63 int type; /* Memory or port I/O */
64 int valid;
65 uint64_t base_addr;
66 uint64_t size; /* size of the region */
67 int resource_fd;
68 } PCIRegion;
70 typedef struct PCIDevRegions {
71 uint8_t bus, dev, func; /* Bus inside domain, device and function */
72 int irq; /* IRQ number */
73 uint16_t region_number; /* number of active regions */
75 /* Port I/O or MMIO Regions */
76 PCIRegion regions[PCI_NUM_REGIONS - 1];
77 int config_fd;
78 } PCIDevRegions;
80 typedef struct AssignedDevRegion {
81 MemoryRegion container;
82 MemoryRegion real_iomem;
83 union {
84 uint8_t *r_virtbase; /* mmapped access address for memory regions */
85 uint32_t r_baseport; /* the base guest port for I/O regions */
86 } u;
87 pcibus_t e_size; /* emulated size of region in bytes */
88 pcibus_t r_size; /* real size of region in bytes */
89 PCIRegion *region;
90 } AssignedDevRegion;
92 #define ASSIGNED_DEVICE_PREFER_MSI_BIT 0
93 #define ASSIGNED_DEVICE_SHARE_INTX_BIT 1
95 #define ASSIGNED_DEVICE_PREFER_MSI_MASK (1 << ASSIGNED_DEVICE_PREFER_MSI_BIT)
96 #define ASSIGNED_DEVICE_SHARE_INTX_MASK (1 << ASSIGNED_DEVICE_SHARE_INTX_BIT)
98 typedef struct MSIXTableEntry {
99 uint32_t addr_lo;
100 uint32_t addr_hi;
101 uint32_t data;
102 uint32_t ctrl;
103 } MSIXTableEntry;
105 typedef enum AssignedIRQType {
106 ASSIGNED_IRQ_NONE = 0,
107 ASSIGNED_IRQ_INTX_HOST_INTX,
108 ASSIGNED_IRQ_INTX_HOST_MSI,
109 ASSIGNED_IRQ_MSI,
110 ASSIGNED_IRQ_MSIX
111 } AssignedIRQType;
113 typedef struct AssignedDevice {
114 PCIDevice dev;
115 PCIHostDeviceAddress host;
116 uint32_t dev_id;
117 uint32_t features;
118 int intpin;
119 AssignedDevRegion v_addrs[PCI_NUM_REGIONS - 1];
120 PCIDevRegions real_device;
121 PCIINTxRoute intx_route;
122 AssignedIRQType assigned_irq_type;
123 struct {
124 #define ASSIGNED_DEVICE_CAP_MSI (1 << 0)
125 #define ASSIGNED_DEVICE_CAP_MSIX (1 << 1)
126 uint32_t available;
127 #define ASSIGNED_DEVICE_MSI_ENABLED (1 << 0)
128 #define ASSIGNED_DEVICE_MSIX_ENABLED (1 << 1)
129 #define ASSIGNED_DEVICE_MSIX_MASKED (1 << 2)
130 uint32_t state;
131 } cap;
132 uint8_t emulate_config_read[PCI_CONFIG_SPACE_SIZE];
133 uint8_t emulate_config_write[PCI_CONFIG_SPACE_SIZE];
134 int msi_virq_nr;
135 int *msi_virq;
136 MSIXTableEntry *msix_table;
137 hwaddr msix_table_addr;
138 uint16_t msix_max;
139 MemoryRegion mmio;
140 char *configfd_name;
141 int32_t bootindex;
142 } AssignedDevice;
144 static void assigned_dev_update_irq_routing(PCIDevice *dev);
146 static void assigned_dev_load_option_rom(AssignedDevice *dev);
148 static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev);
150 static uint64_t assigned_dev_ioport_rw(AssignedDevRegion *dev_region,
151 hwaddr addr, int size,
152 uint64_t *data)
154 uint64_t val = 0;
155 int fd = dev_region->region->resource_fd;
157 if (data) {
158 DEBUG("pwrite data=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx
159 ", addr="TARGET_FMT_plx"\n", *data, size, addr, addr);
160 if (pwrite(fd, data, size, addr) != size) {
161 error_report("%s - pwrite failed %s", __func__, strerror(errno));
163 } else {
164 if (pread(fd, &val, size, addr) != size) {
165 error_report("%s - pread failed %s", __func__, strerror(errno));
166 val = (1UL << (size * 8)) - 1;
168 DEBUG("pread val=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx
169 ", addr=" TARGET_FMT_plx "\n", val, size, addr, addr);
171 return val;
174 static void assigned_dev_ioport_write(void *opaque, hwaddr addr,
175 uint64_t data, unsigned size)
177 assigned_dev_ioport_rw(opaque, addr, size, &data);
180 static uint64_t assigned_dev_ioport_read(void *opaque,
181 hwaddr addr, unsigned size)
183 return assigned_dev_ioport_rw(opaque, addr, size, NULL);
186 static uint32_t slow_bar_readb(void *opaque, hwaddr addr)
188 AssignedDevRegion *d = opaque;
189 uint8_t *in = d->u.r_virtbase + addr;
190 uint32_t r;
192 r = *in;
193 DEBUG("addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
195 return r;
198 static uint32_t slow_bar_readw(void *opaque, hwaddr addr)
200 AssignedDevRegion *d = opaque;
201 uint16_t *in = (uint16_t *)(d->u.r_virtbase + addr);
202 uint32_t r;
204 r = *in;
205 DEBUG("addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
207 return r;
210 static uint32_t slow_bar_readl(void *opaque, hwaddr addr)
212 AssignedDevRegion *d = opaque;
213 uint32_t *in = (uint32_t *)(d->u.r_virtbase + addr);
214 uint32_t r;
216 r = *in;
217 DEBUG("addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
219 return r;
222 static void slow_bar_writeb(void *opaque, hwaddr addr, uint32_t val)
224 AssignedDevRegion *d = opaque;
225 uint8_t *out = d->u.r_virtbase + addr;
227 DEBUG("addr=0x" TARGET_FMT_plx " val=0x%02x\n", addr, val);
228 *out = val;
231 static void slow_bar_writew(void *opaque, hwaddr addr, uint32_t val)
233 AssignedDevRegion *d = opaque;
234 uint16_t *out = (uint16_t *)(d->u.r_virtbase + addr);
236 DEBUG("addr=0x" TARGET_FMT_plx " val=0x%04x\n", addr, val);
237 *out = val;
240 static void slow_bar_writel(void *opaque, hwaddr addr, uint32_t val)
242 AssignedDevRegion *d = opaque;
243 uint32_t *out = (uint32_t *)(d->u.r_virtbase + addr);
245 DEBUG("addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, val);
246 *out = val;
249 static const MemoryRegionOps slow_bar_ops = {
250 .old_mmio = {
251 .read = { slow_bar_readb, slow_bar_readw, slow_bar_readl, },
252 .write = { slow_bar_writeb, slow_bar_writew, slow_bar_writel, },
254 .endianness = DEVICE_NATIVE_ENDIAN,
257 static void assigned_dev_iomem_setup(PCIDevice *pci_dev, int region_num,
258 pcibus_t e_size)
260 AssignedDevice *r_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
261 AssignedDevRegion *region = &r_dev->v_addrs[region_num];
262 PCIRegion *real_region = &r_dev->real_device.regions[region_num];
264 if (e_size > 0) {
265 memory_region_init(&region->container, OBJECT(pci_dev),
266 "assigned-dev-container", e_size);
267 memory_region_add_subregion(&region->container, 0, &region->real_iomem);
269 /* deal with MSI-X MMIO page */
270 if (real_region->base_addr <= r_dev->msix_table_addr &&
271 real_region->base_addr + real_region->size >
272 r_dev->msix_table_addr) {
273 uint64_t offset = r_dev->msix_table_addr - real_region->base_addr;
275 memory_region_add_subregion_overlap(&region->container,
276 offset,
277 &r_dev->mmio,
283 static const MemoryRegionOps assigned_dev_ioport_ops = {
284 .read = assigned_dev_ioport_read,
285 .write = assigned_dev_ioport_write,
286 .endianness = DEVICE_NATIVE_ENDIAN,
289 static void assigned_dev_ioport_setup(PCIDevice *pci_dev, int region_num,
290 pcibus_t size)
292 AssignedDevice *r_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
293 AssignedDevRegion *region = &r_dev->v_addrs[region_num];
295 region->e_size = size;
296 memory_region_init(&region->container, OBJECT(pci_dev),
297 "assigned-dev-container", size);
298 memory_region_init_io(&region->real_iomem, OBJECT(pci_dev),
299 &assigned_dev_ioport_ops, r_dev->v_addrs + region_num,
300 "assigned-dev-iomem", size);
301 memory_region_add_subregion(&region->container, 0, &region->real_iomem);
304 static uint32_t assigned_dev_pci_read(PCIDevice *d, int pos, int len)
306 AssignedDevice *pci_dev = DO_UPCAST(AssignedDevice, dev, d);
307 uint32_t val;
308 ssize_t ret;
309 int fd = pci_dev->real_device.config_fd;
311 again:
312 ret = pread(fd, &val, len, pos);
313 if (ret != len) {
314 if ((ret < 0) && (errno == EINTR || errno == EAGAIN)) {
315 goto again;
318 hw_error("pci read failed, ret = %zd errno = %d\n", ret, errno);
321 return val;
324 static uint8_t assigned_dev_pci_read_byte(PCIDevice *d, int pos)
326 return (uint8_t)assigned_dev_pci_read(d, pos, 1);
329 static void assigned_dev_pci_write(PCIDevice *d, int pos, uint32_t val, int len)
331 AssignedDevice *pci_dev = DO_UPCAST(AssignedDevice, dev, d);
332 ssize_t ret;
333 int fd = pci_dev->real_device.config_fd;
335 again:
336 ret = pwrite(fd, &val, len, pos);
337 if (ret != len) {
338 if ((ret < 0) && (errno == EINTR || errno == EAGAIN)) {
339 goto again;
342 hw_error("pci write failed, ret = %zd errno = %d\n", ret, errno);
346 static void assigned_dev_emulate_config_read(AssignedDevice *dev,
347 uint32_t offset, uint32_t len)
349 memset(dev->emulate_config_read + offset, 0xff, len);
352 static void assigned_dev_direct_config_read(AssignedDevice *dev,
353 uint32_t offset, uint32_t len)
355 memset(dev->emulate_config_read + offset, 0, len);
358 static void assigned_dev_direct_config_write(AssignedDevice *dev,
359 uint32_t offset, uint32_t len)
361 memset(dev->emulate_config_write + offset, 0, len);
364 static uint8_t pci_find_cap_offset(PCIDevice *d, uint8_t cap, uint8_t start)
366 int id;
367 int max_cap = 48;
368 int pos = start ? start : PCI_CAPABILITY_LIST;
369 int status;
371 status = assigned_dev_pci_read_byte(d, PCI_STATUS);
372 if ((status & PCI_STATUS_CAP_LIST) == 0) {
373 return 0;
376 while (max_cap--) {
377 pos = assigned_dev_pci_read_byte(d, pos);
378 if (pos < 0x40) {
379 break;
382 pos &= ~3;
383 id = assigned_dev_pci_read_byte(d, pos + PCI_CAP_LIST_ID);
385 if (id == 0xff) {
386 break;
388 if (id == cap) {
389 return pos;
392 pos += PCI_CAP_LIST_NEXT;
394 return 0;
397 static int assigned_dev_register_regions(PCIRegion *io_regions,
398 unsigned long regions_num,
399 AssignedDevice *pci_dev)
401 uint32_t i;
402 PCIRegion *cur_region = io_regions;
404 for (i = 0; i < regions_num; i++, cur_region++) {
405 if (!cur_region->valid) {
406 continue;
409 /* handle memory io regions */
410 if (cur_region->type & IORESOURCE_MEM) {
411 int t = PCI_BASE_ADDRESS_SPACE_MEMORY;
412 if (cur_region->type & IORESOURCE_PREFETCH) {
413 t |= PCI_BASE_ADDRESS_MEM_PREFETCH;
415 if (cur_region->type & IORESOURCE_MEM_64) {
416 t |= PCI_BASE_ADDRESS_MEM_TYPE_64;
419 /* map physical memory */
420 pci_dev->v_addrs[i].u.r_virtbase = mmap(NULL, cur_region->size,
421 PROT_WRITE | PROT_READ,
422 MAP_SHARED,
423 cur_region->resource_fd,
424 (off_t)0);
426 if (pci_dev->v_addrs[i].u.r_virtbase == MAP_FAILED) {
427 pci_dev->v_addrs[i].u.r_virtbase = NULL;
428 error_report("%s: Error: Couldn't mmap 0x%" PRIx64 "!",
429 __func__, cur_region->base_addr);
430 return -1;
433 pci_dev->v_addrs[i].r_size = cur_region->size;
434 pci_dev->v_addrs[i].e_size = 0;
436 /* add offset */
437 pci_dev->v_addrs[i].u.r_virtbase +=
438 (cur_region->base_addr & 0xFFF);
440 if (cur_region->size & 0xFFF) {
441 error_report("PCI region %d at address 0x%" PRIx64 " has "
442 "size 0x%" PRIx64 ", which is not a multiple of "
443 "4K. You might experience some performance hit "
444 "due to that.",
445 i, cur_region->base_addr, cur_region->size);
446 memory_region_init_io(&pci_dev->v_addrs[i].real_iomem,
447 OBJECT(pci_dev), &slow_bar_ops,
448 &pci_dev->v_addrs[i],
449 "assigned-dev-slow-bar",
450 cur_region->size);
451 } else {
452 void *virtbase = pci_dev->v_addrs[i].u.r_virtbase;
453 char name[32];
454 snprintf(name, sizeof(name), "%s.bar%d",
455 object_get_typename(OBJECT(pci_dev)), i);
456 memory_region_init_ram_ptr(&pci_dev->v_addrs[i].real_iomem,
457 OBJECT(pci_dev), name,
458 cur_region->size, virtbase);
459 vmstate_register_ram(&pci_dev->v_addrs[i].real_iomem,
460 &pci_dev->dev.qdev);
463 assigned_dev_iomem_setup(&pci_dev->dev, i, cur_region->size);
464 pci_register_bar((PCIDevice *) pci_dev, i, t,
465 &pci_dev->v_addrs[i].container);
466 continue;
467 } else {
468 /* handle port io regions */
469 uint32_t val;
470 int ret;
472 /* Test kernel support for ioport resource read/write. Old
473 * kernels return EIO. New kernels only allow 1/2/4 byte reads
474 * so should return EINVAL for a 3 byte read */
475 ret = pread(pci_dev->v_addrs[i].region->resource_fd, &val, 3, 0);
476 if (ret >= 0) {
477 error_report("Unexpected return from I/O port read: %d", ret);
478 abort();
479 } else if (errno != EINVAL) {
480 error_report("Kernel doesn't support ioport resource "
481 "access, hiding this region.");
482 close(pci_dev->v_addrs[i].region->resource_fd);
483 cur_region->valid = 0;
484 continue;
487 pci_dev->v_addrs[i].u.r_baseport = cur_region->base_addr;
488 pci_dev->v_addrs[i].r_size = cur_region->size;
489 pci_dev->v_addrs[i].e_size = 0;
491 assigned_dev_ioport_setup(&pci_dev->dev, i, cur_region->size);
492 pci_register_bar((PCIDevice *) pci_dev, i,
493 PCI_BASE_ADDRESS_SPACE_IO,
494 &pci_dev->v_addrs[i].container);
498 /* success */
499 return 0;
502 static int get_real_id(const char *devpath, const char *idname, uint16_t *val)
504 FILE *f;
505 char name[128];
506 long id;
508 snprintf(name, sizeof(name), "%s%s", devpath, idname);
509 f = fopen(name, "r");
510 if (f == NULL) {
511 error_report("%s: %s: %m", __func__, name);
512 return -1;
514 if (fscanf(f, "%li\n", &id) == 1) {
515 *val = id;
516 } else {
517 fclose(f);
518 return -1;
520 fclose(f);
522 return 0;
525 static int get_real_vendor_id(const char *devpath, uint16_t *val)
527 return get_real_id(devpath, "vendor", val);
530 static int get_real_device_id(const char *devpath, uint16_t *val)
532 return get_real_id(devpath, "device", val);
535 static int get_real_device(AssignedDevice *pci_dev)
537 char dir[128], name[128];
538 int fd, r = 0, v;
539 FILE *f;
540 uint64_t start, end, size, flags;
541 uint16_t id;
542 PCIRegion *rp;
543 PCIDevRegions *dev = &pci_dev->real_device;
545 dev->region_number = 0;
547 snprintf(dir, sizeof(dir), "/sys/bus/pci/devices/%04x:%02x:%02x.%x/",
548 pci_dev->host.domain, pci_dev->host.bus,
549 pci_dev->host.slot, pci_dev->host.function);
551 snprintf(name, sizeof(name), "%sconfig", dir);
553 if (pci_dev->configfd_name && *pci_dev->configfd_name) {
554 dev->config_fd = monitor_handle_fd_param(cur_mon, pci_dev->configfd_name);
555 if (dev->config_fd < 0) {
556 return 1;
558 } else {
559 dev->config_fd = open(name, O_RDWR);
561 if (dev->config_fd == -1) {
562 error_report("%s: %s: %m", __func__, name);
563 return 1;
566 again:
567 r = read(dev->config_fd, pci_dev->dev.config,
568 pci_config_size(&pci_dev->dev));
569 if (r < 0) {
570 if (errno == EINTR || errno == EAGAIN) {
571 goto again;
573 error_report("%s: read failed, errno = %d", __func__, errno);
576 /* Restore or clear multifunction, this is always controlled by qemu */
577 if (pci_dev->dev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
578 pci_dev->dev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
579 } else {
580 pci_dev->dev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
583 /* Clear host resource mapping info. If we choose not to register a
584 * BAR, such as might be the case with the option ROM, we can get
585 * confusing, unwritable, residual addresses from the host here. */
586 memset(&pci_dev->dev.config[PCI_BASE_ADDRESS_0], 0, 24);
587 memset(&pci_dev->dev.config[PCI_ROM_ADDRESS], 0, 4);
589 snprintf(name, sizeof(name), "%sresource", dir);
591 f = fopen(name, "r");
592 if (f == NULL) {
593 error_report("%s: %s: %m", __func__, name);
594 return 1;
597 for (r = 0; r < PCI_ROM_SLOT; r++) {
598 if (fscanf(f, "%" SCNi64 " %" SCNi64 " %" SCNi64 "\n",
599 &start, &end, &flags) != 3) {
600 break;
603 rp = dev->regions + r;
604 rp->valid = 0;
605 rp->resource_fd = -1;
606 size = end - start + 1;
607 flags &= IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_PREFETCH
608 | IORESOURCE_MEM_64;
609 if (size == 0 || (flags & ~IORESOURCE_PREFETCH) == 0) {
610 continue;
612 if (flags & IORESOURCE_MEM) {
613 flags &= ~IORESOURCE_IO;
614 } else {
615 flags &= ~IORESOURCE_PREFETCH;
617 snprintf(name, sizeof(name), "%sresource%d", dir, r);
618 fd = open(name, O_RDWR);
619 if (fd == -1) {
620 continue;
622 rp->resource_fd = fd;
624 rp->type = flags;
625 rp->valid = 1;
626 rp->base_addr = start;
627 rp->size = size;
628 pci_dev->v_addrs[r].region = rp;
629 DEBUG("region %d size %" PRIu64 " start 0x%" PRIx64
630 " type %d resource_fd %d\n",
631 r, rp->size, start, rp->type, rp->resource_fd);
634 fclose(f);
636 /* read and fill vendor ID */
637 v = get_real_vendor_id(dir, &id);
638 if (v) {
639 return 1;
641 pci_dev->dev.config[0] = id & 0xff;
642 pci_dev->dev.config[1] = (id & 0xff00) >> 8;
644 /* read and fill device ID */
645 v = get_real_device_id(dir, &id);
646 if (v) {
647 return 1;
649 pci_dev->dev.config[2] = id & 0xff;
650 pci_dev->dev.config[3] = (id & 0xff00) >> 8;
652 pci_word_test_and_clear_mask(pci_dev->emulate_config_write + PCI_COMMAND,
653 PCI_COMMAND_MASTER | PCI_COMMAND_INTX_DISABLE);
655 dev->region_number = r;
656 return 0;
659 static void free_msi_virqs(AssignedDevice *dev)
661 int i;
663 for (i = 0; i < dev->msi_virq_nr; i++) {
664 if (dev->msi_virq[i] >= 0) {
665 kvm_irqchip_release_virq(kvm_state, dev->msi_virq[i]);
666 dev->msi_virq[i] = -1;
669 g_free(dev->msi_virq);
670 dev->msi_virq = NULL;
671 dev->msi_virq_nr = 0;
674 static void free_assigned_device(AssignedDevice *dev)
676 int i;
678 if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
679 assigned_dev_unregister_msix_mmio(dev);
681 for (i = 0; i < dev->real_device.region_number; i++) {
682 PCIRegion *pci_region = &dev->real_device.regions[i];
683 AssignedDevRegion *region = &dev->v_addrs[i];
685 if (!pci_region->valid) {
686 continue;
688 if (pci_region->type & IORESOURCE_IO) {
689 if (region->u.r_baseport) {
690 memory_region_del_subregion(&region->container,
691 &region->real_iomem);
692 memory_region_destroy(&region->real_iomem);
693 memory_region_destroy(&region->container);
695 } else if (pci_region->type & IORESOURCE_MEM) {
696 if (region->u.r_virtbase) {
697 memory_region_del_subregion(&region->container,
698 &region->real_iomem);
700 /* Remove MSI-X table subregion */
701 if (pci_region->base_addr <= dev->msix_table_addr &&
702 pci_region->base_addr + pci_region->size >
703 dev->msix_table_addr) {
704 memory_region_del_subregion(&region->container,
705 &dev->mmio);
708 memory_region_destroy(&region->real_iomem);
709 memory_region_destroy(&region->container);
710 if (munmap(region->u.r_virtbase,
711 (pci_region->size + 0xFFF) & 0xFFFFF000)) {
712 error_report("Failed to unmap assigned device region: %s",
713 strerror(errno));
717 if (pci_region->resource_fd >= 0) {
718 close(pci_region->resource_fd);
722 if (dev->real_device.config_fd >= 0) {
723 close(dev->real_device.config_fd);
726 free_msi_virqs(dev);
729 static void assign_failed_examine(AssignedDevice *dev)
731 char name[PATH_MAX], dir[PATH_MAX], driver[PATH_MAX] = {}, *ns;
732 uint16_t vendor_id, device_id;
733 int r;
735 snprintf(dir, sizeof(dir), "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
736 dev->host.domain, dev->host.bus, dev->host.slot,
737 dev->host.function);
739 snprintf(name, sizeof(name), "%sdriver", dir);
741 r = readlink(name, driver, sizeof(driver));
742 if ((r <= 0) || r >= sizeof(driver)) {
743 goto fail;
746 driver[r] = 0;
747 ns = strrchr(driver, '/');
748 if (!ns) {
749 goto fail;
752 ns++;
754 if (get_real_vendor_id(dir, &vendor_id) ||
755 get_real_device_id(dir, &device_id)) {
756 goto fail;
759 error_printf("*** The driver '%s' is occupying your device "
760 "%04x:%02x:%02x.%x.\n"
761 "***\n"
762 "*** You can try the following commands to free it:\n"
763 "***\n"
764 "*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub/new_id\n"
765 "*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/%s/unbind\n"
766 "*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/"
767 "pci-stub/bind\n"
768 "*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub/remove_id\n"
769 "***",
770 ns, dev->host.domain, dev->host.bus, dev->host.slot,
771 dev->host.function, vendor_id, device_id,
772 dev->host.domain, dev->host.bus, dev->host.slot, dev->host.function,
773 ns, dev->host.domain, dev->host.bus, dev->host.slot,
774 dev->host.function, vendor_id, device_id);
776 return;
778 fail:
779 error_report("Couldn't find out why.");
782 static int assign_device(AssignedDevice *dev)
784 uint32_t flags = KVM_DEV_ASSIGN_ENABLE_IOMMU;
785 int r;
787 /* Only pass non-zero PCI segment to capable module */
788 if (!kvm_check_extension(kvm_state, KVM_CAP_PCI_SEGMENT) &&
789 dev->host.domain) {
790 error_report("Can't assign device inside non-zero PCI segment "
791 "as this KVM module doesn't support it.");
792 return -ENODEV;
795 if (!kvm_check_extension(kvm_state, KVM_CAP_IOMMU)) {
796 error_report("No IOMMU found. Unable to assign device \"%s\"",
797 dev->dev.qdev.id);
798 return -ENODEV;
801 if (dev->features & ASSIGNED_DEVICE_SHARE_INTX_MASK &&
802 kvm_has_intx_set_mask()) {
803 flags |= KVM_DEV_ASSIGN_PCI_2_3;
806 r = kvm_device_pci_assign(kvm_state, &dev->host, flags, &dev->dev_id);
807 if (r < 0) {
808 error_report("Failed to assign device \"%s\" : %s",
809 dev->dev.qdev.id, strerror(-r));
811 switch (r) {
812 case -EBUSY:
813 assign_failed_examine(dev);
814 break;
815 default:
816 break;
819 return r;
822 static bool check_irqchip_in_kernel(void)
824 if (kvm_irqchip_in_kernel()) {
825 return true;
827 error_report("pci-assign: error: requires KVM with in-kernel irqchip "
828 "enabled");
829 return false;
832 static int assign_intx(AssignedDevice *dev)
834 AssignedIRQType new_type;
835 PCIINTxRoute intx_route;
836 bool intx_host_msi;
837 int r;
839 /* Interrupt PIN 0 means don't use INTx */
840 if (assigned_dev_pci_read_byte(&dev->dev, PCI_INTERRUPT_PIN) == 0) {
841 pci_device_set_intx_routing_notifier(&dev->dev, NULL);
842 return 0;
845 if (!check_irqchip_in_kernel()) {
846 return -ENOTSUP;
849 pci_device_set_intx_routing_notifier(&dev->dev,
850 assigned_dev_update_irq_routing);
852 intx_route = pci_device_route_intx_to_irq(&dev->dev, dev->intpin);
853 assert(intx_route.mode != PCI_INTX_INVERTED);
855 if (!pci_intx_route_changed(&dev->intx_route, &intx_route)) {
856 return 0;
859 switch (dev->assigned_irq_type) {
860 case ASSIGNED_IRQ_INTX_HOST_INTX:
861 case ASSIGNED_IRQ_INTX_HOST_MSI:
862 intx_host_msi = dev->assigned_irq_type == ASSIGNED_IRQ_INTX_HOST_MSI;
863 r = kvm_device_intx_deassign(kvm_state, dev->dev_id, intx_host_msi);
864 break;
865 case ASSIGNED_IRQ_MSI:
866 r = kvm_device_msi_deassign(kvm_state, dev->dev_id);
867 break;
868 case ASSIGNED_IRQ_MSIX:
869 r = kvm_device_msix_deassign(kvm_state, dev->dev_id);
870 break;
871 default:
872 r = 0;
873 break;
875 if (r) {
876 perror("assign_intx: deassignment of previous interrupt failed");
878 dev->assigned_irq_type = ASSIGNED_IRQ_NONE;
880 if (intx_route.mode == PCI_INTX_DISABLED) {
881 dev->intx_route = intx_route;
882 return 0;
885 retry:
886 if (dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK &&
887 dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
888 intx_host_msi = true;
889 new_type = ASSIGNED_IRQ_INTX_HOST_MSI;
890 } else {
891 intx_host_msi = false;
892 new_type = ASSIGNED_IRQ_INTX_HOST_INTX;
895 r = kvm_device_intx_assign(kvm_state, dev->dev_id, intx_host_msi,
896 intx_route.irq);
897 if (r < 0) {
898 if (r == -EIO && !(dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK) &&
899 dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
900 /* Retry with host-side MSI. There might be an IRQ conflict and
901 * either the kernel or the device doesn't support sharing. */
902 error_report("Host-side INTx sharing not supported, "
903 "using MSI instead");
904 error_printf("Some devices do not work properly in this mode.\n");
905 dev->features |= ASSIGNED_DEVICE_PREFER_MSI_MASK;
906 goto retry;
908 error_report("Failed to assign irq for \"%s\": %s",
909 dev->dev.qdev.id, strerror(-r));
910 error_report("Perhaps you are assigning a device "
911 "that shares an IRQ with another device?");
912 return r;
915 dev->intx_route = intx_route;
916 dev->assigned_irq_type = new_type;
917 return r;
920 static void deassign_device(AssignedDevice *dev)
922 int r;
924 r = kvm_device_pci_deassign(kvm_state, dev->dev_id);
925 assert(r == 0);
928 /* The pci config space got updated. Check if irq numbers have changed
929 * for our devices
931 static void assigned_dev_update_irq_routing(PCIDevice *dev)
933 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, dev);
934 Error *err = NULL;
935 int r;
937 r = assign_intx(assigned_dev);
938 if (r < 0) {
939 qdev_unplug(&dev->qdev, &err);
940 assert(!err);
944 static void assigned_dev_update_msi(PCIDevice *pci_dev)
946 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
947 uint8_t ctrl_byte = pci_get_byte(pci_dev->config + pci_dev->msi_cap +
948 PCI_MSI_FLAGS);
949 int r;
951 /* Some guests gratuitously disable MSI even if they're not using it,
952 * try to catch this by only deassigning irqs if the guest is using
953 * MSI or intends to start. */
954 if (assigned_dev->assigned_irq_type == ASSIGNED_IRQ_MSI ||
955 (ctrl_byte & PCI_MSI_FLAGS_ENABLE)) {
956 r = kvm_device_msi_deassign(kvm_state, assigned_dev->dev_id);
957 /* -ENXIO means no assigned irq */
958 if (r && r != -ENXIO) {
959 perror("assigned_dev_update_msi: deassign irq");
962 free_msi_virqs(assigned_dev);
964 assigned_dev->assigned_irq_type = ASSIGNED_IRQ_NONE;
965 pci_device_set_intx_routing_notifier(pci_dev, NULL);
968 if (ctrl_byte & PCI_MSI_FLAGS_ENABLE) {
969 MSIMessage msg = msi_get_message(pci_dev, 0);
970 int virq;
972 virq = kvm_irqchip_add_msi_route(kvm_state, msg);
973 if (virq < 0) {
974 perror("assigned_dev_update_msi: kvm_irqchip_add_msi_route");
975 return;
978 assigned_dev->msi_virq = g_malloc(sizeof(*assigned_dev->msi_virq));
979 assigned_dev->msi_virq_nr = 1;
980 assigned_dev->msi_virq[0] = virq;
981 if (kvm_device_msi_assign(kvm_state, assigned_dev->dev_id, virq) < 0) {
982 perror("assigned_dev_update_msi: kvm_device_msi_assign");
985 assigned_dev->intx_route.mode = PCI_INTX_DISABLED;
986 assigned_dev->intx_route.irq = -1;
987 assigned_dev->assigned_irq_type = ASSIGNED_IRQ_MSI;
988 } else {
989 assign_intx(assigned_dev);
993 static void assigned_dev_update_msi_msg(PCIDevice *pci_dev)
995 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
996 uint8_t ctrl_byte = pci_get_byte(pci_dev->config + pci_dev->msi_cap +
997 PCI_MSI_FLAGS);
999 if (assigned_dev->assigned_irq_type != ASSIGNED_IRQ_MSI ||
1000 !(ctrl_byte & PCI_MSI_FLAGS_ENABLE)) {
1001 return;
1004 kvm_irqchip_update_msi_route(kvm_state, assigned_dev->msi_virq[0],
1005 msi_get_message(pci_dev, 0));
1008 static bool assigned_dev_msix_masked(MSIXTableEntry *entry)
1010 return (entry->ctrl & cpu_to_le32(0x1)) != 0;
1014 * When MSI-X is first enabled the vector table typically has all the
1015 * vectors masked, so we can't use that as the obvious test to figure out
1016 * how many vectors to initially enable. Instead we look at the data field
1017 * because this is what worked for pci-assign for a long time. This makes
1018 * sure the physical MSI-X state tracks the guest's view, which is important
1019 * for some VF/PF and PF/fw communication channels.
1021 static bool assigned_dev_msix_skipped(MSIXTableEntry *entry)
1023 return !entry->data;
1026 static int assigned_dev_update_msix_mmio(PCIDevice *pci_dev)
1028 AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1029 uint16_t entries_nr = 0;
1030 int i, r = 0;
1031 MSIXTableEntry *entry = adev->msix_table;
1032 MSIMessage msg;
1034 /* Get the usable entry number for allocating */
1035 for (i = 0; i < adev->msix_max; i++, entry++) {
1036 if (assigned_dev_msix_skipped(entry)) {
1037 continue;
1039 entries_nr++;
1042 DEBUG("MSI-X entries: %d\n", entries_nr);
1044 /* It's valid to enable MSI-X with all entries masked */
1045 if (!entries_nr) {
1046 return 0;
1049 r = kvm_device_msix_init_vectors(kvm_state, adev->dev_id, entries_nr);
1050 if (r != 0) {
1051 error_report("fail to set MSI-X entry number for MSIX! %s",
1052 strerror(-r));
1053 return r;
1056 free_msi_virqs(adev);
1058 adev->msi_virq_nr = adev->msix_max;
1059 adev->msi_virq = g_malloc(adev->msix_max * sizeof(*adev->msi_virq));
1061 entry = adev->msix_table;
1062 for (i = 0; i < adev->msix_max; i++, entry++) {
1063 adev->msi_virq[i] = -1;
1065 if (assigned_dev_msix_skipped(entry)) {
1066 continue;
1069 msg.address = entry->addr_lo | ((uint64_t)entry->addr_hi << 32);
1070 msg.data = entry->data;
1071 r = kvm_irqchip_add_msi_route(kvm_state, msg);
1072 if (r < 0) {
1073 return r;
1075 adev->msi_virq[i] = r;
1077 DEBUG("MSI-X vector %d, gsi %d, addr %08x_%08x, data %08x\n", i,
1078 r, entry->addr_hi, entry->addr_lo, entry->data);
1080 r = kvm_device_msix_set_vector(kvm_state, adev->dev_id, i,
1081 adev->msi_virq[i]);
1082 if (r) {
1083 error_report("fail to set MSI-X entry! %s", strerror(-r));
1084 break;
1088 return r;
1091 static void assigned_dev_update_msix(PCIDevice *pci_dev)
1093 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1094 uint16_t ctrl_word = pci_get_word(pci_dev->config + pci_dev->msix_cap +
1095 PCI_MSIX_FLAGS);
1096 int r;
1098 /* Some guests gratuitously disable MSIX even if they're not using it,
1099 * try to catch this by only deassigning irqs if the guest is using
1100 * MSIX or intends to start. */
1101 if ((assigned_dev->assigned_irq_type == ASSIGNED_IRQ_MSIX) ||
1102 (ctrl_word & PCI_MSIX_FLAGS_ENABLE)) {
1103 r = kvm_device_msix_deassign(kvm_state, assigned_dev->dev_id);
1104 /* -ENXIO means no assigned irq */
1105 if (r && r != -ENXIO) {
1106 perror("assigned_dev_update_msix: deassign irq");
1109 free_msi_virqs(assigned_dev);
1111 assigned_dev->assigned_irq_type = ASSIGNED_IRQ_NONE;
1112 pci_device_set_intx_routing_notifier(pci_dev, NULL);
1115 if (ctrl_word & PCI_MSIX_FLAGS_ENABLE) {
1116 if (assigned_dev_update_msix_mmio(pci_dev) < 0) {
1117 perror("assigned_dev_update_msix_mmio");
1118 return;
1121 if (assigned_dev->msi_virq_nr > 0) {
1122 if (kvm_device_msix_assign(kvm_state, assigned_dev->dev_id) < 0) {
1123 perror("assigned_dev_enable_msix: assign irq");
1124 return;
1127 assigned_dev->intx_route.mode = PCI_INTX_DISABLED;
1128 assigned_dev->intx_route.irq = -1;
1129 assigned_dev->assigned_irq_type = ASSIGNED_IRQ_MSIX;
1130 } else {
1131 assign_intx(assigned_dev);
1135 static uint32_t assigned_dev_pci_read_config(PCIDevice *pci_dev,
1136 uint32_t address, int len)
1138 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1139 uint32_t virt_val = pci_default_read_config(pci_dev, address, len);
1140 uint32_t real_val, emulate_mask, full_emulation_mask;
1142 emulate_mask = 0;
1143 memcpy(&emulate_mask, assigned_dev->emulate_config_read + address, len);
1144 emulate_mask = le32_to_cpu(emulate_mask);
1146 full_emulation_mask = 0xffffffff >> (32 - len * 8);
1148 if (emulate_mask != full_emulation_mask) {
1149 real_val = assigned_dev_pci_read(pci_dev, address, len);
1150 return (virt_val & emulate_mask) | (real_val & ~emulate_mask);
1151 } else {
1152 return virt_val;
1156 static void assigned_dev_pci_write_config(PCIDevice *pci_dev, uint32_t address,
1157 uint32_t val, int len)
1159 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1160 uint16_t old_cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1161 uint32_t emulate_mask, full_emulation_mask;
1162 int ret;
1164 pci_default_write_config(pci_dev, address, val, len);
1166 if (kvm_has_intx_set_mask() &&
1167 range_covers_byte(address, len, PCI_COMMAND + 1)) {
1168 bool intx_masked = (pci_get_word(pci_dev->config + PCI_COMMAND) &
1169 PCI_COMMAND_INTX_DISABLE);
1171 if (intx_masked != !!(old_cmd & PCI_COMMAND_INTX_DISABLE)) {
1172 ret = kvm_device_intx_set_mask(kvm_state, assigned_dev->dev_id,
1173 intx_masked);
1174 if (ret) {
1175 perror("assigned_dev_pci_write_config: set intx mask");
1179 if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
1180 if (range_covers_byte(address, len,
1181 pci_dev->msi_cap + PCI_MSI_FLAGS)) {
1182 assigned_dev_update_msi(pci_dev);
1183 } else if (ranges_overlap(address, len, /* 32bit MSI only */
1184 pci_dev->msi_cap + PCI_MSI_ADDRESS_LO, 6)) {
1185 assigned_dev_update_msi_msg(pci_dev);
1188 if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1189 if (range_covers_byte(address, len,
1190 pci_dev->msix_cap + PCI_MSIX_FLAGS + 1)) {
1191 assigned_dev_update_msix(pci_dev);
1195 emulate_mask = 0;
1196 memcpy(&emulate_mask, assigned_dev->emulate_config_write + address, len);
1197 emulate_mask = le32_to_cpu(emulate_mask);
1199 full_emulation_mask = 0xffffffff >> (32 - len * 8);
1201 if (emulate_mask != full_emulation_mask) {
1202 if (emulate_mask) {
1203 val &= ~emulate_mask;
1204 val |= assigned_dev_pci_read(pci_dev, address, len) & emulate_mask;
1206 assigned_dev_pci_write(pci_dev, address, val, len);
1210 static void assigned_dev_setup_cap_read(AssignedDevice *dev, uint32_t offset,
1211 uint32_t len)
1213 assigned_dev_direct_config_read(dev, offset, len);
1214 assigned_dev_emulate_config_read(dev, offset + PCI_CAP_LIST_NEXT, 1);
1217 static int assigned_device_pci_cap_init(PCIDevice *pci_dev)
1219 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1220 PCIRegion *pci_region = dev->real_device.regions;
1221 int ret, pos;
1223 /* Clear initial capabilities pointer and status copied from hw */
1224 pci_set_byte(pci_dev->config + PCI_CAPABILITY_LIST, 0);
1225 pci_set_word(pci_dev->config + PCI_STATUS,
1226 pci_get_word(pci_dev->config + PCI_STATUS) &
1227 ~PCI_STATUS_CAP_LIST);
1229 /* Expose MSI capability
1230 * MSI capability is the 1st capability in capability config */
1231 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSI, 0);
1232 if (pos != 0 && kvm_check_extension(kvm_state, KVM_CAP_ASSIGN_DEV_IRQ)) {
1233 if (!check_irqchip_in_kernel()) {
1234 return -ENOTSUP;
1236 dev->cap.available |= ASSIGNED_DEVICE_CAP_MSI;
1237 /* Only 32-bit/no-mask currently supported */
1238 ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSI, pos, 10);
1239 if (ret < 0) {
1240 return ret;
1242 pci_dev->msi_cap = pos;
1244 pci_set_word(pci_dev->config + pos + PCI_MSI_FLAGS,
1245 pci_get_word(pci_dev->config + pos + PCI_MSI_FLAGS) &
1246 PCI_MSI_FLAGS_QMASK);
1247 pci_set_long(pci_dev->config + pos + PCI_MSI_ADDRESS_LO, 0);
1248 pci_set_word(pci_dev->config + pos + PCI_MSI_DATA_32, 0);
1250 /* Set writable fields */
1251 pci_set_word(pci_dev->wmask + pos + PCI_MSI_FLAGS,
1252 PCI_MSI_FLAGS_QSIZE | PCI_MSI_FLAGS_ENABLE);
1253 pci_set_long(pci_dev->wmask + pos + PCI_MSI_ADDRESS_LO, 0xfffffffc);
1254 pci_set_word(pci_dev->wmask + pos + PCI_MSI_DATA_32, 0xffff);
1256 /* Expose MSI-X capability */
1257 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSIX, 0);
1258 if (pos != 0 && kvm_device_msix_supported(kvm_state)) {
1259 int bar_nr;
1260 uint32_t msix_table_entry;
1262 if (!check_irqchip_in_kernel()) {
1263 return -ENOTSUP;
1265 dev->cap.available |= ASSIGNED_DEVICE_CAP_MSIX;
1266 ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSIX, pos, 12);
1267 if (ret < 0) {
1268 return ret;
1270 pci_dev->msix_cap = pos;
1272 pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS,
1273 pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) &
1274 PCI_MSIX_FLAGS_QSIZE);
1276 /* Only enable and function mask bits are writable */
1277 pci_set_word(pci_dev->wmask + pos + PCI_MSIX_FLAGS,
1278 PCI_MSIX_FLAGS_ENABLE | PCI_MSIX_FLAGS_MASKALL);
1280 msix_table_entry = pci_get_long(pci_dev->config + pos + PCI_MSIX_TABLE);
1281 bar_nr = msix_table_entry & PCI_MSIX_FLAGS_BIRMASK;
1282 msix_table_entry &= ~PCI_MSIX_FLAGS_BIRMASK;
1283 dev->msix_table_addr = pci_region[bar_nr].base_addr + msix_table_entry;
1284 dev->msix_max = pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS);
1285 dev->msix_max &= PCI_MSIX_FLAGS_QSIZE;
1286 dev->msix_max += 1;
1289 /* Minimal PM support, nothing writable, device appears to NAK changes */
1290 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PM, 0);
1291 if (pos) {
1292 uint16_t pmc;
1294 ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, pos, PCI_PM_SIZEOF);
1295 if (ret < 0) {
1296 return ret;
1299 assigned_dev_setup_cap_read(dev, pos, PCI_PM_SIZEOF);
1301 pmc = pci_get_word(pci_dev->config + pos + PCI_CAP_FLAGS);
1302 pmc &= (PCI_PM_CAP_VER_MASK | PCI_PM_CAP_DSI);
1303 pci_set_word(pci_dev->config + pos + PCI_CAP_FLAGS, pmc);
1305 /* assign_device will bring the device up to D0, so we don't need
1306 * to worry about doing that ourselves here. */
1307 pci_set_word(pci_dev->config + pos + PCI_PM_CTRL,
1308 PCI_PM_CTRL_NO_SOFT_RESET);
1310 pci_set_byte(pci_dev->config + pos + PCI_PM_PPB_EXTENSIONS, 0);
1311 pci_set_byte(pci_dev->config + pos + PCI_PM_DATA_REGISTER, 0);
1314 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_EXP, 0);
1315 if (pos) {
1316 uint8_t version, size = 0;
1317 uint16_t type, devctl, lnksta;
1318 uint32_t devcap, lnkcap;
1320 version = pci_get_byte(pci_dev->config + pos + PCI_EXP_FLAGS);
1321 version &= PCI_EXP_FLAGS_VERS;
1322 if (version == 1) {
1323 size = 0x14;
1324 } else if (version == 2) {
1326 * Check for non-std size, accept reduced size to 0x34,
1327 * which is what bcm5761 implemented, violating the
1328 * PCIe v3.0 spec that regs should exist and be read as 0,
1329 * not optionally provided and shorten the struct size.
1331 size = MIN(0x3c, PCI_CONFIG_SPACE_SIZE - pos);
1332 if (size < 0x34) {
1333 error_report("%s: Invalid size PCIe cap-id 0x%x",
1334 __func__, PCI_CAP_ID_EXP);
1335 return -EINVAL;
1336 } else if (size != 0x3c) {
1337 error_report("WARNING, %s: PCIe cap-id 0x%x has "
1338 "non-standard size 0x%x; std size should be 0x3c",
1339 __func__, PCI_CAP_ID_EXP, size);
1341 } else if (version == 0) {
1342 uint16_t vid, did;
1343 vid = pci_get_word(pci_dev->config + PCI_VENDOR_ID);
1344 did = pci_get_word(pci_dev->config + PCI_DEVICE_ID);
1345 if (vid == PCI_VENDOR_ID_INTEL && did == 0x10ed) {
1347 * quirk for Intel 82599 VF with invalid PCIe capability
1348 * version, should really be version 2 (same as PF)
1350 size = 0x3c;
1354 if (size == 0) {
1355 error_report("%s: Unsupported PCI express capability version %d",
1356 __func__, version);
1357 return -EINVAL;
1360 ret = pci_add_capability(pci_dev, PCI_CAP_ID_EXP, pos, size);
1361 if (ret < 0) {
1362 return ret;
1365 assigned_dev_setup_cap_read(dev, pos, size);
1367 type = pci_get_word(pci_dev->config + pos + PCI_EXP_FLAGS);
1368 type = (type & PCI_EXP_FLAGS_TYPE) >> 4;
1369 if (type != PCI_EXP_TYPE_ENDPOINT &&
1370 type != PCI_EXP_TYPE_LEG_END && type != PCI_EXP_TYPE_RC_END) {
1371 error_report("Device assignment only supports endpoint assignment,"
1372 " device type %d", type);
1373 return -EINVAL;
1376 /* capabilities, pass existing read-only copy
1377 * PCI_EXP_FLAGS_IRQ: updated by hardware, should be direct read */
1379 /* device capabilities: hide FLR */
1380 devcap = pci_get_long(pci_dev->config + pos + PCI_EXP_DEVCAP);
1381 devcap &= ~PCI_EXP_DEVCAP_FLR;
1382 pci_set_long(pci_dev->config + pos + PCI_EXP_DEVCAP, devcap);
1384 /* device control: clear all error reporting enable bits, leaving
1385 * only a few host values. Note, these are
1386 * all writable, but not passed to hw.
1388 devctl = pci_get_word(pci_dev->config + pos + PCI_EXP_DEVCTL);
1389 devctl = (devctl & (PCI_EXP_DEVCTL_READRQ | PCI_EXP_DEVCTL_PAYLOAD)) |
1390 PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN;
1391 pci_set_word(pci_dev->config + pos + PCI_EXP_DEVCTL, devctl);
1392 devctl = PCI_EXP_DEVCTL_BCR_FLR | PCI_EXP_DEVCTL_AUX_PME;
1393 pci_set_word(pci_dev->wmask + pos + PCI_EXP_DEVCTL, ~devctl);
1395 /* Clear device status */
1396 pci_set_word(pci_dev->config + pos + PCI_EXP_DEVSTA, 0);
1398 /* Link capabilities, expose links and latencues, clear reporting */
1399 lnkcap = pci_get_long(pci_dev->config + pos + PCI_EXP_LNKCAP);
1400 lnkcap &= (PCI_EXP_LNKCAP_SLS | PCI_EXP_LNKCAP_MLW |
1401 PCI_EXP_LNKCAP_ASPMS | PCI_EXP_LNKCAP_L0SEL |
1402 PCI_EXP_LNKCAP_L1EL);
1403 pci_set_long(pci_dev->config + pos + PCI_EXP_LNKCAP, lnkcap);
1405 /* Link control, pass existing read-only copy. Should be writable? */
1407 /* Link status, only expose current speed and width */
1408 lnksta = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKSTA);
1409 lnksta &= (PCI_EXP_LNKSTA_CLS | PCI_EXP_LNKSTA_NLW);
1410 pci_set_word(pci_dev->config + pos + PCI_EXP_LNKSTA, lnksta);
1412 if (version >= 2) {
1413 /* Slot capabilities, control, status - not needed for endpoints */
1414 pci_set_long(pci_dev->config + pos + PCI_EXP_SLTCAP, 0);
1415 pci_set_word(pci_dev->config + pos + PCI_EXP_SLTCTL, 0);
1416 pci_set_word(pci_dev->config + pos + PCI_EXP_SLTSTA, 0);
1418 /* Root control, capabilities, status - not needed for endpoints */
1419 pci_set_word(pci_dev->config + pos + PCI_EXP_RTCTL, 0);
1420 pci_set_word(pci_dev->config + pos + PCI_EXP_RTCAP, 0);
1421 pci_set_long(pci_dev->config + pos + PCI_EXP_RTSTA, 0);
1423 /* Device capabilities/control 2, pass existing read-only copy */
1424 /* Link control 2, pass existing read-only copy */
1428 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PCIX, 0);
1429 if (pos) {
1430 uint16_t cmd;
1431 uint32_t status;
1433 /* Only expose the minimum, 8 byte capability */
1434 ret = pci_add_capability(pci_dev, PCI_CAP_ID_PCIX, pos, 8);
1435 if (ret < 0) {
1436 return ret;
1439 assigned_dev_setup_cap_read(dev, pos, 8);
1441 /* Command register, clear upper bits, including extended modes */
1442 cmd = pci_get_word(pci_dev->config + pos + PCI_X_CMD);
1443 cmd &= (PCI_X_CMD_DPERR_E | PCI_X_CMD_ERO | PCI_X_CMD_MAX_READ |
1444 PCI_X_CMD_MAX_SPLIT);
1445 pci_set_word(pci_dev->config + pos + PCI_X_CMD, cmd);
1447 /* Status register, update with emulated PCI bus location, clear
1448 * error bits, leave the rest. */
1449 status = pci_get_long(pci_dev->config + pos + PCI_X_STATUS);
1450 status &= ~(PCI_X_STATUS_BUS | PCI_X_STATUS_DEVFN);
1451 status |= (pci_bus_num(pci_dev->bus) << 8) | pci_dev->devfn;
1452 status &= ~(PCI_X_STATUS_SPL_DISC | PCI_X_STATUS_UNX_SPL |
1453 PCI_X_STATUS_SPL_ERR);
1454 pci_set_long(pci_dev->config + pos + PCI_X_STATUS, status);
1457 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VPD, 0);
1458 if (pos) {
1459 /* Direct R/W passthrough */
1460 ret = pci_add_capability(pci_dev, PCI_CAP_ID_VPD, pos, 8);
1461 if (ret < 0) {
1462 return ret;
1465 assigned_dev_setup_cap_read(dev, pos, 8);
1467 /* direct write for cap content */
1468 assigned_dev_direct_config_write(dev, pos + 2, 6);
1471 /* Devices can have multiple vendor capabilities, get them all */
1472 for (pos = 0; (pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VNDR, pos));
1473 pos += PCI_CAP_LIST_NEXT) {
1474 uint8_t len = pci_get_byte(pci_dev->config + pos + PCI_CAP_FLAGS);
1475 /* Direct R/W passthrough */
1476 ret = pci_add_capability(pci_dev, PCI_CAP_ID_VNDR, pos, len);
1477 if (ret < 0) {
1478 return ret;
1481 assigned_dev_setup_cap_read(dev, pos, len);
1483 /* direct write for cap content */
1484 assigned_dev_direct_config_write(dev, pos + 2, len - 2);
1487 /* If real and virtual capability list status bits differ, virtualize the
1488 * access. */
1489 if ((pci_get_word(pci_dev->config + PCI_STATUS) & PCI_STATUS_CAP_LIST) !=
1490 (assigned_dev_pci_read_byte(pci_dev, PCI_STATUS) &
1491 PCI_STATUS_CAP_LIST)) {
1492 dev->emulate_config_read[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1495 return 0;
1498 static uint64_t
1499 assigned_dev_msix_mmio_read(void *opaque, hwaddr addr,
1500 unsigned size)
1502 AssignedDevice *adev = opaque;
1503 uint64_t val;
1505 memcpy(&val, (void *)((uint8_t *)adev->msix_table + addr), size);
1507 return val;
1510 static void assigned_dev_msix_mmio_write(void *opaque, hwaddr addr,
1511 uint64_t val, unsigned size)
1513 AssignedDevice *adev = opaque;
1514 PCIDevice *pdev = &adev->dev;
1515 uint16_t ctrl;
1516 MSIXTableEntry orig;
1517 int i = addr >> 4;
1519 if (i >= adev->msix_max) {
1520 return; /* Drop write */
1523 ctrl = pci_get_word(pdev->config + pdev->msix_cap + PCI_MSIX_FLAGS);
1525 DEBUG("write to MSI-X table offset 0x%lx, val 0x%lx\n", addr, val);
1527 if (ctrl & PCI_MSIX_FLAGS_ENABLE) {
1528 orig = adev->msix_table[i];
1531 memcpy((uint8_t *)adev->msix_table + addr, &val, size);
1533 if (ctrl & PCI_MSIX_FLAGS_ENABLE) {
1534 MSIXTableEntry *entry = &adev->msix_table[i];
1536 if (!assigned_dev_msix_masked(&orig) &&
1537 assigned_dev_msix_masked(entry)) {
1539 * Vector masked, disable it
1541 * XXX It's not clear if we can or should actually attempt
1542 * to mask or disable the interrupt. KVM doesn't have
1543 * support for pending bits and kvm_assign_set_msix_entry
1544 * doesn't modify the device hardware mask. Interrupts
1545 * while masked are simply not injected to the guest, so
1546 * are lost. Can we get away with always injecting an
1547 * interrupt on unmask?
1549 } else if (assigned_dev_msix_masked(&orig) &&
1550 !assigned_dev_msix_masked(entry)) {
1551 /* Vector unmasked */
1552 if (i >= adev->msi_virq_nr || adev->msi_virq[i] < 0) {
1553 /* Previously unassigned vector, start from scratch */
1554 assigned_dev_update_msix(pdev);
1555 return;
1556 } else {
1557 /* Update an existing, previously masked vector */
1558 MSIMessage msg;
1559 int ret;
1561 msg.address = entry->addr_lo |
1562 ((uint64_t)entry->addr_hi << 32);
1563 msg.data = entry->data;
1565 ret = kvm_irqchip_update_msi_route(kvm_state,
1566 adev->msi_virq[i], msg);
1567 if (ret) {
1568 error_report("Error updating irq routing entry (%d)", ret);
1575 static const MemoryRegionOps assigned_dev_msix_mmio_ops = {
1576 .read = assigned_dev_msix_mmio_read,
1577 .write = assigned_dev_msix_mmio_write,
1578 .endianness = DEVICE_NATIVE_ENDIAN,
1579 .valid = {
1580 .min_access_size = 4,
1581 .max_access_size = 8,
1583 .impl = {
1584 .min_access_size = 4,
1585 .max_access_size = 8,
1589 static void assigned_dev_msix_reset(AssignedDevice *dev)
1591 MSIXTableEntry *entry;
1592 int i;
1594 if (!dev->msix_table) {
1595 return;
1598 memset(dev->msix_table, 0, MSIX_PAGE_SIZE);
1600 for (i = 0, entry = dev->msix_table; i < dev->msix_max; i++, entry++) {
1601 entry->ctrl = cpu_to_le32(0x1); /* Masked */
1605 static int assigned_dev_register_msix_mmio(AssignedDevice *dev)
1607 dev->msix_table = mmap(NULL, MSIX_PAGE_SIZE, PROT_READ|PROT_WRITE,
1608 MAP_ANONYMOUS|MAP_PRIVATE, 0, 0);
1609 if (dev->msix_table == MAP_FAILED) {
1610 error_report("fail allocate msix_table! %s", strerror(errno));
1611 return -EFAULT;
1614 assigned_dev_msix_reset(dev);
1616 memory_region_init_io(&dev->mmio, OBJECT(dev), &assigned_dev_msix_mmio_ops,
1617 dev, "assigned-dev-msix", MSIX_PAGE_SIZE);
1618 return 0;
1621 static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev)
1623 if (!dev->msix_table) {
1624 return;
1627 memory_region_destroy(&dev->mmio);
1629 if (munmap(dev->msix_table, MSIX_PAGE_SIZE) == -1) {
1630 error_report("error unmapping msix_table! %s", strerror(errno));
1632 dev->msix_table = NULL;
1635 static const VMStateDescription vmstate_assigned_device = {
1636 .name = "pci-assign",
1637 .unmigratable = 1,
1640 static void reset_assigned_device(DeviceState *dev)
1642 PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
1643 AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1644 char reset_file[64];
1645 const char reset[] = "1";
1646 int fd, ret;
1649 * If a guest is reset without being shutdown, MSI/MSI-X can still
1650 * be running. We want to return the device to a known state on
1651 * reset, so disable those here. We especially do not want MSI-X
1652 * enabled since it lives in MMIO space, which is about to get
1653 * disabled.
1655 if (adev->assigned_irq_type == ASSIGNED_IRQ_MSIX) {
1656 uint16_t ctrl = pci_get_word(pci_dev->config +
1657 pci_dev->msix_cap + PCI_MSIX_FLAGS);
1659 pci_set_word(pci_dev->config + pci_dev->msix_cap + PCI_MSIX_FLAGS,
1660 ctrl & ~PCI_MSIX_FLAGS_ENABLE);
1661 assigned_dev_update_msix(pci_dev);
1662 } else if (adev->assigned_irq_type == ASSIGNED_IRQ_MSI) {
1663 uint8_t ctrl = pci_get_byte(pci_dev->config +
1664 pci_dev->msi_cap + PCI_MSI_FLAGS);
1666 pci_set_byte(pci_dev->config + pci_dev->msi_cap + PCI_MSI_FLAGS,
1667 ctrl & ~PCI_MSI_FLAGS_ENABLE);
1668 assigned_dev_update_msi(pci_dev);
1671 snprintf(reset_file, sizeof(reset_file),
1672 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/reset",
1673 adev->host.domain, adev->host.bus, adev->host.slot,
1674 adev->host.function);
1677 * Issue a device reset via pci-sysfs. Note that we use write(2) here
1678 * and ignore the return value because some kernels have a bug that
1679 * returns 0 rather than bytes written on success, sending us into an
1680 * infinite retry loop using other write mechanisms.
1682 fd = open(reset_file, O_WRONLY);
1683 if (fd != -1) {
1684 ret = write(fd, reset, strlen(reset));
1685 (void)ret;
1686 close(fd);
1690 * When a 0 is written to the bus master register, the device is logically
1691 * disconnected from the PCI bus. This avoids further DMA transfers.
1693 assigned_dev_pci_write_config(pci_dev, PCI_COMMAND, 0, 1);
1696 static int assigned_initfn(struct PCIDevice *pci_dev)
1698 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1699 uint8_t e_intx;
1700 int r;
1702 if (!kvm_enabled()) {
1703 error_report("pci-assign: error: requires KVM support");
1704 return -1;
1707 if (!dev->host.domain && !dev->host.bus && !dev->host.slot &&
1708 !dev->host.function) {
1709 error_report("pci-assign: error: no host device specified");
1710 return -1;
1714 * Set up basic config space access control. Will be further refined during
1715 * device initialization.
1717 assigned_dev_emulate_config_read(dev, 0, PCI_CONFIG_SPACE_SIZE);
1718 assigned_dev_direct_config_read(dev, PCI_STATUS, 2);
1719 assigned_dev_direct_config_read(dev, PCI_REVISION_ID, 1);
1720 assigned_dev_direct_config_read(dev, PCI_CLASS_PROG, 3);
1721 assigned_dev_direct_config_read(dev, PCI_CACHE_LINE_SIZE, 1);
1722 assigned_dev_direct_config_read(dev, PCI_LATENCY_TIMER, 1);
1723 assigned_dev_direct_config_read(dev, PCI_BIST, 1);
1724 assigned_dev_direct_config_read(dev, PCI_CARDBUS_CIS, 4);
1725 assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_VENDOR_ID, 2);
1726 assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_ID, 2);
1727 assigned_dev_direct_config_read(dev, PCI_CAPABILITY_LIST + 1, 7);
1728 assigned_dev_direct_config_read(dev, PCI_MIN_GNT, 1);
1729 assigned_dev_direct_config_read(dev, PCI_MAX_LAT, 1);
1730 memcpy(dev->emulate_config_write, dev->emulate_config_read,
1731 sizeof(dev->emulate_config_read));
1733 if (get_real_device(dev)) {
1734 error_report("pci-assign: Error: Couldn't get real device (%s)!",
1735 dev->dev.qdev.id);
1736 goto out;
1739 if (assigned_device_pci_cap_init(pci_dev) < 0) {
1740 goto out;
1743 /* intercept MSI-X entry page in the MMIO */
1744 if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1745 if (assigned_dev_register_msix_mmio(dev)) {
1746 goto out;
1750 /* handle real device's MMIO/PIO BARs */
1751 if (assigned_dev_register_regions(dev->real_device.regions,
1752 dev->real_device.region_number,
1753 dev)) {
1754 goto out;
1757 /* handle interrupt routing */
1758 e_intx = dev->dev.config[PCI_INTERRUPT_PIN] - 1;
1759 dev->intpin = e_intx;
1760 dev->intx_route.mode = PCI_INTX_DISABLED;
1761 dev->intx_route.irq = -1;
1763 /* assign device to guest */
1764 r = assign_device(dev);
1765 if (r < 0) {
1766 goto out;
1769 /* assign legacy INTx to the device */
1770 r = assign_intx(dev);
1771 if (r < 0) {
1772 goto assigned_out;
1775 assigned_dev_load_option_rom(dev);
1777 add_boot_device_path(dev->bootindex, &pci_dev->qdev, NULL);
1779 return 0;
1781 assigned_out:
1782 deassign_device(dev);
1783 out:
1784 free_assigned_device(dev);
1785 return -1;
1788 static void assigned_exitfn(struct PCIDevice *pci_dev)
1790 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1792 deassign_device(dev);
1793 free_assigned_device(dev);
1796 static Property assigned_dev_properties[] = {
1797 DEFINE_PROP_PCI_HOST_DEVADDR("host", AssignedDevice, host),
1798 DEFINE_PROP_BIT("prefer_msi", AssignedDevice, features,
1799 ASSIGNED_DEVICE_PREFER_MSI_BIT, false),
1800 DEFINE_PROP_BIT("share_intx", AssignedDevice, features,
1801 ASSIGNED_DEVICE_SHARE_INTX_BIT, true),
1802 DEFINE_PROP_INT32("bootindex", AssignedDevice, bootindex, -1),
1803 DEFINE_PROP_STRING("configfd", AssignedDevice, configfd_name),
1804 DEFINE_PROP_END_OF_LIST(),
1807 static void assign_class_init(ObjectClass *klass, void *data)
1809 PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1810 DeviceClass *dc = DEVICE_CLASS(klass);
1812 k->init = assigned_initfn;
1813 k->exit = assigned_exitfn;
1814 k->config_read = assigned_dev_pci_read_config;
1815 k->config_write = assigned_dev_pci_write_config;
1816 dc->props = assigned_dev_properties;
1817 dc->vmsd = &vmstate_assigned_device;
1818 dc->reset = reset_assigned_device;
1819 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1820 dc->desc = "KVM-based PCI passthrough";
1823 static const TypeInfo assign_info = {
1824 .name = "kvm-pci-assign",
1825 .parent = TYPE_PCI_DEVICE,
1826 .instance_size = sizeof(AssignedDevice),
1827 .class_init = assign_class_init,
1830 static void assign_register_types(void)
1832 type_register_static(&assign_info);
1835 type_init(assign_register_types)
1838 * Scan the assigned devices for the devices that have an option ROM, and then
1839 * load the corresponding ROM data to RAM. If an error occurs while loading an
1840 * option ROM, we just ignore that option ROM and continue with the next one.
1842 static void assigned_dev_load_option_rom(AssignedDevice *dev)
1844 char name[32], rom_file[64];
1845 FILE *fp;
1846 uint8_t val;
1847 struct stat st;
1848 void *ptr;
1850 /* If loading ROM from file, pci handles it */
1851 if (dev->dev.romfile || !dev->dev.rom_bar) {
1852 return;
1855 snprintf(rom_file, sizeof(rom_file),
1856 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/rom",
1857 dev->host.domain, dev->host.bus, dev->host.slot,
1858 dev->host.function);
1860 if (stat(rom_file, &st)) {
1861 return;
1864 if (access(rom_file, F_OK)) {
1865 error_report("pci-assign: Insufficient privileges for %s", rom_file);
1866 return;
1869 /* Write "1" to the ROM file to enable it */
1870 fp = fopen(rom_file, "r+");
1871 if (fp == NULL) {
1872 return;
1874 val = 1;
1875 if (fwrite(&val, 1, 1, fp) != 1) {
1876 goto close_rom;
1878 fseek(fp, 0, SEEK_SET);
1880 snprintf(name, sizeof(name), "%s.rom",
1881 object_get_typename(OBJECT(dev)));
1882 memory_region_init_ram(&dev->dev.rom, OBJECT(dev), name, st.st_size);
1883 vmstate_register_ram(&dev->dev.rom, &dev->dev.qdev);
1884 ptr = memory_region_get_ram_ptr(&dev->dev.rom);
1885 memset(ptr, 0xff, st.st_size);
1887 if (!fread(ptr, 1, st.st_size, fp)) {
1888 error_report("pci-assign: Cannot read from host %s", rom_file);
1889 error_printf("Device option ROM contents are probably invalid "
1890 "(check dmesg).\nSkip option ROM probe with rombar=0, "
1891 "or load from file with romfile=\n");
1892 memory_region_destroy(&dev->dev.rom);
1893 goto close_rom;
1896 pci_register_bar(&dev->dev, PCI_ROM_SLOT, 0, &dev->dev.rom);
1897 dev->dev.has_rom = true;
1898 close_rom:
1899 /* Write "0" to disable ROM */
1900 fseek(fp, 0, SEEK_SET);
1901 val = 0;
1902 if (!fwrite(&val, 1, 1, fp)) {
1903 DEBUG("%s\n", "Failed to disable pci-sysfs rom file");
1905 fclose(fp);