qemu-kvm: Remove broken ia64 fragments
[qemu-kvm.git] / hw / device-assignment.c
blob0bd2cd0573553013a21ea34f9eedd0302c2134be
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 if (dev->girq == irq)
823 return r;
825 memset(&assigned_irq_data, 0, sizeof(assigned_irq_data));
826 assigned_irq_data.assigned_dev_id = calc_assigned_dev_id(dev);
827 assigned_irq_data.guest_irq = irq;
828 assigned_irq_data.host_irq = dev->real_device.irq;
829 if (dev->irq_requested_type) {
830 assigned_irq_data.flags = dev->irq_requested_type;
831 r = kvm_deassign_irq(kvm_state, &assigned_irq_data);
832 if (r) {
833 perror("assign_irq: deassign");
835 dev->irq_requested_type = 0;
838 assigned_irq_data.flags = KVM_DEV_IRQ_GUEST_INTX;
839 if (dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK &&
840 dev->cap.available & ASSIGNED_DEVICE_CAP_MSI)
841 assigned_irq_data.flags |= KVM_DEV_IRQ_HOST_MSI;
842 else
843 assigned_irq_data.flags |= KVM_DEV_IRQ_HOST_INTX;
845 r = kvm_assign_irq(kvm_state, &assigned_irq_data);
846 if (r < 0) {
847 fprintf(stderr, "Failed to assign irq for \"%s\": %s\n",
848 dev->dev.qdev.id, strerror(-r));
849 fprintf(stderr, "Perhaps you are assigning a device "
850 "that shares an IRQ with another device?\n");
851 return r;
854 dev->girq = irq;
855 dev->irq_requested_type = assigned_irq_data.flags;
856 return r;
859 static void deassign_device(AssignedDevice *dev)
861 struct kvm_assigned_pci_dev assigned_dev_data;
862 int r;
864 memset(&assigned_dev_data, 0, sizeof(assigned_dev_data));
865 assigned_dev_data.assigned_dev_id = calc_assigned_dev_id(dev);
867 r = kvm_deassign_pci_device(kvm_state, &assigned_dev_data);
868 if (r < 0)
869 fprintf(stderr, "Failed to deassign device \"%s\" : %s\n",
870 dev->dev.qdev.id, strerror(-r));
873 #if 0
874 AssignedDevInfo *get_assigned_device(int pcibus, int slot)
876 AssignedDevice *assigned_dev = NULL;
877 AssignedDevInfo *adev = NULL;
879 QLIST_FOREACH(adev, &adev_head, next) {
880 assigned_dev = adev->assigned_dev;
881 if (pci_bus_num(assigned_dev->dev.bus) == pcibus &&
882 PCI_SLOT(assigned_dev->dev.devfn) == slot)
883 return adev;
886 return NULL;
888 #endif
890 /* The pci config space got updated. Check if irq numbers have changed
891 * for our devices
893 void assigned_dev_update_irqs(void)
895 AssignedDevice *dev, *next;
896 int r;
898 dev = QLIST_FIRST(&devs);
899 while (dev) {
900 next = QLIST_NEXT(dev, next);
901 if (dev->irq_requested_type & KVM_DEV_IRQ_HOST_INTX) {
902 r = assign_irq(dev);
903 if (r < 0) {
904 qdev_unplug(&dev->dev.qdev);
907 dev = next;
911 static void assigned_dev_update_msi(PCIDevice *pci_dev)
913 struct kvm_assigned_irq assigned_irq_data;
914 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
915 uint8_t ctrl_byte = pci_get_byte(pci_dev->config + pci_dev->msi_cap +
916 PCI_MSI_FLAGS);
917 int r;
919 memset(&assigned_irq_data, 0, sizeof assigned_irq_data);
920 assigned_irq_data.assigned_dev_id = calc_assigned_dev_id(assigned_dev);
922 /* Some guests gratuitously disable MSI even if they're not using it,
923 * try to catch this by only deassigning irqs if the guest is using
924 * MSI or intends to start. */
925 if ((assigned_dev->irq_requested_type & KVM_DEV_IRQ_GUEST_MSI) ||
926 (ctrl_byte & PCI_MSI_FLAGS_ENABLE)) {
928 assigned_irq_data.flags = assigned_dev->irq_requested_type;
929 free_dev_irq_entries(assigned_dev);
930 r = kvm_deassign_irq(kvm_state, &assigned_irq_data);
931 /* -ENXIO means no assigned irq */
932 if (r && r != -ENXIO)
933 perror("assigned_dev_update_msi: deassign irq");
935 assigned_dev->irq_requested_type = 0;
938 if (ctrl_byte & PCI_MSI_FLAGS_ENABLE) {
939 uint8_t *pos = pci_dev->config + pci_dev->msi_cap;
941 assigned_dev->entry = g_malloc0(sizeof(*(assigned_dev->entry)));
942 assigned_dev->entry->u.msi.address_lo =
943 pci_get_long(pos + PCI_MSI_ADDRESS_LO);
944 assigned_dev->entry->u.msi.address_hi = 0;
945 assigned_dev->entry->u.msi.data = pci_get_word(pos + PCI_MSI_DATA_32);
946 assigned_dev->entry->type = KVM_IRQ_ROUTING_MSI;
947 r = kvm_get_irq_route_gsi();
948 if (r < 0) {
949 perror("assigned_dev_update_msi: kvm_get_irq_route_gsi");
950 return;
952 assigned_dev->entry->gsi = r;
954 kvm_add_routing_entry(assigned_dev->entry);
955 if (kvm_commit_irq_routes() < 0) {
956 perror("assigned_dev_update_msi: kvm_commit_irq_routes");
957 assigned_dev->cap.state &= ~ASSIGNED_DEVICE_MSI_ENABLED;
958 return;
960 assigned_dev->irq_entries_nr = 1;
962 assigned_irq_data.guest_irq = assigned_dev->entry->gsi;
963 assigned_irq_data.flags = KVM_DEV_IRQ_HOST_MSI | KVM_DEV_IRQ_GUEST_MSI;
964 if (kvm_assign_irq(kvm_state, &assigned_irq_data) < 0) {
965 perror("assigned_dev_enable_msi: assign irq");
968 assigned_dev->girq = -1;
969 assigned_dev->irq_requested_type = assigned_irq_data.flags;
970 } else {
971 assign_irq(assigned_dev);
975 static int assigned_dev_update_msix_mmio(PCIDevice *pci_dev)
977 AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
978 uint16_t entries_nr = 0, entries_max_nr;
979 int pos = 0, i, r = 0;
980 uint32_t msg_addr, msg_upper_addr, msg_data, msg_ctrl;
981 struct kvm_assigned_msix_nr msix_nr;
982 struct kvm_assigned_msix_entry msix_entry;
983 void *va = adev->msix_table_page;
985 pos = pci_find_capability(pci_dev, PCI_CAP_ID_MSIX);
987 entries_max_nr = *(uint16_t *)(pci_dev->config + pos + 2);
988 entries_max_nr &= PCI_MSIX_FLAGS_QSIZE;
989 entries_max_nr += 1;
991 /* Get the usable entry number for allocating */
992 for (i = 0; i < entries_max_nr; i++) {
993 memcpy(&msg_ctrl, va + i * 16 + 12, 4);
994 memcpy(&msg_data, va + i * 16 + 8, 4);
995 /* Ignore unused entry even it's unmasked */
996 if (msg_data == 0)
997 continue;
998 entries_nr ++;
1001 if (entries_nr == 0) {
1002 fprintf(stderr, "MSI-X entry number is zero!\n");
1003 return -EINVAL;
1005 msix_nr.assigned_dev_id = calc_assigned_dev_id(adev);
1006 msix_nr.entry_nr = entries_nr;
1007 r = kvm_assign_set_msix_nr(kvm_state, &msix_nr);
1008 if (r != 0) {
1009 fprintf(stderr, "fail to set MSI-X entry number for MSIX! %s\n",
1010 strerror(-r));
1011 return r;
1014 free_dev_irq_entries(adev);
1015 adev->irq_entries_nr = entries_nr;
1016 adev->entry = g_malloc0(entries_nr * sizeof(*(adev->entry)));
1018 msix_entry.assigned_dev_id = msix_nr.assigned_dev_id;
1019 entries_nr = 0;
1020 for (i = 0; i < entries_max_nr; i++) {
1021 if (entries_nr >= msix_nr.entry_nr)
1022 break;
1023 memcpy(&msg_ctrl, va + i * 16 + 12, 4);
1024 memcpy(&msg_data, va + i * 16 + 8, 4);
1025 if (msg_data == 0)
1026 continue;
1028 memcpy(&msg_addr, va + i * 16, 4);
1029 memcpy(&msg_upper_addr, va + i * 16 + 4, 4);
1031 r = kvm_get_irq_route_gsi();
1032 if (r < 0)
1033 return r;
1035 adev->entry[entries_nr].gsi = r;
1036 adev->entry[entries_nr].type = KVM_IRQ_ROUTING_MSI;
1037 adev->entry[entries_nr].flags = 0;
1038 adev->entry[entries_nr].u.msi.address_lo = msg_addr;
1039 adev->entry[entries_nr].u.msi.address_hi = msg_upper_addr;
1040 adev->entry[entries_nr].u.msi.data = msg_data;
1041 DEBUG("MSI-X data 0x%x, MSI-X addr_lo 0x%x\n!", msg_data, msg_addr);
1042 kvm_add_routing_entry(&adev->entry[entries_nr]);
1044 msix_entry.gsi = adev->entry[entries_nr].gsi;
1045 msix_entry.entry = i;
1046 r = kvm_assign_set_msix_entry(kvm_state, &msix_entry);
1047 if (r) {
1048 fprintf(stderr, "fail to set MSI-X entry! %s\n", strerror(-r));
1049 break;
1051 DEBUG("MSI-X entry gsi 0x%x, entry %d\n!",
1052 msix_entry.gsi, msix_entry.entry);
1053 entries_nr ++;
1056 if (r == 0 && kvm_commit_irq_routes() < 0) {
1057 perror("assigned_dev_update_msix_mmio: kvm_commit_irq_routes");
1058 return -EINVAL;
1061 return r;
1064 static void assigned_dev_update_msix(PCIDevice *pci_dev)
1066 struct kvm_assigned_irq assigned_irq_data;
1067 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1068 uint16_t ctrl_word = pci_get_word(pci_dev->config + pci_dev->msix_cap +
1069 PCI_MSIX_FLAGS);
1070 int r;
1072 memset(&assigned_irq_data, 0, sizeof assigned_irq_data);
1073 assigned_irq_data.assigned_dev_id = calc_assigned_dev_id(assigned_dev);
1075 /* Some guests gratuitously disable MSIX even if they're not using it,
1076 * try to catch this by only deassigning irqs if the guest is using
1077 * MSIX or intends to start. */
1078 if ((assigned_dev->irq_requested_type & KVM_DEV_IRQ_GUEST_MSIX) ||
1079 (ctrl_word & PCI_MSIX_FLAGS_ENABLE)) {
1081 assigned_irq_data.flags = assigned_dev->irq_requested_type;
1082 free_dev_irq_entries(assigned_dev);
1083 r = kvm_deassign_irq(kvm_state, &assigned_irq_data);
1084 /* -ENXIO means no assigned irq */
1085 if (r && r != -ENXIO)
1086 perror("assigned_dev_update_msix: deassign irq");
1088 assigned_dev->irq_requested_type = 0;
1091 if (ctrl_word & PCI_MSIX_FLAGS_ENABLE) {
1092 assigned_irq_data.flags = KVM_DEV_IRQ_HOST_MSIX |
1093 KVM_DEV_IRQ_GUEST_MSIX;
1095 if (assigned_dev_update_msix_mmio(pci_dev) < 0) {
1096 perror("assigned_dev_update_msix_mmio");
1097 return;
1099 if (kvm_assign_irq(kvm_state, &assigned_irq_data) < 0) {
1100 perror("assigned_dev_enable_msix: assign irq");
1101 return;
1103 assigned_dev->girq = -1;
1104 assigned_dev->irq_requested_type = assigned_irq_data.flags;
1105 } else {
1106 assign_irq(assigned_dev);
1110 static uint32_t assigned_dev_pci_read_config(PCIDevice *pci_dev,
1111 uint32_t address, int len)
1113 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1114 uint32_t virt_val = pci_default_read_config(pci_dev, address, len);
1115 uint32_t real_val, emulate_mask, full_emulation_mask;
1117 emulate_mask = 0;
1118 memcpy(&emulate_mask, assigned_dev->emulate_config_read + address, len);
1119 emulate_mask = le32_to_cpu(emulate_mask);
1121 full_emulation_mask = 0xffffffff >> (32 - len * 8);
1123 if (emulate_mask != full_emulation_mask) {
1124 real_val = assigned_dev_pci_read(pci_dev, address, len);
1125 return (virt_val & emulate_mask) | (real_val & ~emulate_mask);
1126 } else {
1127 return virt_val;
1131 static void assigned_dev_pci_write_config(PCIDevice *pci_dev, uint32_t address,
1132 uint32_t val, int len)
1134 AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1135 uint32_t emulate_mask, full_emulation_mask;
1137 pci_default_write_config(pci_dev, address, val, len);
1139 if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
1140 if (range_covers_byte(address, len,
1141 pci_dev->msi_cap + PCI_MSI_FLAGS)) {
1142 assigned_dev_update_msi(pci_dev);
1145 if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1146 if (range_covers_byte(address, len,
1147 pci_dev->msix_cap + PCI_MSIX_FLAGS + 1)) {
1148 assigned_dev_update_msix(pci_dev);
1152 emulate_mask = 0;
1153 memcpy(&emulate_mask, assigned_dev->emulate_config_write + address, len);
1154 emulate_mask = le32_to_cpu(emulate_mask);
1156 full_emulation_mask = 0xffffffff >> (32 - len * 8);
1158 if (emulate_mask != full_emulation_mask) {
1159 if (emulate_mask) {
1160 val &= ~emulate_mask;
1161 val |= assigned_dev_pci_read(pci_dev, address, len) & emulate_mask;
1163 assigned_dev_pci_write(pci_dev, address, val, len);
1167 static void assigned_dev_setup_cap_read(AssignedDevice *dev, uint32_t offset,
1168 uint32_t len)
1170 assigned_dev_direct_config_read(dev, offset, len);
1171 assigned_dev_emulate_config_read(dev, offset + PCI_CAP_LIST_NEXT, 1);
1174 static int assigned_device_pci_cap_init(PCIDevice *pci_dev)
1176 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1177 PCIRegion *pci_region = dev->real_device.regions;
1178 int ret, pos;
1180 /* Clear initial capabilities pointer and status copied from hw */
1181 pci_set_byte(pci_dev->config + PCI_CAPABILITY_LIST, 0);
1182 pci_set_word(pci_dev->config + PCI_STATUS,
1183 pci_get_word(pci_dev->config + PCI_STATUS) &
1184 ~PCI_STATUS_CAP_LIST);
1186 /* Expose MSI capability
1187 * MSI capability is the 1st capability in capability config */
1188 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSI, 0);
1189 if (pos != 0 && kvm_check_extension(kvm_state, KVM_CAP_ASSIGN_DEV_IRQ)) {
1190 dev->cap.available |= ASSIGNED_DEVICE_CAP_MSI;
1191 /* Only 32-bit/no-mask currently supported */
1192 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSI, pos, 10)) < 0) {
1193 return ret;
1195 pci_dev->msi_cap = pos;
1197 pci_set_word(pci_dev->config + pos + PCI_MSI_FLAGS,
1198 pci_get_word(pci_dev->config + pos + PCI_MSI_FLAGS) &
1199 PCI_MSI_FLAGS_QMASK);
1200 pci_set_long(pci_dev->config + pos + PCI_MSI_ADDRESS_LO, 0);
1201 pci_set_word(pci_dev->config + pos + PCI_MSI_DATA_32, 0);
1203 /* Set writable fields */
1204 pci_set_word(pci_dev->wmask + pos + PCI_MSI_FLAGS,
1205 PCI_MSI_FLAGS_QSIZE | PCI_MSI_FLAGS_ENABLE);
1206 pci_set_long(pci_dev->wmask + pos + PCI_MSI_ADDRESS_LO, 0xfffffffc);
1207 pci_set_word(pci_dev->wmask + pos + PCI_MSI_DATA_32, 0xffff);
1209 /* Expose MSI-X capability */
1210 pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSIX, 0);
1211 /* Would really like to test kvm_check_extension(, KVM_CAP_DEVICE_MSIX),
1212 * but the kernel doesn't expose it. Instead do a dummy call to
1213 * KVM_ASSIGN_SET_MSIX_NR to see if it exists. */
1214 if (pos != 0 && kvm_assign_set_msix_nr(kvm_state, NULL) == -EFAULT) {
1215 int bar_nr;
1216 uint32_t msix_table_entry;
1218 dev->cap.available |= ASSIGNED_DEVICE_CAP_MSIX;
1219 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSIX, pos, 12)) < 0) {
1220 return ret;
1222 pci_dev->msix_cap = pos;
1224 pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS,
1225 pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) &
1226 PCI_MSIX_FLAGS_QSIZE);
1228 /* Only enable and function mask bits are writable */
1229 pci_set_word(pci_dev->wmask + pos + PCI_MSIX_FLAGS,
1230 PCI_MSIX_FLAGS_ENABLE | PCI_MSIX_FLAGS_MASKALL);
1232 msix_table_entry = pci_get_long(pci_dev->config + pos + PCI_MSIX_TABLE);
1233 bar_nr = msix_table_entry & PCI_MSIX_FLAGS_BIRMASK;
1234 msix_table_entry &= ~PCI_MSIX_FLAGS_BIRMASK;
1235 dev->msix_table_addr = pci_region[bar_nr].base_addr + msix_table_entry;
1238 /* Minimal PM support, nothing writable, device appears to NAK changes */
1239 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PM, 0))) {
1240 uint16_t pmc;
1241 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, pos,
1242 PCI_PM_SIZEOF)) < 0) {
1243 return ret;
1246 assigned_dev_setup_cap_read(dev, pos, PCI_PM_SIZEOF);
1248 pmc = pci_get_word(pci_dev->config + pos + PCI_CAP_FLAGS);
1249 pmc &= (PCI_PM_CAP_VER_MASK | PCI_PM_CAP_DSI);
1250 pci_set_word(pci_dev->config + pos + PCI_CAP_FLAGS, pmc);
1252 /* assign_device will bring the device up to D0, so we don't need
1253 * to worry about doing that ourselves here. */
1254 pci_set_word(pci_dev->config + pos + PCI_PM_CTRL,
1255 PCI_PM_CTRL_NO_SOFT_RESET);
1257 pci_set_byte(pci_dev->config + pos + PCI_PM_PPB_EXTENSIONS, 0);
1258 pci_set_byte(pci_dev->config + pos + PCI_PM_DATA_REGISTER, 0);
1261 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_EXP, 0))) {
1262 uint8_t version, size;
1263 uint16_t type, devctl, lnkcap, lnksta;
1264 uint32_t devcap;
1266 version = pci_get_byte(pci_dev->config + pos + PCI_EXP_FLAGS);
1267 version &= PCI_EXP_FLAGS_VERS;
1268 if (version == 1) {
1269 size = 0x14;
1270 } else if (version == 2) {
1272 * Check for non-std size, accept reduced size to 0x34,
1273 * which is what bcm5761 implemented, violating the
1274 * PCIe v3.0 spec that regs should exist and be read as 0,
1275 * not optionally provided and shorten the struct size.
1277 size = MIN(0x3c, PCI_CONFIG_SPACE_SIZE - pos);
1278 if (size < 0x34) {
1279 fprintf(stderr,
1280 "%s: Invalid size PCIe cap-id 0x%x \n",
1281 __func__, PCI_CAP_ID_EXP);
1282 return -EINVAL;
1283 } else if (size != 0x3c) {
1284 fprintf(stderr,
1285 "WARNING, %s: PCIe cap-id 0x%x has "
1286 "non-standard size 0x%x; std size should be 0x3c \n",
1287 __func__, PCI_CAP_ID_EXP, size);
1289 } else {
1290 fprintf(stderr,
1291 "%s: Unsupported PCI express capability version %d\n",
1292 __func__, version);
1293 return -EINVAL;
1296 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_EXP,
1297 pos, size)) < 0) {
1298 return ret;
1301 assigned_dev_setup_cap_read(dev, pos, size);
1303 type = pci_get_word(pci_dev->config + pos + PCI_EXP_FLAGS);
1304 type = (type & PCI_EXP_FLAGS_TYPE) >> 8;
1305 if (type != PCI_EXP_TYPE_ENDPOINT &&
1306 type != PCI_EXP_TYPE_LEG_END && type != PCI_EXP_TYPE_RC_END) {
1307 fprintf(stderr,
1308 "Device assignment only supports endpoint assignment, "
1309 "device type %d\n", type);
1310 return -EINVAL;
1313 /* capabilities, pass existing read-only copy
1314 * PCI_EXP_FLAGS_IRQ: updated by hardware, should be direct read */
1316 /* device capabilities: hide FLR */
1317 devcap = pci_get_long(pci_dev->config + pos + PCI_EXP_DEVCAP);
1318 devcap &= ~PCI_EXP_DEVCAP_FLR;
1319 pci_set_long(pci_dev->config + pos + PCI_EXP_DEVCAP, devcap);
1321 /* device control: clear all error reporting enable bits, leaving
1322 * leaving only a few host values. Note, these are
1323 * all writable, but not passed to hw.
1325 devctl = pci_get_word(pci_dev->config + pos + PCI_EXP_DEVCTL);
1326 devctl = (devctl & (PCI_EXP_DEVCTL_READRQ | PCI_EXP_DEVCTL_PAYLOAD)) |
1327 PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN;
1328 pci_set_word(pci_dev->config + pos + PCI_EXP_DEVCTL, devctl);
1329 devctl = PCI_EXP_DEVCTL_BCR_FLR | PCI_EXP_DEVCTL_AUX_PME;
1330 pci_set_word(pci_dev->wmask + pos + PCI_EXP_DEVCTL, ~devctl);
1332 /* Clear device status */
1333 pci_set_word(pci_dev->config + pos + PCI_EXP_DEVSTA, 0);
1335 /* Link capabilities, expose links and latencues, clear reporting */
1336 lnkcap = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKCAP);
1337 lnkcap &= (PCI_EXP_LNKCAP_SLS | PCI_EXP_LNKCAP_MLW |
1338 PCI_EXP_LNKCAP_ASPMS | PCI_EXP_LNKCAP_L0SEL |
1339 PCI_EXP_LNKCAP_L1EL);
1340 pci_set_word(pci_dev->config + pos + PCI_EXP_LNKCAP, lnkcap);
1341 pci_set_word(pci_dev->wmask + pos + PCI_EXP_LNKCAP,
1342 PCI_EXP_LNKCTL_ASPMC | PCI_EXP_LNKCTL_RCB |
1343 PCI_EXP_LNKCTL_CCC | PCI_EXP_LNKCTL_ES |
1344 PCI_EXP_LNKCTL_CLKREQ_EN | PCI_EXP_LNKCTL_HAWD);
1346 /* Link control, pass existing read-only copy. Should be writable? */
1348 /* Link status, only expose current speed and width */
1349 lnksta = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKSTA);
1350 lnksta &= (PCI_EXP_LNKSTA_CLS | PCI_EXP_LNKSTA_NLW);
1351 pci_set_word(pci_dev->config + pos + PCI_EXP_LNKSTA, lnksta);
1353 if (version >= 2) {
1354 /* Slot capabilities, control, status - not needed for endpoints */
1355 pci_set_long(pci_dev->config + pos + PCI_EXP_SLTCAP, 0);
1356 pci_set_word(pci_dev->config + pos + PCI_EXP_SLTCTL, 0);
1357 pci_set_word(pci_dev->config + pos + PCI_EXP_SLTSTA, 0);
1359 /* Root control, capabilities, status - not needed for endpoints */
1360 pci_set_word(pci_dev->config + pos + PCI_EXP_RTCTL, 0);
1361 pci_set_word(pci_dev->config + pos + PCI_EXP_RTCAP, 0);
1362 pci_set_long(pci_dev->config + pos + PCI_EXP_RTSTA, 0);
1364 /* Device capabilities/control 2, pass existing read-only copy */
1365 /* Link control 2, pass existing read-only copy */
1369 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PCIX, 0))) {
1370 uint16_t cmd;
1371 uint32_t status;
1373 /* Only expose the minimum, 8 byte capability */
1374 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_PCIX, pos, 8)) < 0) {
1375 return ret;
1378 assigned_dev_setup_cap_read(dev, pos, 8);
1380 /* Command register, clear upper bits, including extended modes */
1381 cmd = pci_get_word(pci_dev->config + pos + PCI_X_CMD);
1382 cmd &= (PCI_X_CMD_DPERR_E | PCI_X_CMD_ERO | PCI_X_CMD_MAX_READ |
1383 PCI_X_CMD_MAX_SPLIT);
1384 pci_set_word(pci_dev->config + pos + PCI_X_CMD, cmd);
1386 /* Status register, update with emulated PCI bus location, clear
1387 * error bits, leave the rest. */
1388 status = pci_get_long(pci_dev->config + pos + PCI_X_STATUS);
1389 status &= ~(PCI_X_STATUS_BUS | PCI_X_STATUS_DEVFN);
1390 status |= (pci_bus_num(pci_dev->bus) << 8) | pci_dev->devfn;
1391 status &= ~(PCI_X_STATUS_SPL_DISC | PCI_X_STATUS_UNX_SPL |
1392 PCI_X_STATUS_SPL_ERR);
1393 pci_set_long(pci_dev->config + pos + PCI_X_STATUS, status);
1396 if ((pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VPD, 0))) {
1397 /* Direct R/W passthrough */
1398 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_VPD, pos, 8)) < 0) {
1399 return ret;
1402 assigned_dev_setup_cap_read(dev, pos, 8);
1404 /* direct write for cap content */
1405 assigned_dev_direct_config_write(dev, pos + 2, 6);
1408 /* Devices can have multiple vendor capabilities, get them all */
1409 for (pos = 0; (pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VNDR, pos));
1410 pos += PCI_CAP_LIST_NEXT) {
1411 uint8_t len = pci_get_byte(pci_dev->config + pos + PCI_CAP_FLAGS);
1412 /* Direct R/W passthrough */
1413 if ((ret = pci_add_capability(pci_dev, PCI_CAP_ID_VNDR,
1414 pos, len)) < 0) {
1415 return ret;
1418 assigned_dev_setup_cap_read(dev, pos, len);
1420 /* direct write for cap content */
1421 assigned_dev_direct_config_write(dev, pos + 2, len - 2);
1424 /* If real and virtual capability list status bits differ, virtualize the
1425 * access. */
1426 if ((pci_get_word(pci_dev->config + PCI_STATUS) & PCI_STATUS_CAP_LIST) !=
1427 (assigned_dev_pci_read_byte(pci_dev, PCI_STATUS) &
1428 PCI_STATUS_CAP_LIST)) {
1429 dev->emulate_config_read[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1432 return 0;
1435 static uint32_t msix_mmio_readl(void *opaque, target_phys_addr_t addr)
1437 AssignedDevice *adev = opaque;
1438 unsigned int offset = addr & 0xfff;
1439 void *page = adev->msix_table_page;
1440 uint32_t val = 0;
1442 memcpy(&val, (void *)((char *)page + offset), 4);
1444 return val;
1447 static uint32_t msix_mmio_readb(void *opaque, target_phys_addr_t addr)
1449 return ((msix_mmio_readl(opaque, addr & ~3)) >>
1450 (8 * (addr & 3))) & 0xff;
1453 static uint32_t msix_mmio_readw(void *opaque, target_phys_addr_t addr)
1455 return ((msix_mmio_readl(opaque, addr & ~3)) >>
1456 (8 * (addr & 3))) & 0xffff;
1459 static void msix_mmio_writel(void *opaque,
1460 target_phys_addr_t addr, uint32_t val)
1462 AssignedDevice *adev = opaque;
1463 unsigned int offset = addr & 0xfff;
1464 void *page = adev->msix_table_page;
1466 DEBUG("write to MSI-X entry table mmio offset 0x%lx, val 0x%x\n",
1467 addr, val);
1468 memcpy((void *)((char *)page + offset), &val, 4);
1471 static void msix_mmio_writew(void *opaque,
1472 target_phys_addr_t addr, uint32_t val)
1474 msix_mmio_writel(opaque, addr & ~3,
1475 (val & 0xffff) << (8*(addr & 3)));
1478 static void msix_mmio_writeb(void *opaque,
1479 target_phys_addr_t addr, uint32_t val)
1481 msix_mmio_writel(opaque, addr & ~3,
1482 (val & 0xff) << (8*(addr & 3)));
1485 static const MemoryRegionOps msix_mmio_ops = {
1486 .old_mmio = {
1487 .read = { msix_mmio_readb, msix_mmio_readw, msix_mmio_readl, },
1488 .write = { msix_mmio_writeb, msix_mmio_writew, msix_mmio_writel, },
1490 .endianness = DEVICE_NATIVE_ENDIAN,
1493 static int assigned_dev_register_msix_mmio(AssignedDevice *dev)
1495 dev->msix_table_page = mmap(NULL, 0x1000,
1496 PROT_READ|PROT_WRITE,
1497 MAP_ANONYMOUS|MAP_PRIVATE, 0, 0);
1498 if (dev->msix_table_page == MAP_FAILED) {
1499 fprintf(stderr, "fail allocate msix_table_page! %s\n",
1500 strerror(errno));
1501 return -EFAULT;
1503 memset(dev->msix_table_page, 0, 0x1000);
1504 memory_region_init_io(&dev->mmio, &msix_mmio_ops, dev,
1505 "assigned-dev-msix", MSIX_PAGE_SIZE);
1506 return 0;
1509 static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev)
1511 if (!dev->msix_table_page)
1512 return;
1514 memory_region_destroy(&dev->mmio);
1516 if (munmap(dev->msix_table_page, 0x1000) == -1) {
1517 fprintf(stderr, "error unmapping msix_table_page! %s\n",
1518 strerror(errno));
1520 dev->msix_table_page = NULL;
1523 static const VMStateDescription vmstate_assigned_device = {
1524 .name = "pci-assign",
1525 .unmigratable = 1,
1528 static void reset_assigned_device(DeviceState *dev)
1530 PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
1531 AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1532 char reset_file[64];
1533 const char reset[] = "1";
1534 int fd, ret;
1536 snprintf(reset_file, sizeof(reset_file),
1537 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/reset",
1538 adev->host.seg, adev->host.bus, adev->host.dev, adev->host.func);
1541 * Issue a device reset via pci-sysfs. Note that we use write(2) here
1542 * and ignore the return value because some kernels have a bug that
1543 * returns 0 rather than bytes written on success, sending us into an
1544 * infinite retry loop using other write mechanisms.
1546 fd = open(reset_file, O_WRONLY);
1547 if (fd != -1) {
1548 ret = write(fd, reset, strlen(reset));
1549 (void)ret;
1550 close(fd);
1554 * When a 0 is written to the command register, the device is logically
1555 * disconnected from the PCI bus. This avoids further DMA transfers.
1557 assigned_dev_pci_write_config(pci_dev, PCI_COMMAND, 0, 2);
1560 static int assigned_initfn(struct PCIDevice *pci_dev)
1562 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1563 uint8_t e_intx;
1564 int r;
1566 if (!kvm_enabled()) {
1567 error_report("pci-assign: error: requires KVM support");
1568 return -1;
1571 if (!dev->host.seg && !dev->host.bus && !dev->host.dev && !dev->host.func) {
1572 error_report("pci-assign: error: no host device specified");
1573 return -1;
1577 * Set up basic config space access control. Will be further refined during
1578 * device initialization.
1580 assigned_dev_emulate_config_read(dev, 0, PCI_CONFIG_SPACE_SIZE);
1581 assigned_dev_direct_config_read(dev, PCI_COMMAND, 2);
1582 assigned_dev_direct_config_read(dev, PCI_STATUS, 2);
1583 assigned_dev_direct_config_read(dev, PCI_REVISION_ID, 1);
1584 assigned_dev_direct_config_read(dev, PCI_CLASS_PROG, 3);
1585 assigned_dev_direct_config_read(dev, PCI_CACHE_LINE_SIZE, 1);
1586 assigned_dev_direct_config_read(dev, PCI_LATENCY_TIMER, 1);
1587 assigned_dev_direct_config_read(dev, PCI_HEADER_TYPE, 1);
1588 assigned_dev_direct_config_read(dev, PCI_BIST, 1);
1589 assigned_dev_direct_config_read(dev, PCI_CARDBUS_CIS, 4);
1590 assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_VENDOR_ID, 2);
1591 assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_ID, 2);
1592 assigned_dev_direct_config_read(dev, PCI_CAPABILITY_LIST + 1, 7);
1593 assigned_dev_direct_config_read(dev, PCI_MIN_GNT, 1);
1594 assigned_dev_direct_config_read(dev, PCI_MAX_LAT, 1);
1595 memcpy(dev->emulate_config_write, dev->emulate_config_read,
1596 sizeof(dev->emulate_config_read));
1598 if (get_real_device(dev, dev->host.seg, dev->host.bus,
1599 dev->host.dev, dev->host.func)) {
1600 error_report("pci-assign: Error: Couldn't get real device (%s)!",
1601 dev->dev.qdev.id);
1602 goto out;
1605 if (assigned_device_pci_cap_init(pci_dev) < 0) {
1606 goto out;
1609 /* intercept MSI-X entry page in the MMIO */
1610 if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1611 if (assigned_dev_register_msix_mmio(dev)) {
1612 goto out;
1616 /* handle real device's MMIO/PIO BARs */
1617 if (assigned_dev_register_regions(dev->real_device.regions,
1618 dev->real_device.region_number,
1619 dev))
1620 goto out;
1622 /* handle interrupt routing */
1623 e_intx = dev->dev.config[0x3d] - 1;
1624 dev->intpin = e_intx;
1625 dev->run = 0;
1626 dev->girq = -1;
1627 dev->h_segnr = dev->host.seg;
1628 dev->h_busnr = dev->host.bus;
1629 dev->h_devfn = PCI_DEVFN(dev->host.dev, dev->host.func);
1631 /* assign device to guest */
1632 r = assign_device(dev);
1633 if (r < 0)
1634 goto out;
1636 /* assign irq for the device */
1637 r = assign_irq(dev);
1638 if (r < 0)
1639 goto assigned_out;
1641 assigned_dev_load_option_rom(dev);
1642 QLIST_INSERT_HEAD(&devs, dev, next);
1644 add_boot_device_path(dev->bootindex, &pci_dev->qdev, NULL);
1646 return 0;
1648 assigned_out:
1649 deassign_device(dev);
1650 out:
1651 free_assigned_device(dev);
1652 return -1;
1655 static int assigned_exitfn(struct PCIDevice *pci_dev)
1657 AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1659 QLIST_REMOVE(dev, next);
1660 deassign_device(dev);
1661 free_assigned_device(dev);
1662 return 0;
1665 static int parse_hostaddr(DeviceState *dev, Property *prop, const char *str)
1667 PCIHostDevice *ptr = qdev_get_prop_ptr(dev, prop);
1668 int rc;
1670 rc = pci_parse_host_devaddr(str, &ptr->seg, &ptr->bus, &ptr->dev, &ptr->func);
1671 if (rc != 0)
1672 return -1;
1673 return 0;
1676 static int print_hostaddr(DeviceState *dev, Property *prop, char *dest, size_t len)
1678 PCIHostDevice *ptr = qdev_get_prop_ptr(dev, prop);
1680 return snprintf(dest, len, "%02x:%02x.%x", ptr->bus, ptr->dev, ptr->func);
1683 PropertyInfo qdev_prop_hostaddr = {
1684 .name = "pci-hostaddr",
1685 .type = -1,
1686 .size = sizeof(PCIHostDevice),
1687 .parse = parse_hostaddr,
1688 .print = print_hostaddr,
1691 static PCIDeviceInfo assign_info = {
1692 .qdev.name = "pci-assign",
1693 .qdev.desc = "pass through host pci devices to the guest",
1694 .qdev.size = sizeof(AssignedDevice),
1695 .qdev.vmsd = &vmstate_assigned_device,
1696 .qdev.reset = reset_assigned_device,
1697 .init = assigned_initfn,
1698 .exit = assigned_exitfn,
1699 .config_read = assigned_dev_pci_read_config,
1700 .config_write = assigned_dev_pci_write_config,
1701 .qdev.props = (Property[]) {
1702 DEFINE_PROP("host", AssignedDevice, host, qdev_prop_hostaddr, PCIHostDevice),
1703 DEFINE_PROP_BIT("iommu", AssignedDevice, features,
1704 ASSIGNED_DEVICE_USE_IOMMU_BIT, true),
1705 DEFINE_PROP_BIT("prefer_msi", AssignedDevice, features,
1706 ASSIGNED_DEVICE_PREFER_MSI_BIT, true),
1707 DEFINE_PROP_INT32("bootindex", AssignedDevice, bootindex, -1),
1708 DEFINE_PROP_STRING("configfd", AssignedDevice, configfd_name),
1709 DEFINE_PROP_END_OF_LIST(),
1713 static void assign_register_devices(void)
1715 pci_qdev_register(&assign_info);
1718 device_init(assign_register_devices)
1721 * Scan the assigned devices for the devices that have an option ROM, and then
1722 * load the corresponding ROM data to RAM. If an error occurs while loading an
1723 * option ROM, we just ignore that option ROM and continue with the next one.
1725 static void assigned_dev_load_option_rom(AssignedDevice *dev)
1727 char name[32], rom_file[64];
1728 FILE *fp;
1729 uint8_t val;
1730 struct stat st;
1731 void *ptr;
1733 /* If loading ROM from file, pci handles it */
1734 if (dev->dev.romfile || !dev->dev.rom_bar)
1735 return;
1737 snprintf(rom_file, sizeof(rom_file),
1738 "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/rom",
1739 dev->host.seg, dev->host.bus, dev->host.dev, dev->host.func);
1741 if (stat(rom_file, &st)) {
1742 return;
1745 if (access(rom_file, F_OK)) {
1746 fprintf(stderr, "pci-assign: Insufficient privileges for %s\n",
1747 rom_file);
1748 return;
1751 /* Write "1" to the ROM file to enable it */
1752 fp = fopen(rom_file, "r+");
1753 if (fp == NULL) {
1754 return;
1756 val = 1;
1757 if (fwrite(&val, 1, 1, fp) != 1) {
1758 goto close_rom;
1760 fseek(fp, 0, SEEK_SET);
1762 snprintf(name, sizeof(name), "%s.rom", dev->dev.qdev.info->name);
1763 memory_region_init_ram(&dev->dev.rom, &dev->dev.qdev, name, st.st_size);
1764 ptr = memory_region_get_ram_ptr(&dev->dev.rom);
1765 memset(ptr, 0xff, st.st_size);
1767 if (!fread(ptr, 1, st.st_size, fp)) {
1768 fprintf(stderr, "pci-assign: Cannot read from host %s\n"
1769 "\tDevice option ROM contents are probably invalid "
1770 "(check dmesg).\n\tSkip option ROM probe with rombar=0, "
1771 "or load from file with romfile=\n", rom_file);
1772 memory_region_destroy(&dev->dev.rom);
1773 goto close_rom;
1776 pci_register_bar(&dev->dev, PCI_ROM_SLOT, 0, &dev->dev.rom);
1777 dev->dev.has_rom = true;
1778 close_rom:
1779 /* Write "0" to disable ROM */
1780 fseek(fp, 0, SEEK_SET);
1781 val = 0;
1782 if (!fwrite(&val, 1, 1, fp)) {
1783 DEBUG("%s\n", "Failed to disable pci-sysfs rom file");
1785 fclose(fp);