pci-assign: Fix MSI-X capability test
[qemu-kvm.git] / hw / device-assignment.c
blobf0a6ca9b24aaaff43fea9d2ba3e48d91a95465b5
1 /*
2 * Copyright (c) 2007, Neocleus Corporation.
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms and conditions of the GNU General Public License,
6 * version 2, as published by the Free Software Foundation.
8 * This program is distributed in the hope it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
11 * more details.
13 * You should have received a copy of the GNU General Public License along with
14 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15 * Place - Suite 330, Boston, MA 02111-1307 USA.
18 * Assign a PCI device from the host to a guest VM.
20 * Adapted for KVM by Qumranet.
22 * Copyright (c) 2007, Neocleus, Alex Novik (alex@neocleus.com)
23 * Copyright (c) 2007, Neocleus, Guy Zana (guy@neocleus.com)
24 * Copyright (C) 2008, Qumranet, Amit Shah (amit.shah@qumranet.com)
25 * Copyright (C) 2008, Red Hat, Amit Shah (amit.shah@redhat.com)
26 * Copyright (C) 2008, IBM, Muli Ben-Yehuda (muli@il.ibm.com)
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <sys/io.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include "qemu-kvm.h"
34 #include "hw.h"
35 #include "pc.h"
36 #include "qemu-error.h"
37 #include "console.h"
38 #include "device-assignment.h"
39 #include "loader.h"
40 #include "monitor.h"
41 #include "range.h"
42 #include "sysemu.h"
44 #define MSIX_PAGE_SIZE 0x1000
46 /* From linux/ioport.h */
47 #define IORESOURCE_IO 0x00000100 /* Resource type */
48 #define IORESOURCE_MEM 0x00000200
49 #define IORESOURCE_IRQ 0x00000400
50 #define IORESOURCE_DMA 0x00000800
51 #define IORESOURCE_PREFETCH 0x00002000 /* No side effects */
53 /* #define DEVICE_ASSIGNMENT_DEBUG 1 */
55 #ifdef DEVICE_ASSIGNMENT_DEBUG
56 #define DEBUG(fmt, ...) \
57 do { \
58 fprintf(stderr, "%s: " fmt, __func__ , __VA_ARGS__); \
59 } while (0)
60 #else
61 #define DEBUG(fmt, ...) do { } while(0)
62 #endif
64 static void assigned_dev_load_option_rom(AssignedDevice *dev);
66 static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev);
68 static uint32_t assigned_dev_ioport_rw(AssignedDevRegion *dev_region,
69 uint32_t addr, int len, uint32_t *val)
71 uint32_t ret = 0;
72 uint32_t offset = addr;
73 int fd = dev_region->region->resource_fd;
75 if (fd >= 0) {
76 if (val) {
77 DEBUG("pwrite val=%x, len=%d, e_phys=%x, offset=%x\n",
78 *val, len, addr, offset);
79 if (pwrite(fd, val, len, offset) != len) {
80 fprintf(stderr, "%s - pwrite failed %s\n",
81 __func__, strerror(errno));
83 } else {
84 if (pread(fd, &ret, len, offset) != len) {
85 fprintf(stderr, "%s - pread failed %s\n",
86 __func__, strerror(errno));
87 ret = (1UL << (len * 8)) - 1;
89 DEBUG("pread ret=%x, len=%d, e_phys=%x, offset=%x\n",
90 ret, len, addr, offset);
92 } else {
93 uint32_t port = offset + dev_region->u.r_baseport;
95 if (val) {
96 DEBUG("out val=%x, len=%d, e_phys=%x, host=%x\n",
97 *val, len, addr, port);
98 switch (len) {
99 case 1:
100 outb(*val, port);
101 break;
102 case 2:
103 outw(*val, port);
104 break;
105 case 4:
106 outl(*val, port);
107 break;
109 } else {
110 switch (len) {
111 case 1:
112 ret = inb(port);
113 break;
114 case 2:
115 ret = inw(port);
116 break;
117 case 4:
118 ret = inl(port);
119 break;
121 DEBUG("in val=%x, len=%d, e_phys=%x, host=%x\n",
122 ret, len, addr, port);
125 return ret;
128 static void assigned_dev_ioport_writeb(void *opaque, uint32_t addr,
129 uint32_t value)
131 assigned_dev_ioport_rw(opaque, addr, 1, &value);
132 return;
135 static void assigned_dev_ioport_writew(void *opaque, uint32_t addr,
136 uint32_t value)
138 assigned_dev_ioport_rw(opaque, addr, 2, &value);
139 return;
142 static void assigned_dev_ioport_writel(void *opaque, uint32_t addr,
143 uint32_t value)
145 assigned_dev_ioport_rw(opaque, addr, 4, &value);
146 return;
149 static uint32_t assigned_dev_ioport_readb(void *opaque, uint32_t addr)
151 return assigned_dev_ioport_rw(opaque, addr, 1, NULL);
154 static uint32_t assigned_dev_ioport_readw(void *opaque, uint32_t addr)
156 return assigned_dev_ioport_rw(opaque, addr, 2, NULL);
159 static uint32_t assigned_dev_ioport_readl(void *opaque, uint32_t addr)
161 return assigned_dev_ioport_rw(opaque, addr, 4, NULL);
164 static uint32_t slow_bar_readb(void *opaque, target_phys_addr_t addr)
166 AssignedDevRegion *d = opaque;
167 uint8_t *in = d->u.r_virtbase + addr;
168 uint32_t r;
170 r = *in;
171 DEBUG("slow_bar_readl addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
173 return r;
176 static uint32_t slow_bar_readw(void *opaque, target_phys_addr_t addr)
178 AssignedDevRegion *d = opaque;
179 uint16_t *in = d->u.r_virtbase + addr;
180 uint32_t r;
182 r = *in;
183 DEBUG("slow_bar_readl addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
185 return r;
188 static uint32_t slow_bar_readl(void *opaque, target_phys_addr_t addr)
190 AssignedDevRegion *d = opaque;
191 uint32_t *in = d->u.r_virtbase + addr;
192 uint32_t r;
194 r = *in;
195 DEBUG("slow_bar_readl addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
197 return r;
200 static void slow_bar_writeb(void *opaque, target_phys_addr_t addr, uint32_t val)
202 AssignedDevRegion *d = opaque;
203 uint8_t *out = d->u.r_virtbase + addr;
205 DEBUG("slow_bar_writeb addr=0x" TARGET_FMT_plx " val=0x%02x\n", addr, val);
206 *out = val;
209 static void slow_bar_writew(void *opaque, target_phys_addr_t addr, uint32_t val)
211 AssignedDevRegion *d = opaque;
212 uint16_t *out = d->u.r_virtbase + addr;
214 DEBUG("slow_bar_writew addr=0x" TARGET_FMT_plx " val=0x%04x\n", addr, val);
215 *out = val;
218 static void slow_bar_writel(void *opaque, target_phys_addr_t addr, uint32_t val)
220 AssignedDevRegion *d = opaque;
221 uint32_t *out = d->u.r_virtbase + addr;
223 DEBUG("slow_bar_writel addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, val);
224 *out = val;
227 static const MemoryRegionOps slow_bar_ops = {
228 .old_mmio = {
229 .read = { slow_bar_readb, slow_bar_readw, slow_bar_readl, },
230 .write = { slow_bar_writeb, slow_bar_writew, slow_bar_writel, },
232 .endianness = DEVICE_NATIVE_ENDIAN,
235 static void assigned_dev_iomem_setup(PCIDevice *pci_dev, int region_num,
236 pcibus_t e_size)
238 AssignedDevice *r_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
239 AssignedDevRegion *region = &r_dev->v_addrs[region_num];
240 PCIRegion *real_region = &r_dev->real_device.regions[region_num];
242 if (e_size > 0) {
243 memory_region_init(&region->container, "assigned-dev-container",
244 e_size);
245 memory_region_add_subregion(&region->container, 0, &region->real_iomem);
247 /* deal with MSI-X MMIO page */
248 if (real_region->base_addr <= r_dev->msix_table_addr &&
249 real_region->base_addr + real_region->size >=
250 r_dev->msix_table_addr) {
251 int offset = r_dev->msix_table_addr - real_region->base_addr;
253 memory_region_add_subregion_overlap(&region->container,
254 offset,
255 &r_dev->mmio,
261 static const MemoryRegionPortio assigned_dev_old_portio[] = {
262 { 0x10000, 1, .read = assigned_dev_ioport_readb, },
263 { 0x10000, 2, .read = assigned_dev_ioport_readw, },
264 { 0x10000, 4, .read = assigned_dev_ioport_readl, },
265 { 0x10000, 1, .write = assigned_dev_ioport_writeb, },
266 { 0x10000, 2, .write = assigned_dev_ioport_writew, },
267 { 0x10000, 4, .write = assigned_dev_ioport_writel, },
268 PORTIO_END_OF_LIST()
271 static const MemoryRegionOps assigned_dev_ioport_ops = {
272 .old_portio = assigned_dev_old_portio,
273 .endianness = DEVICE_NATIVE_ENDIAN,
276 static void assigned_dev_ioport_setup(PCIDevice *pci_dev, int region_num,
277 pcibus_t size)
279 AssignedDevice *r_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
280 AssignedDevRegion *region = &r_dev->v_addrs[region_num];
281 int r;
283 region->e_size = size;
285 if (region->region->resource_fd < 0) {
286 r = kvm_add_ioport_region(region->u.r_baseport, region->r_size,
287 pci_dev->qdev.hotplugged);
288 if (r < 0) {
289 fprintf(stderr, "%s: failed to enable ioport access (%m)\n",
290 __func__);
293 memory_region_init(&region->container, "assigned-dev-container", size);
294 memory_region_init_io(&region->real_iomem, &assigned_dev_ioport_ops,
295 r_dev->v_addrs + region_num,
296 "assigned-dev-iomem", size);
297 memory_region_add_subregion(&region->container, 0, &region->real_iomem);
300 static uint32_t assigned_dev_pci_read(PCIDevice *d, int pos, int len)
302 AssignedDevice *pci_dev = DO_UPCAST(AssignedDevice, dev, d);
303 uint32_t val;
304 ssize_t ret;
305 int fd = pci_dev->real_device.config_fd;
307 again:
308 ret = pread(fd, &val, len, pos);
309 if (ret != len) {
310 if ((ret < 0) && (errno == EINTR || errno == EAGAIN))
311 goto again;
313 fprintf(stderr, "%s: pread failed, ret = %zd errno = %d\n",
314 __func__, ret, errno);
316 exit(1);
319 return val;
322 static uint8_t assigned_dev_pci_read_byte(PCIDevice *d, int pos)
324 return (uint8_t)assigned_dev_pci_read(d, pos, 1);
327 static void assigned_dev_pci_write(PCIDevice *d, int pos, uint32_t val, int len)
329 AssignedDevice *pci_dev = DO_UPCAST(AssignedDevice, dev, d);
330 ssize_t ret;
331 int fd = pci_dev->real_device.config_fd;
333 again:
334 ret = pwrite(fd, &val, len, pos);
335 if (ret != len) {
336 if ((ret < 0) && (errno == EINTR || errno == EAGAIN))
337 goto again;
339 fprintf(stderr, "%s: pwrite failed, ret = %zd errno = %d\n",
340 __func__, ret, errno);
342 exit(1);
345 return;
348 static void assigned_dev_emulate_config_read(AssignedDevice *dev,
349 uint32_t offset, uint32_t len)
351 memset(dev->emulate_config_read + offset, 0xff, len);
354 static void assigned_dev_direct_config_read(AssignedDevice *dev,
355 uint32_t offset, uint32_t len)
357 memset(dev->emulate_config_read + offset, 0, len);
360 static void assigned_dev_direct_config_write(AssignedDevice *dev,
361 uint32_t offset, uint32_t len)
363 memset(dev->emulate_config_write + offset, 0, len);
366 static uint8_t pci_find_cap_offset(PCIDevice *d, uint8_t cap, uint8_t start)
368 int id;
369 int max_cap = 48;
370 int pos = start ? start : PCI_CAPABILITY_LIST;
371 int status;
373 status = assigned_dev_pci_read_byte(d, PCI_STATUS);
374 if ((status & PCI_STATUS_CAP_LIST) == 0)
375 return 0;
377 while (max_cap--) {
378 pos = assigned_dev_pci_read_byte(d, pos);
379 if (pos < 0x40)
380 break;
382 pos &= ~3;
383 id = assigned_dev_pci_read_byte(d, pos + PCI_CAP_LIST_ID);
385 if (id == 0xff)
386 break;
387 if (id == cap)
388 return pos;
390 pos += PCI_CAP_LIST_NEXT;
392 return 0;
395 static int assigned_dev_register_regions(PCIRegion *io_regions,
396 unsigned long regions_num,
397 AssignedDevice *pci_dev)
399 uint32_t i;
400 PCIRegion *cur_region = io_regions;
402 for (i = 0; i < regions_num; i++, cur_region++) {
403 if (!cur_region->valid)
404 continue;
405 pci_dev->v_addrs[i].num = i;
407 /* handle memory io regions */
408 if (cur_region->type & IORESOURCE_MEM) {
409 int t = cur_region->type & IORESOURCE_PREFETCH
410 ? PCI_BASE_ADDRESS_MEM_PREFETCH
411 : PCI_BASE_ADDRESS_SPACE_MEMORY;
413 /* map physical memory */
414 pci_dev->v_addrs[i].u.r_virtbase = mmap(NULL, cur_region->size,
415 PROT_WRITE | PROT_READ,
416 MAP_SHARED,
417 cur_region->resource_fd,
418 (off_t)0);
420 if (pci_dev->v_addrs[i].u.r_virtbase == MAP_FAILED) {
421 pci_dev->v_addrs[i].u.r_virtbase = NULL;
422 fprintf(stderr, "%s: Error: Couldn't mmap 0x%x!"
423 "\n", __func__,
424 (uint32_t) (cur_region->base_addr));
425 return -1;
428 pci_dev->v_addrs[i].r_size = cur_region->size;
429 pci_dev->v_addrs[i].e_size = 0;
431 /* add offset */
432 pci_dev->v_addrs[i].u.r_virtbase +=
433 (cur_region->base_addr & 0xFFF);
435 if (cur_region->size & 0xFFF) {
436 fprintf(stderr, "PCI region %d at address 0x%llx "
437 "has size 0x%x, which is not a multiple of 4K. "
438 "You might experience some performance hit "
439 "due to that.\n",
440 i, (unsigned long long)cur_region->base_addr,
441 cur_region->size);
442 memory_region_init_io(&pci_dev->v_addrs[i].real_iomem,
443 &slow_bar_ops, &pci_dev->v_addrs[i],
444 "assigned-dev-slow-bar",
445 cur_region->size);
446 } else {
447 void *virtbase = pci_dev->v_addrs[i].u.r_virtbase;
448 char name[32];
449 snprintf(name, sizeof(name), "%s.bar%d",
450 pci_dev->dev.qdev.info->name, i);
451 memory_region_init_ram_ptr(&pci_dev->v_addrs[i].real_iomem,
452 &pci_dev->dev.qdev,
453 name, cur_region->size,
454 virtbase);
457 assigned_dev_iomem_setup(&pci_dev->dev, i, cur_region->size);
458 pci_register_bar((PCIDevice *) pci_dev, i, t,
459 &pci_dev->v_addrs[i].container);
460 continue;
461 } else {
462 /* handle port io regions */
463 uint32_t val;
464 int ret;
466 /* Test kernel support for ioport resource read/write. Old
467 * kernels return EIO. New kernels only allow 1/2/4 byte reads
468 * so should return EINVAL for a 3 byte read */
469 ret = pread(pci_dev->v_addrs[i].region->resource_fd, &val, 3, 0);
470 if (ret == 3) {
471 fprintf(stderr, "I/O port resource supports 3 byte read?!\n");
472 abort();
473 } else if (errno != EINVAL) {
474 fprintf(stderr, "Using raw in/out ioport access (sysfs - %s)\n",
475 strerror(errno));
476 close(pci_dev->v_addrs[i].region->resource_fd);
477 pci_dev->v_addrs[i].region->resource_fd = -1;
480 pci_dev->v_addrs[i].u.r_baseport = cur_region->base_addr;
481 pci_dev->v_addrs[i].r_size = cur_region->size;
482 pci_dev->v_addrs[i].e_size = 0;
484 assigned_dev_ioport_setup(&pci_dev->dev, i, cur_region->size);
485 pci_register_bar((PCIDevice *) pci_dev, i,
486 PCI_BASE_ADDRESS_SPACE_IO,
487 &pci_dev->v_addrs[i].container);
491 /* success */
492 return 0;
495 static int get_real_id(const char *devpath, const char *idname, uint16_t *val)
497 FILE *f;
498 char name[128];
499 long id;
501 snprintf(name, sizeof(name), "%s%s", devpath, idname);
502 f = fopen(name, "r");
503 if (f == NULL) {
504 fprintf(stderr, "%s: %s: %m\n", __func__, name);
505 return -1;
507 if (fscanf(f, "%li\n", &id) == 1) {
508 *val = id;
509 } else {
510 return -1;
512 fclose(f);
514 return 0;
517 static int get_real_vendor_id(const char *devpath, uint16_t *val)
519 return get_real_id(devpath, "vendor", val);
522 static int get_real_device_id(const char *devpath, uint16_t *val)
524 return get_real_id(devpath, "device", val);
527 static int get_real_device(AssignedDevice *pci_dev, uint16_t r_seg,
528 uint8_t r_bus, uint8_t r_dev, uint8_t r_func)
530 char dir[128], name[128];
531 int fd, r = 0, v;
532 FILE *f;
533 unsigned long long start, end, size, flags;
534 uint16_t id;
535 struct stat statbuf;
536 PCIRegion *rp;
537 PCIDevRegions *dev = &pci_dev->real_device;
539 dev->region_number = 0;
541 snprintf(dir, sizeof(dir), "/sys/bus/pci/devices/%04x:%02x:%02x.%x/",
542 r_seg, r_bus, r_dev, r_func);
544 snprintf(name, sizeof(name), "%sconfig", dir);
546 if (pci_dev->configfd_name && *pci_dev->configfd_name) {
547 if (qemu_isdigit(pci_dev->configfd_name[0])) {
548 dev->config_fd = strtol(pci_dev->configfd_name, NULL, 0);
549 } else {
550 dev->config_fd = monitor_get_fd(cur_mon, pci_dev->configfd_name);
551 if (dev->config_fd < 0) {
552 fprintf(stderr, "%s: (%s) unkown\n", __func__,
553 pci_dev->configfd_name);
554 return 1;
557 } else {
558 dev->config_fd = open(name, O_RDWR);
560 if (dev->config_fd == -1) {
561 fprintf(stderr, "%s: %s: %m\n", __func__, name);
562 return 1;
565 again:
566 r = read(dev->config_fd, pci_dev->dev.config,
567 pci_config_size(&pci_dev->dev));
568 if (r < 0) {
569 if (errno == EINTR || errno == EAGAIN)
570 goto again;
571 fprintf(stderr, "%s: read failed, errno = %d\n", __func__, errno);
574 /* Clear host resource mapping info. If we choose not to register a
575 * BAR, such as might be the case with the option ROM, we can get
576 * confusing, unwritable, residual addresses from the host here. */
577 memset(&pci_dev->dev.config[PCI_BASE_ADDRESS_0], 0, 24);
578 memset(&pci_dev->dev.config[PCI_ROM_ADDRESS], 0, 4);
580 snprintf(name, sizeof(name), "%sresource", dir);
582 f = fopen(name, "r");
583 if (f == NULL) {
584 fprintf(stderr, "%s: %s: %m\n", __func__, name);
585 return 1;
588 for (r = 0; r < PCI_ROM_SLOT; r++) {
589 if (fscanf(f, "%lli %lli %lli\n", &start, &end, &flags) != 3)
590 break;
592 rp = dev->regions + r;
593 rp->valid = 0;
594 rp->resource_fd = -1;
595 size = end - start + 1;
596 flags &= IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_PREFETCH;
597 if (size == 0 || (flags & ~IORESOURCE_PREFETCH) == 0)
598 continue;
599 if (flags & IORESOURCE_MEM) {
600 flags &= ~IORESOURCE_IO;
601 } else {
602 flags &= ~IORESOURCE_PREFETCH;
604 snprintf(name, sizeof(name), "%sresource%d", dir, r);
605 fd = open(name, O_RDWR);
606 if (fd == -1)
607 continue;
608 rp->resource_fd = fd;
610 rp->type = flags;
611 rp->valid = 1;
612 rp->base_addr = start;
613 rp->size = size;
614 pci_dev->v_addrs[r].region = rp;
615 DEBUG("region %d size %d start 0x%llx type %d resource_fd %d\n",
616 r, rp->size, start, rp->type, rp->resource_fd);
619 fclose(f);
621 /* read and fill vendor ID */
622 v = get_real_vendor_id(dir, &id);
623 if (v) {
624 return 1;
626 pci_dev->dev.config[0] = id & 0xff;
627 pci_dev->dev.config[1] = (id & 0xff00) >> 8;
629 /* read and fill device ID */
630 v = get_real_device_id(dir, &id);
631 if (v) {
632 return 1;
634 pci_dev->dev.config[2] = id & 0xff;
635 pci_dev->dev.config[3] = (id & 0xff00) >> 8;
637 /* dealing with virtual function device */
638 snprintf(name, sizeof(name), "%sphysfn/", dir);
639 if (!stat(name, &statbuf)) {
640 /* always provide the written value on readout */
641 assigned_dev_emulate_config_read(pci_dev, PCI_COMMAND, 2);
644 dev->region_number = r;
645 return 0;
648 static QLIST_HEAD(, AssignedDevice) devs = QLIST_HEAD_INITIALIZER(devs);
650 static void free_dev_irq_entries(AssignedDevice *dev)
652 int i;
654 for (i = 0; i < dev->irq_entries_nr; i++)
655 kvm_del_routing_entry(&dev->entry[i]);
656 g_free(dev->entry);
657 dev->entry = NULL;
658 dev->irq_entries_nr = 0;
661 static void free_assigned_device(AssignedDevice *dev)
663 int i;
665 if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
666 assigned_dev_unregister_msix_mmio(dev);
668 for (i = 0; i < dev->real_device.region_number; i++) {
669 PCIRegion *pci_region = &dev->real_device.regions[i];
670 AssignedDevRegion *region = &dev->v_addrs[i];
672 if (!pci_region->valid) {
673 continue;
675 if (pci_region->type & IORESOURCE_IO) {
676 if (pci_region->resource_fd < 0) {
677 kvm_remove_ioport_region(region->u.r_baseport, region->r_size,
678 dev->dev.qdev.hotplugged);
680 } else if (pci_region->type & IORESOURCE_MEM) {
681 if (region->u.r_virtbase) {
682 memory_region_del_subregion(&region->container,
683 &region->real_iomem);
684 memory_region_destroy(&region->real_iomem);
685 memory_region_destroy(&region->container);
686 if (munmap(region->u.r_virtbase,
687 (pci_region->size + 0xFFF) & 0xFFFFF000)) {
688 fprintf(stderr,
689 "Failed to unmap assigned device region: %s\n",
690 strerror(errno));
694 if (pci_region->resource_fd >= 0) {
695 close(pci_region->resource_fd);
699 if (dev->real_device.config_fd >= 0) {
700 close(dev->real_device.config_fd);
703 free_dev_irq_entries(dev);
706 static uint32_t calc_assigned_dev_id(AssignedDevice *dev)
708 return (uint32_t)dev->h_segnr << 16 | (uint32_t)dev->h_busnr << 8 |
709 (uint32_t)dev->h_devfn;
712 static void assign_failed_examine(AssignedDevice *dev)
714 char name[PATH_MAX], dir[PATH_MAX], driver[PATH_MAX] = {}, *ns;
715 uint16_t vendor_id, device_id;
716 int r;
718 sprintf(dir, "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
719 dev->host.seg, dev->host.bus, dev->host.dev, dev->host.func);
721 sprintf(name, "%sdriver", dir);
723 r = readlink(name, driver, sizeof(driver));
724 if ((r <= 0) || r >= sizeof(driver) || !(ns = strrchr(driver, '/'))) {
725 goto fail;
728 ns++;
730 if (get_real_vendor_id(dir, &vendor_id) ||
731 get_real_device_id(dir, &device_id)) {
732 goto fail;
735 fprintf(stderr, "*** The driver '%s' is occupying your device "
736 "%04x:%02x:%02x.%x.\n",
737 ns, dev->host.seg, dev->host.bus, dev->host.dev, dev->host.func);
738 fprintf(stderr, "***\n");
739 fprintf(stderr, "*** You can try the following commands to free it:\n");
740 fprintf(stderr, "***\n");
741 fprintf(stderr, "*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub/"
742 "new_id\n", vendor_id, device_id);
743 fprintf(stderr, "*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/"
744 "%s/unbind\n",
745 dev->host.seg, dev->host.bus, dev->host.dev, dev->host.func, ns);
746 fprintf(stderr, "*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/"
747 "pci-stub/bind\n",
748 dev->host.seg, dev->host.bus, dev->host.dev, dev->host.func);
749 fprintf(stderr, "*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub"
750 "/remove_id\n", vendor_id, device_id);
751 fprintf(stderr, "***\n");
753 return;
755 fail:
756 fprintf(stderr, "Couldn't find out why.\n");
759 static int assign_device(AssignedDevice *dev)
761 struct kvm_assigned_pci_dev assigned_dev_data;
762 int r;
764 /* Only pass non-zero PCI segment to capable module */
765 if (!kvm_check_extension(kvm_state, KVM_CAP_PCI_SEGMENT) &&
766 dev->h_segnr) {
767 fprintf(stderr, "Can't assign device inside non-zero PCI segment "
768 "as this KVM module doesn't support it.\n");
769 return -ENODEV;
772 memset(&assigned_dev_data, 0, sizeof(assigned_dev_data));
773 assigned_dev_data.assigned_dev_id = calc_assigned_dev_id(dev);
774 assigned_dev_data.segnr = dev->h_segnr;
775 assigned_dev_data.busnr = dev->h_busnr;
776 assigned_dev_data.devfn = dev->h_devfn;
778 /* We always enable the IOMMU unless disabled on the command line */
779 if (dev->features & ASSIGNED_DEVICE_USE_IOMMU_MASK) {
780 if (!kvm_check_extension(kvm_state, KVM_CAP_IOMMU)) {
781 fprintf(stderr, "No IOMMU found. Unable to assign device \"%s\"\n",
782 dev->dev.qdev.id);
783 return -ENODEV;
785 assigned_dev_data.flags |= KVM_DEV_ASSIGN_ENABLE_IOMMU;
787 if (!(dev->features & ASSIGNED_DEVICE_USE_IOMMU_MASK)) {
788 fprintf(stderr,
789 "WARNING: Assigning a device without IOMMU protection can "
790 "cause host memory corruption if the device issues DMA write "
791 "requests!\n");
794 r = kvm_assign_pci_device(kvm_state, &assigned_dev_data);
795 if (r < 0) {
796 fprintf(stderr, "Failed to assign device \"%s\" : %s\n",
797 dev->dev.qdev.id, strerror(-r));
799 switch (r) {
800 case -EBUSY:
801 assign_failed_examine(dev);
802 break;
803 default:
804 break;
807 return r;
810 static int assign_irq(AssignedDevice *dev)
812 struct kvm_assigned_irq assigned_irq_data;
813 int irq, r = 0;
815 /* Interrupt PIN 0 means don't use INTx */
816 if (assigned_dev_pci_read_byte(&dev->dev, PCI_INTERRUPT_PIN) == 0)
817 return 0;
819 irq = pci_map_irq(&dev->dev, dev->intpin);
820 irq = piix_get_irq(irq);
822 #ifdef TARGET_IA64
823 irq = ipf_map_irq(&dev->dev, irq);
824 #endif
826 if (dev->girq == irq)
827 return r;
829 memset(&assigned_irq_data, 0, sizeof(assigned_irq_data));
830 assigned_irq_data.assigned_dev_id = calc_assigned_dev_id(dev);
831 assigned_irq_data.guest_irq = irq;
832 assigned_irq_data.host_irq = dev->real_device.irq;
833 if (dev->irq_requested_type) {
834 assigned_irq_data.flags = dev->irq_requested_type;
835 r = kvm_deassign_irq(kvm_state, &assigned_irq_data);
836 if (r) {
837 perror("assign_irq: deassign");
839 dev->irq_requested_type = 0;
842 assigned_irq_data.flags = KVM_DEV_IRQ_GUEST_INTX;
843 if (dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK &&
844 dev->cap.available & ASSIGNED_DEVICE_CAP_MSI)
845 assigned_irq_data.flags |= KVM_DEV_IRQ_HOST_MSI;
846 else
847 assigned_irq_data.flags |= KVM_DEV_IRQ_HOST_INTX;
849 r = kvm_assign_irq(kvm_state, &assigned_irq_data);
850 if (r < 0) {
851 fprintf(stderr, "Failed to assign irq for \"%s\": %s\n",
852 dev->dev.qdev.id, strerror(-r));
853 fprintf(stderr, "Perhaps you are assigning a device "
854 "that shares an IRQ with another device?\n");
855 return r;
858 dev->girq = irq;
859 dev->irq_requested_type = assigned_irq_data.flags;
860 return r;
863 static void deassign_device(AssignedDevice *dev)
865 struct kvm_assigned_pci_dev assigned_dev_data;
866 int r;
868 memset(&assigned_dev_data, 0, sizeof(assigned_dev_data));
869 assigned_dev_data.assigned_dev_id = calc_assigned_dev_id(dev);
871 r = kvm_deassign_pci_device(kvm_state, &assigned_dev_data);
872 if (r < 0)
873 fprintf(stderr, "Failed to deassign device \"%s\" : %s\n",
874 dev->dev.qdev.id, strerror(-r));
877 #if 0
878 AssignedDevInfo *get_assigned_device(int pcibus, int slot)
880 AssignedDevice *assigned_dev = NULL;
881 AssignedDevInfo *adev = NULL;
883 QLIST_FOREACH(adev, &adev_head, next) {
884 assigned_dev = adev->assigned_dev;
885 if (pci_bus_num(assigned_dev->dev.bus) == pcibus &&
886 PCI_SLOT(assigned_dev->dev.devfn) == slot)
887 return adev;
890 return NULL;
892 #endif
894 /* The pci config space got updated. Check if irq numbers have changed
895 * for our devices
897 void assigned_dev_update_irqs(void)
899 AssignedDevice *dev, *next;
900 int r;
902 dev = QLIST_FIRST(&devs);
903 while (dev) {
904 next = QLIST_NEXT(dev, next);
905 if (dev->irq_requested_type & KVM_DEV_IRQ_HOST_INTX) {
906 r = assign_irq(dev);
907 if (r < 0) {
908 qdev_unplug(&dev->dev.qdev);
911 dev = next;
915 static void assigned_dev_update_msi(PCIDevice *pci_dev)
917 struct kvm_assigned_irq assigned_irq_data;
918 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
919 uint8_t ctrl_byte = pci_get_byte(pci_dev->config + pci_dev->msi_cap +
920 PCI_MSI_FLAGS);
921 int r;
923 memset(&assigned_irq_data, 0, sizeof assigned_irq_data);
924 assigned_irq_data.assigned_dev_id = calc_assigned_dev_id(assigned_dev);
926 /* Some guests gratuitously disable MSI even if they're not using it,
927 * try to catch this by only deassigning irqs if the guest is using
928 * MSI or intends to start. */
929 if ((assigned_dev->irq_requested_type & KVM_DEV_IRQ_GUEST_MSI) ||
930 (ctrl_byte & PCI_MSI_FLAGS_ENABLE)) {
932 assigned_irq_data.flags = assigned_dev->irq_requested_type;
933 free_dev_irq_entries(assigned_dev);
934 r = kvm_deassign_irq(kvm_state, &assigned_irq_data);
935 /* -ENXIO means no assigned irq */
936 if (r && r != -ENXIO)
937 perror("assigned_dev_update_msi: deassign irq");
939 assigned_dev->irq_requested_type = 0;
942 if (ctrl_byte & PCI_MSI_FLAGS_ENABLE) {
943 uint8_t *pos = pci_dev->config + pci_dev->msi_cap;
945 assigned_dev->entry = g_malloc0(sizeof(*(assigned_dev->entry)));
946 assigned_dev->entry->u.msi.address_lo =
947 pci_get_long(pos + PCI_MSI_ADDRESS_LO);
948 assigned_dev->entry->u.msi.address_hi = 0;
949 assigned_dev->entry->u.msi.data = pci_get_word(pos + PCI_MSI_DATA_32);
950 assigned_dev->entry->type = KVM_IRQ_ROUTING_MSI;
951 r = kvm_get_irq_route_gsi();
952 if (r < 0) {
953 perror("assigned_dev_update_msi: kvm_get_irq_route_gsi");
954 return;
956 assigned_dev->entry->gsi = r;
958 kvm_add_routing_entry(assigned_dev->entry);
959 if (kvm_commit_irq_routes() < 0) {
960 perror("assigned_dev_update_msi: kvm_commit_irq_routes");
961 assigned_dev->cap.state &= ~ASSIGNED_DEVICE_MSI_ENABLED;
962 return;
964 assigned_dev->irq_entries_nr = 1;
966 assigned_irq_data.guest_irq = assigned_dev->entry->gsi;
967 assigned_irq_data.flags = KVM_DEV_IRQ_HOST_MSI | KVM_DEV_IRQ_GUEST_MSI;
968 if (kvm_assign_irq(kvm_state, &assigned_irq_data) < 0) {
969 perror("assigned_dev_enable_msi: assign irq");
972 assigned_dev->girq = -1;
973 assigned_dev->irq_requested_type = assigned_irq_data.flags;
974 } else {
975 assign_irq(assigned_dev);
979 static int assigned_dev_update_msix_mmio(PCIDevice *pci_dev)
981 AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
982 uint16_t entries_nr = 0, entries_max_nr;
983 int pos = 0, i, r = 0;
984 uint32_t msg_addr, msg_upper_addr, msg_data, msg_ctrl;
985 struct kvm_assigned_msix_nr msix_nr;
986 struct kvm_assigned_msix_entry msix_entry;
987 void *va = adev->msix_table_page;
989 pos = pci_find_capability(pci_dev, PCI_CAP_ID_MSIX);
991 entries_max_nr = *(uint16_t *)(pci_dev->config + pos + 2);
992 entries_max_nr &= PCI_MSIX_FLAGS_QSIZE;
993 entries_max_nr += 1;
995 /* Get the usable entry number for allocating */
996 for (i = 0; i < entries_max_nr; i++) {
997 memcpy(&msg_ctrl, va + i * 16 + 12, 4);
998 memcpy(&msg_data, va + i * 16 + 8, 4);
999 /* Ignore unused entry even it's unmasked */
1000 if (msg_data == 0)
1001 continue;
1002 entries_nr ++;
1005 if (entries_nr == 0) {
1006 fprintf(stderr, "MSI-X entry number is zero!\n");
1007 return -EINVAL;
1009 msix_nr.assigned_dev_id = calc_assigned_dev_id(adev);
1010 msix_nr.entry_nr = entries_nr;
1011 r = kvm_assign_set_msix_nr(kvm_state, &msix_nr);
1012 if (r != 0) {
1013 fprintf(stderr, "fail to set MSI-X entry number for MSIX! %s\n",
1014 strerror(-r));
1015 return r;
1018 free_dev_irq_entries(adev);
1019 adev->irq_entries_nr = entries_nr;
1020 adev->entry = g_malloc0(entries_nr * sizeof(*(adev->entry)));
1022 msix_entry.assigned_dev_id = msix_nr.assigned_dev_id;
1023 entries_nr = 0;
1024 for (i = 0; i < entries_max_nr; i++) {
1025 if (entries_nr >= msix_nr.entry_nr)
1026 break;
1027 memcpy(&msg_ctrl, va + i * 16 + 12, 4);
1028 memcpy(&msg_data, va + i * 16 + 8, 4);
1029 if (msg_data == 0)
1030 continue;
1032 memcpy(&msg_addr, va + i * 16, 4);
1033 memcpy(&msg_upper_addr, va + i * 16 + 4, 4);
1035 r = kvm_get_irq_route_gsi();
1036 if (r < 0)
1037 return r;
1039 adev->entry[entries_nr].gsi = r;
1040 adev->entry[entries_nr].type = KVM_IRQ_ROUTING_MSI;
1041 adev->entry[entries_nr].flags = 0;
1042 adev->entry[entries_nr].u.msi.address_lo = msg_addr;
1043 adev->entry[entries_nr].u.msi.address_hi = msg_upper_addr;
1044 adev->entry[entries_nr].u.msi.data = msg_data;
1045 DEBUG("MSI-X data 0x%x, MSI-X addr_lo 0x%x\n!", msg_data, msg_addr);
1046 kvm_add_routing_entry(&adev->entry[entries_nr]);
1048 msix_entry.gsi = adev->entry[entries_nr].gsi;
1049 msix_entry.entry = i;
1050 r = kvm_assign_set_msix_entry(kvm_state, &msix_entry);
1051 if (r) {
1052 fprintf(stderr, "fail to set MSI-X entry! %s\n", strerror(-r));
1053 break;
1055 DEBUG("MSI-X entry gsi 0x%x, entry %d\n!",
1056 msix_entry.gsi, msix_entry.entry);
1057 entries_nr ++;
1060 if (r == 0 && kvm_commit_irq_routes() < 0) {
1061 perror("assigned_dev_update_msix_mmio: kvm_commit_irq_routes");
1062 return -EINVAL;
1065 return r;
1068 static void assigned_dev_update_msix(PCIDevice *pci_dev)
1070 struct kvm_assigned_irq assigned_irq_data;
1071 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1072 uint16_t ctrl_word = pci_get_word(pci_dev->config + pci_dev->msix_cap +
1073 PCI_MSIX_FLAGS);
1074 int r;
1076 memset(&assigned_irq_data, 0, sizeof assigned_irq_data);
1077 assigned_irq_data.assigned_dev_id = calc_assigned_dev_id(assigned_dev);
1079 /* Some guests gratuitously disable MSIX even if they're not using it,
1080 * try to catch this by only deassigning irqs if the guest is using
1081 * MSIX or intends to start. */
1082 if ((assigned_dev->irq_requested_type & KVM_DEV_IRQ_GUEST_MSIX) ||
1083 (ctrl_word & PCI_MSIX_FLAGS_ENABLE)) {
1085 assigned_irq_data.flags = assigned_dev->irq_requested_type;
1086 free_dev_irq_entries(assigned_dev);
1087 r = kvm_deassign_irq(kvm_state, &assigned_irq_data);
1088 /* -ENXIO means no assigned irq */
1089 if (r && r != -ENXIO)
1090 perror("assigned_dev_update_msix: deassign irq");
1092 assigned_dev->irq_requested_type = 0;
1095 if (ctrl_word & PCI_MSIX_FLAGS_ENABLE) {
1096 assigned_irq_data.flags = KVM_DEV_IRQ_HOST_MSIX |
1097 KVM_DEV_IRQ_GUEST_MSIX;
1099 if (assigned_dev_update_msix_mmio(pci_dev) < 0) {
1100 perror("assigned_dev_update_msix_mmio");
1101 return;
1103 if (kvm_assign_irq(kvm_state, &assigned_irq_data) < 0) {
1104 perror("assigned_dev_enable_msix: assign irq");
1105 return;
1107 assigned_dev->girq = -1;
1108 assigned_dev->irq_requested_type = assigned_irq_data.flags;
1109 } else {
1110 assign_irq(assigned_dev);
1114 static uint32_t assigned_dev_pci_read_config(PCIDevice *pci_dev,
1115 uint32_t address, int len)
1117 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1118 uint32_t virt_val = pci_default_read_config(pci_dev, address, len);
1119 uint32_t real_val, emulate_mask, full_emulation_mask;
1121 emulate_mask = 0;
1122 memcpy(&emulate_mask, assigned_dev->emulate_config_read + address, len);
1123 emulate_mask = le32_to_cpu(emulate_mask);
1125 full_emulation_mask = 0xffffffff >> (32 - len * 8);
1127 if (emulate_mask != full_emulation_mask) {
1128 real_val = assigned_dev_pci_read(pci_dev, address, len);
1129 return (virt_val & emulate_mask) | (real_val & ~emulate_mask);
1130 } else {
1131 return virt_val;
1135 static void assigned_dev_pci_write_config(PCIDevice *pci_dev, uint32_t address,
1136 uint32_t val, int len)
1138 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1139 uint32_t emulate_mask, full_emulation_mask;
1141 pci_default_write_config(pci_dev, address, val, len);
1143 if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
1144 if (range_covers_byte(address, len,
1145 pci_dev->msi_cap + PCI_MSI_FLAGS)) {
1146 assigned_dev_update_msi(pci_dev);
1149 if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1150 if (range_covers_byte(address, len,
1151 pci_dev->msix_cap + PCI_MSIX_FLAGS + 1)) {
1152 assigned_dev_update_msix(pci_dev);
1156 emulate_mask = 0;
1157 memcpy(&emulate_mask, assigned_dev->emulate_config_write + address, len);
1158 emulate_mask = le32_to_cpu(emulate_mask);
1160 full_emulation_mask = 0xffffffff >> (32 - len * 8);
1162 if (emulate_mask != full_emulation_mask) {
1163 if (emulate_mask) {
1164 val &= ~emulate_mask;
1165 val |= assigned_dev_pci_read(pci_dev, address, len) & emulate_mask;
1167 assigned_dev_pci_write(pci_dev, address, val, len);
1171 static void assigned_dev_setup_cap_read(AssignedDevice *dev, uint32_t offset,
1172 uint32_t len)
1174 assigned_dev_direct_config_read(dev, offset, len);
1175 assigned_dev_emulate_config_read(dev, offset + PCI_CAP_LIST_NEXT, 1);
1178 static int assigned_device_pci_cap_init(PCIDevice *pci_dev)
1180 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1181 PCIRegion *pci_region = dev->real_device.regions;
1182 int ret, pos;
1184 /* Clear initial capabilities pointer and status copied from hw */
1185 pci_set_byte(pci_dev->config + PCI_CAPABILITY_LIST, 0);
1186 pci_set_word(pci_dev->config + PCI_STATUS,
1187 pci_get_word(pci_dev->config + PCI_STATUS) &
1188 ~PCI_STATUS_CAP_LIST);
1190 /* Expose MSI capability
1191 * MSI capability is the 1st capability in capability config */
1192 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSI, 0);
1193 if (pos != 0 && kvm_check_extension(kvm_state, KVM_CAP_ASSIGN_DEV_IRQ)) {
1194 dev->cap.available |= ASSIGNED_DEVICE_CAP_MSI;
1195 /* Only 32-bit/no-mask currently supported */
1196 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSI, pos, 10)) < 0) {
1197 return ret;
1199 pci_dev->msi_cap = pos;
1201 pci_set_word(pci_dev->config + pos + PCI_MSI_FLAGS,
1202 pci_get_word(pci_dev->config + pos + PCI_MSI_FLAGS) &
1203 PCI_MSI_FLAGS_QMASK);
1204 pci_set_long(pci_dev->config + pos + PCI_MSI_ADDRESS_LO, 0);
1205 pci_set_word(pci_dev->config + pos + PCI_MSI_DATA_32, 0);
1207 /* Set writable fields */
1208 pci_set_word(pci_dev->wmask + pos + PCI_MSI_FLAGS,
1209 PCI_MSI_FLAGS_QSIZE | PCI_MSI_FLAGS_ENABLE);
1210 pci_set_long(pci_dev->wmask + pos + PCI_MSI_ADDRESS_LO, 0xfffffffc);
1211 pci_set_word(pci_dev->wmask + pos + PCI_MSI_DATA_32, 0xffff);
1213 /* Expose MSI-X capability */
1214 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSIX, 0);
1215 /* Would really like to test kvm_check_extension(, KVM_CAP_DEVICE_MSIX),
1216 * but the kernel doesn't expose it. Instead do a dummy call to
1217 * KVM_ASSIGN_SET_MSIX_NR to see if it exists. */
1218 if (pos != 0 && kvm_assign_set_msix_nr(kvm_state, NULL) == -EFAULT) {
1219 int bar_nr;
1220 uint32_t msix_table_entry;
1222 dev->cap.available |= ASSIGNED_DEVICE_CAP_MSIX;
1223 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSIX, pos, 12)) < 0) {
1224 return ret;
1226 pci_dev->msix_cap = pos;
1228 pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS,
1229 pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) &
1230 PCI_MSIX_FLAGS_QSIZE);
1232 /* Only enable and function mask bits are writable */
1233 pci_set_word(pci_dev->wmask + pos + PCI_MSIX_FLAGS,
1234 PCI_MSIX_FLAGS_ENABLE | PCI_MSIX_FLAGS_MASKALL);
1236 msix_table_entry = pci_get_long(pci_dev->config + pos + PCI_MSIX_TABLE);
1237 bar_nr = msix_table_entry & PCI_MSIX_FLAGS_BIRMASK;
1238 msix_table_entry &= ~PCI_MSIX_FLAGS_BIRMASK;
1239 dev->msix_table_addr = pci_region[bar_nr].base_addr + msix_table_entry;
1242 /* Minimal PM support, nothing writable, device appears to NAK changes */
1243 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PM, 0))) {
1244 uint16_t pmc;
1245 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, pos,
1246 PCI_PM_SIZEOF)) < 0) {
1247 return ret;
1250 assigned_dev_setup_cap_read(dev, pos, PCI_PM_SIZEOF);
1252 pmc = pci_get_word(pci_dev->config + pos + PCI_CAP_FLAGS);
1253 pmc &= (PCI_PM_CAP_VER_MASK | PCI_PM_CAP_DSI);
1254 pci_set_word(pci_dev->config + pos + PCI_CAP_FLAGS, pmc);
1256 /* assign_device will bring the device up to D0, so we don't need
1257 * to worry about doing that ourselves here. */
1258 pci_set_word(pci_dev->config + pos + PCI_PM_CTRL,
1259 PCI_PM_CTRL_NO_SOFT_RESET);
1261 pci_set_byte(pci_dev->config + pos + PCI_PM_PPB_EXTENSIONS, 0);
1262 pci_set_byte(pci_dev->config + pos + PCI_PM_DATA_REGISTER, 0);
1265 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_EXP, 0))) {
1266 uint8_t version, size;
1267 uint16_t type, devctl, lnkcap, lnksta;
1268 uint32_t devcap;
1270 version = pci_get_byte(pci_dev->config + pos + PCI_EXP_FLAGS);
1271 version &= PCI_EXP_FLAGS_VERS;
1272 if (version == 1) {
1273 size = 0x14;
1274 } else if (version == 2) {
1276 * Check for non-std size, accept reduced size to 0x34,
1277 * which is what bcm5761 implemented, violating the
1278 * PCIe v3.0 spec that regs should exist and be read as 0,
1279 * not optionally provided and shorten the struct size.
1281 size = MIN(0x3c, PCI_CONFIG_SPACE_SIZE - pos);
1282 if (size < 0x34) {
1283 fprintf(stderr,
1284 "%s: Invalid size PCIe cap-id 0x%x \n",
1285 __func__, PCI_CAP_ID_EXP);
1286 return -EINVAL;
1287 } else if (size != 0x3c) {
1288 fprintf(stderr,
1289 "WARNING, %s: PCIe cap-id 0x%x has "
1290 "non-standard size 0x%x; std size should be 0x3c \n",
1291 __func__, PCI_CAP_ID_EXP, size);
1293 } else {
1294 fprintf(stderr,
1295 "%s: Unsupported PCI express capability version %d\n",
1296 __func__, version);
1297 return -EINVAL;
1300 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_EXP,
1301 pos, size)) < 0) {
1302 return ret;
1305 assigned_dev_setup_cap_read(dev, pos, size);
1307 type = pci_get_word(pci_dev->config + pos + PCI_EXP_FLAGS);
1308 type = (type & PCI_EXP_FLAGS_TYPE) >> 8;
1309 if (type != PCI_EXP_TYPE_ENDPOINT &&
1310 type != PCI_EXP_TYPE_LEG_END && type != PCI_EXP_TYPE_RC_END) {
1311 fprintf(stderr,
1312 "Device assignment only supports endpoint assignment, "
1313 "device type %d\n", type);
1314 return -EINVAL;
1317 /* capabilities, pass existing read-only copy
1318 * PCI_EXP_FLAGS_IRQ: updated by hardware, should be direct read */
1320 /* device capabilities: hide FLR */
1321 devcap = pci_get_long(pci_dev->config + pos + PCI_EXP_DEVCAP);
1322 devcap &= ~PCI_EXP_DEVCAP_FLR;
1323 pci_set_long(pci_dev->config + pos + PCI_EXP_DEVCAP, devcap);
1325 /* device control: clear all error reporting enable bits, leaving
1326 * leaving only a few host values. Note, these are
1327 * all writable, but not passed to hw.
1329 devctl = pci_get_word(pci_dev->config + pos + PCI_EXP_DEVCTL);
1330 devctl = (devctl & (PCI_EXP_DEVCTL_READRQ | PCI_EXP_DEVCTL_PAYLOAD)) |
1331 PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN;
1332 pci_set_word(pci_dev->config + pos + PCI_EXP_DEVCTL, devctl);
1333 devctl = PCI_EXP_DEVCTL_BCR_FLR | PCI_EXP_DEVCTL_AUX_PME;
1334 pci_set_word(pci_dev->wmask + pos + PCI_EXP_DEVCTL, ~devctl);
1336 /* Clear device status */
1337 pci_set_word(pci_dev->config + pos + PCI_EXP_DEVSTA, 0);
1339 /* Link capabilities, expose links and latencues, clear reporting */
1340 lnkcap = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKCAP);
1341 lnkcap &= (PCI_EXP_LNKCAP_SLS | PCI_EXP_LNKCAP_MLW |
1342 PCI_EXP_LNKCAP_ASPMS | PCI_EXP_LNKCAP_L0SEL |
1343 PCI_EXP_LNKCAP_L1EL);
1344 pci_set_word(pci_dev->config + pos + PCI_EXP_LNKCAP, lnkcap);
1345 pci_set_word(pci_dev->wmask + pos + PCI_EXP_LNKCAP,
1346 PCI_EXP_LNKCTL_ASPMC | PCI_EXP_LNKCTL_RCB |
1347 PCI_EXP_LNKCTL_CCC | PCI_EXP_LNKCTL_ES |
1348 PCI_EXP_LNKCTL_CLKREQ_EN | PCI_EXP_LNKCTL_HAWD);
1350 /* Link control, pass existing read-only copy. Should be writable? */
1352 /* Link status, only expose current speed and width */
1353 lnksta = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKSTA);
1354 lnksta &= (PCI_EXP_LNKSTA_CLS | PCI_EXP_LNKSTA_NLW);
1355 pci_set_word(pci_dev->config + pos + PCI_EXP_LNKSTA, lnksta);
1357 if (version >= 2) {
1358 /* Slot capabilities, control, status - not needed for endpoints */
1359 pci_set_long(pci_dev->config + pos + PCI_EXP_SLTCAP, 0);
1360 pci_set_word(pci_dev->config + pos + PCI_EXP_SLTCTL, 0);
1361 pci_set_word(pci_dev->config + pos + PCI_EXP_SLTSTA, 0);
1363 /* Root control, capabilities, status - not needed for endpoints */
1364 pci_set_word(pci_dev->config + pos + PCI_EXP_RTCTL, 0);
1365 pci_set_word(pci_dev->config + pos + PCI_EXP_RTCAP, 0);
1366 pci_set_long(pci_dev->config + pos + PCI_EXP_RTSTA, 0);
1368 /* Device capabilities/control 2, pass existing read-only copy */
1369 /* Link control 2, pass existing read-only copy */
1373 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PCIX, 0))) {
1374 uint16_t cmd;
1375 uint32_t status;
1377 /* Only expose the minimum, 8 byte capability */
1378 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_PCIX, pos, 8)) < 0) {
1379 return ret;
1382 assigned_dev_setup_cap_read(dev, pos, 8);
1384 /* Command register, clear upper bits, including extended modes */
1385 cmd = pci_get_word(pci_dev->config + pos + PCI_X_CMD);
1386 cmd &= (PCI_X_CMD_DPERR_E | PCI_X_CMD_ERO | PCI_X_CMD_MAX_READ |
1387 PCI_X_CMD_MAX_SPLIT);
1388 pci_set_word(pci_dev->config + pos + PCI_X_CMD, cmd);
1390 /* Status register, update with emulated PCI bus location, clear
1391 * error bits, leave the rest. */
1392 status = pci_get_long(pci_dev->config + pos + PCI_X_STATUS);
1393 status &= ~(PCI_X_STATUS_BUS | PCI_X_STATUS_DEVFN);
1394 status |= (pci_bus_num(pci_dev->bus) << 8) | pci_dev->devfn;
1395 status &= ~(PCI_X_STATUS_SPL_DISC | PCI_X_STATUS_UNX_SPL |
1396 PCI_X_STATUS_SPL_ERR);
1397 pci_set_long(pci_dev->config + pos + PCI_X_STATUS, status);
1400 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VPD, 0))) {
1401 /* Direct R/W passthrough */
1402 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_VPD, pos, 8)) < 0) {
1403 return ret;
1406 assigned_dev_setup_cap_read(dev, pos, 8);
1408 /* direct write for cap content */
1409 assigned_dev_direct_config_write(dev, pos + 2, 6);
1412 /* Devices can have multiple vendor capabilities, get them all */
1413 for (pos = 0; (pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VNDR, pos));
1414 pos += PCI_CAP_LIST_NEXT) {
1415 uint8_t len = pci_get_byte(pci_dev->config + pos + PCI_CAP_FLAGS);
1416 /* Direct R/W passthrough */
1417 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_VNDR,
1418 pos, len)) < 0) {
1419 return ret;
1422 assigned_dev_setup_cap_read(dev, pos, len);
1424 /* direct write for cap content */
1425 assigned_dev_direct_config_write(dev, pos + 2, len - 2);
1428 /* If real and virtual capability list status bits differ, virtualize the
1429 * access. */
1430 if ((pci_get_word(pci_dev->config + PCI_STATUS) & PCI_STATUS_CAP_LIST) !=
1431 (assigned_dev_pci_read_byte(pci_dev, PCI_STATUS) &
1432 PCI_STATUS_CAP_LIST)) {
1433 dev->emulate_config_read[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1436 return 0;
1439 static uint32_t msix_mmio_readl(void *opaque, target_phys_addr_t addr)
1441 AssignedDevice *adev = opaque;
1442 unsigned int offset = addr & 0xfff;
1443 void *page = adev->msix_table_page;
1444 uint32_t val = 0;
1446 memcpy(&val, (void *)((char *)page + offset), 4);
1448 return val;
1451 static uint32_t msix_mmio_readb(void *opaque, target_phys_addr_t addr)
1453 return ((msix_mmio_readl(opaque, addr & ~3)) >>
1454 (8 * (addr & 3))) & 0xff;
1457 static uint32_t msix_mmio_readw(void *opaque, target_phys_addr_t addr)
1459 return ((msix_mmio_readl(opaque, addr & ~3)) >>
1460 (8 * (addr & 3))) & 0xffff;
1463 static void msix_mmio_writel(void *opaque,
1464 target_phys_addr_t addr, uint32_t val)
1466 AssignedDevice *adev = opaque;
1467 unsigned int offset = addr & 0xfff;
1468 void *page = adev->msix_table_page;
1470 DEBUG("write to MSI-X entry table mmio offset 0x%lx, val 0x%x\n",
1471 addr, val);
1472 memcpy((void *)((char *)page + offset), &val, 4);
1475 static void msix_mmio_writew(void *opaque,
1476 target_phys_addr_t addr, uint32_t val)
1478 msix_mmio_writel(opaque, addr & ~3,
1479 (val & 0xffff) << (8*(addr & 3)));
1482 static void msix_mmio_writeb(void *opaque,
1483 target_phys_addr_t addr, uint32_t val)
1485 msix_mmio_writel(opaque, addr & ~3,
1486 (val & 0xff) << (8*(addr & 3)));
1489 static const MemoryRegionOps msix_mmio_ops = {
1490 .old_mmio = {
1491 .read = { msix_mmio_readb, msix_mmio_readw, msix_mmio_readl, },
1492 .write = { msix_mmio_writeb, msix_mmio_writew, msix_mmio_writel, },
1494 .endianness = DEVICE_NATIVE_ENDIAN,
1497 static int assigned_dev_register_msix_mmio(AssignedDevice *dev)
1499 dev->msix_table_page = mmap(NULL, 0x1000,
1500 PROT_READ|PROT_WRITE,
1501 MAP_ANONYMOUS|MAP_PRIVATE, 0, 0);
1502 if (dev->msix_table_page == MAP_FAILED) {
1503 fprintf(stderr, "fail allocate msix_table_page! %s\n",
1504 strerror(errno));
1505 return -EFAULT;
1507 memset(dev->msix_table_page, 0, 0x1000);
1508 memory_region_init_io(&dev->mmio, &msix_mmio_ops, dev,
1509 "assigned-dev-msix", MSIX_PAGE_SIZE);
1510 return 0;
1513 static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev)
1515 if (!dev->msix_table_page)
1516 return;
1518 memory_region_destroy(&dev->mmio);
1520 if (munmap(dev->msix_table_page, 0x1000) == -1) {
1521 fprintf(stderr, "error unmapping msix_table_page! %s\n",
1522 strerror(errno));
1524 dev->msix_table_page = NULL;
1527 static const VMStateDescription vmstate_assigned_device = {
1528 .name = "pci-assign",
1529 .unmigratable = 1,
1532 static void reset_assigned_device(DeviceState *dev)
1534 PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
1535 AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1536 char reset_file[64];
1537 const char reset[] = "1";
1538 int fd, ret;
1540 snprintf(reset_file, sizeof(reset_file),
1541 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/reset",
1542 adev->host.seg, adev->host.bus, adev->host.dev, adev->host.func);
1545 * Issue a device reset via pci-sysfs. Note that we use write(2) here
1546 * and ignore the return value because some kernels have a bug that
1547 * returns 0 rather than bytes written on success, sending us into an
1548 * infinite retry loop using other write mechanisms.
1550 fd = open(reset_file, O_WRONLY);
1551 if (fd != -1) {
1552 ret = write(fd, reset, strlen(reset));
1553 (void)ret;
1554 close(fd);
1558 * When a 0 is written to the command register, the device is logically
1559 * disconnected from the PCI bus. This avoids further DMA transfers.
1561 assigned_dev_pci_write_config(pci_dev, PCI_COMMAND, 0, 2);
1564 static int assigned_initfn(struct PCIDevice *pci_dev)
1566 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1567 uint8_t e_intx;
1568 int r;
1570 if (!kvm_enabled()) {
1571 error_report("pci-assign: error: requires KVM support");
1572 return -1;
1575 if (!dev->host.seg && !dev->host.bus && !dev->host.dev && !dev->host.func) {
1576 error_report("pci-assign: error: no host device specified");
1577 return -1;
1581 * Set up basic config space access control. Will be further refined during
1582 * device initialization.
1584 assigned_dev_emulate_config_read(dev, 0, PCI_CONFIG_SPACE_SIZE);
1585 assigned_dev_direct_config_read(dev, PCI_COMMAND, 2);
1586 assigned_dev_direct_config_read(dev, PCI_STATUS, 2);
1587 assigned_dev_direct_config_read(dev, PCI_REVISION_ID, 1);
1588 assigned_dev_direct_config_read(dev, PCI_CLASS_PROG, 3);
1589 assigned_dev_direct_config_read(dev, PCI_CACHE_LINE_SIZE, 1);
1590 assigned_dev_direct_config_read(dev, PCI_LATENCY_TIMER, 1);
1591 assigned_dev_direct_config_read(dev, PCI_HEADER_TYPE, 1);
1592 assigned_dev_direct_config_read(dev, PCI_BIST, 1);
1593 assigned_dev_direct_config_read(dev, PCI_CARDBUS_CIS, 4);
1594 assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_VENDOR_ID, 2);
1595 assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_ID, 2);
1596 assigned_dev_direct_config_read(dev, PCI_CAPABILITY_LIST + 1, 7);
1597 assigned_dev_direct_config_read(dev, PCI_MIN_GNT, 1);
1598 assigned_dev_direct_config_read(dev, PCI_MAX_LAT, 1);
1599 memcpy(dev->emulate_config_write, dev->emulate_config_read,
1600 sizeof(dev->emulate_config_read));
1602 if (get_real_device(dev, dev->host.seg, dev->host.bus,
1603 dev->host.dev, dev->host.func)) {
1604 error_report("pci-assign: Error: Couldn't get real device (%s)!",
1605 dev->dev.qdev.id);
1606 goto out;
1609 if (assigned_device_pci_cap_init(pci_dev) < 0) {
1610 goto out;
1613 /* intercept MSI-X entry page in the MMIO */
1614 if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1615 if (assigned_dev_register_msix_mmio(dev)) {
1616 goto out;
1620 /* handle real device's MMIO/PIO BARs */
1621 if (assigned_dev_register_regions(dev->real_device.regions,
1622 dev->real_device.region_number,
1623 dev))
1624 goto out;
1626 /* handle interrupt routing */
1627 e_intx = dev->dev.config[0x3d] - 1;
1628 dev->intpin = e_intx;
1629 dev->run = 0;
1630 dev->girq = -1;
1631 dev->h_segnr = dev->host.seg;
1632 dev->h_busnr = dev->host.bus;
1633 dev->h_devfn = PCI_DEVFN(dev->host.dev, dev->host.func);
1635 /* assign device to guest */
1636 r = assign_device(dev);
1637 if (r < 0)
1638 goto out;
1640 /* assign irq for the device */
1641 r = assign_irq(dev);
1642 if (r < 0)
1643 goto assigned_out;
1645 assigned_dev_load_option_rom(dev);
1646 QLIST_INSERT_HEAD(&devs, dev, next);
1648 add_boot_device_path(dev->bootindex, &pci_dev->qdev, NULL);
1650 return 0;
1652 assigned_out:
1653 deassign_device(dev);
1654 out:
1655 free_assigned_device(dev);
1656 return -1;
1659 static int assigned_exitfn(struct PCIDevice *pci_dev)
1661 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1663 QLIST_REMOVE(dev, next);
1664 deassign_device(dev);
1665 free_assigned_device(dev);
1666 return 0;
1669 static int parse_hostaddr(DeviceState *dev, Property *prop, const char *str)
1671 PCIHostDevice *ptr = qdev_get_prop_ptr(dev, prop);
1672 int rc;
1674 rc = pci_parse_host_devaddr(str, &ptr->seg, &ptr->bus, &ptr->dev, &ptr->func);
1675 if (rc != 0)
1676 return -1;
1677 return 0;
1680 static int print_hostaddr(DeviceState *dev, Property *prop, char *dest, size_t len)
1682 PCIHostDevice *ptr = qdev_get_prop_ptr(dev, prop);
1684 return snprintf(dest, len, "%02x:%02x.%x", ptr->bus, ptr->dev, ptr->func);
1687 PropertyInfo qdev_prop_hostaddr = {
1688 .name = "pci-hostaddr",
1689 .type = -1,
1690 .size = sizeof(PCIHostDevice),
1691 .parse = parse_hostaddr,
1692 .print = print_hostaddr,
1695 static PCIDeviceInfo assign_info = {
1696 .qdev.name = "pci-assign",
1697 .qdev.desc = "pass through host pci devices to the guest",
1698 .qdev.size = sizeof(AssignedDevice),
1699 .qdev.vmsd = &vmstate_assigned_device,
1700 .qdev.reset = reset_assigned_device,
1701 .init = assigned_initfn,
1702 .exit = assigned_exitfn,
1703 .config_read = assigned_dev_pci_read_config,
1704 .config_write = assigned_dev_pci_write_config,
1705 .qdev.props = (Property[]) {
1706 DEFINE_PROP("host", AssignedDevice, host, qdev_prop_hostaddr, PCIHostDevice),
1707 DEFINE_PROP_BIT("iommu", AssignedDevice, features,
1708 ASSIGNED_DEVICE_USE_IOMMU_BIT, true),
1709 DEFINE_PROP_BIT("prefer_msi", AssignedDevice, features,
1710 ASSIGNED_DEVICE_PREFER_MSI_BIT, true),
1711 DEFINE_PROP_INT32("bootindex", AssignedDevice, bootindex, -1),
1712 DEFINE_PROP_STRING("configfd", AssignedDevice, configfd_name),
1713 DEFINE_PROP_END_OF_LIST(),
1717 static void assign_register_devices(void)
1719 pci_qdev_register(&assign_info);
1722 device_init(assign_register_devices)
1725 * Scan the assigned devices for the devices that have an option ROM, and then
1726 * load the corresponding ROM data to RAM. If an error occurs while loading an
1727 * option ROM, we just ignore that option ROM and continue with the next one.
1729 static void assigned_dev_load_option_rom(AssignedDevice *dev)
1731 char name[32], rom_file[64];
1732 FILE *fp;
1733 uint8_t val;
1734 struct stat st;
1735 void *ptr;
1737 /* If loading ROM from file, pci handles it */
1738 if (dev->dev.romfile || !dev->dev.rom_bar)
1739 return;
1741 snprintf(rom_file, sizeof(rom_file),
1742 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/rom",
1743 dev->host.seg, dev->host.bus, dev->host.dev, dev->host.func);
1745 if (stat(rom_file, &st)) {
1746 return;
1749 if (access(rom_file, F_OK)) {
1750 fprintf(stderr, "pci-assign: Insufficient privileges for %s\n",
1751 rom_file);
1752 return;
1755 /* Write "1" to the ROM file to enable it */
1756 fp = fopen(rom_file, "r+");
1757 if (fp == NULL) {
1758 return;
1760 val = 1;
1761 if (fwrite(&val, 1, 1, fp) != 1) {
1762 goto close_rom;
1764 fseek(fp, 0, SEEK_SET);
1766 snprintf(name, sizeof(name), "%s.rom", dev->dev.qdev.info->name);
1767 memory_region_init_ram(&dev->dev.rom, &dev->dev.qdev, name, st.st_size);
1768 ptr = memory_region_get_ram_ptr(&dev->dev.rom);
1769 memset(ptr, 0xff, st.st_size);
1771 if (!fread(ptr, 1, st.st_size, fp)) {
1772 fprintf(stderr, "pci-assign: Cannot read from host %s\n"
1773 "\tDevice option ROM contents are probably invalid "
1774 "(check dmesg).\n\tSkip option ROM probe with rombar=0, "
1775 "or load from file with romfile=\n", rom_file);
1776 memory_region_destroy(&dev->dev.rom);
1777 goto close_rom;
1780 pci_register_bar(&dev->dev, PCI_ROM_SLOT, 0, &dev->dev.rom);
1781 dev->dev.has_rom = true;
1782 close_rom:
1783 /* Write "0" to disable ROM */
1784 fseek(fp, 0, SEEK_SET);
1785 val = 0;
1786 if (!fwrite(&val, 1, 1, fp)) {
1787 DEBUG("%s\n", "Failed to disable pci-sysfs rom file");
1789 fclose(fp);