]> Git Repo - qemu.git/blob - hw/i386/kvm/pci-assign.c
Merge branch 'realize-isa.v2' of git://github.com/afaerber/qemu-cpu
[qemu.git] / hw / i386 / kvm / pci-assign.c
1 /*
2  * Copyright (c) 2007, Neocleus Corporation.
3  *
4  * This work is licensed under the terms of the GNU GPL, version 2.  See
5  * the COPYING file in the top-level directory.
6  *
7  *
8  *  Assign a PCI device from the host to a guest VM.
9  *
10  *  This implementation uses the classic device assignment interface of KVM
11  *  and is only available on x86 hosts. It is expected to be obsoleted by VFIO
12  *  based device assignment.
13  *
14  *  Adapted for KVM (qemu-kvm) by Qumranet. QEMU version was based on qemu-kvm
15  *  revision 4144fe9d48. See its repository for the history.
16  *
17  *  Copyright (c) 2007, Neocleus, Alex Novik ([email protected])
18  *  Copyright (c) 2007, Neocleus, Guy Zana ([email protected])
19  *  Copyright (C) 2008, Qumranet, Amit Shah ([email protected])
20  *  Copyright (C) 2008, Red Hat, Amit Shah ([email protected])
21  *  Copyright (C) 2008, IBM, Muli Ben-Yehuda ([email protected])
22  */
23 #include <stdio.h>
24 #include <unistd.h>
25 #include <sys/io.h>
26 #include <sys/mman.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include "hw/hw.h"
30 #include "hw/i386/pc.h"
31 #include "qemu/error-report.h"
32 #include "ui/console.h"
33 #include "hw/loader.h"
34 #include "monitor/monitor.h"
35 #include "qemu/range.h"
36 #include "sysemu/sysemu.h"
37 #include "hw/pci/pci.h"
38 #include "hw/pci/msi.h"
39 #include "kvm_i386.h"
40
41 #define MSIX_PAGE_SIZE 0x1000
42
43 /* From linux/ioport.h */
44 #define IORESOURCE_IO       0x00000100  /* Resource type */
45 #define IORESOURCE_MEM      0x00000200
46 #define IORESOURCE_IRQ      0x00000400
47 #define IORESOURCE_DMA      0x00000800
48 #define IORESOURCE_PREFETCH 0x00002000  /* No side effects */
49 #define IORESOURCE_MEM_64   0x00100000
50
51 //#define DEVICE_ASSIGNMENT_DEBUG
52
53 #ifdef DEVICE_ASSIGNMENT_DEBUG
54 #define DEBUG(fmt, ...)                                       \
55     do {                                                      \
56         fprintf(stderr, "%s: " fmt, __func__ , __VA_ARGS__);  \
57     } while (0)
58 #else
59 #define DEBUG(fmt, ...)
60 #endif
61
62 typedef struct PCIRegion {
63     int type;           /* Memory or port I/O */
64     int valid;
65     uint64_t base_addr;
66     uint64_t size;    /* size of the region */
67     int resource_fd;
68 } PCIRegion;
69
70 typedef struct PCIDevRegions {
71     uint8_t bus, dev, func; /* Bus inside domain, device and function */
72     int irq;                /* IRQ number */
73     uint16_t region_number; /* number of active regions */
74
75     /* Port I/O or MMIO Regions */
76     PCIRegion regions[PCI_NUM_REGIONS - 1];
77     int config_fd;
78 } PCIDevRegions;
79
80 typedef struct AssignedDevRegion {
81     MemoryRegion container;
82     MemoryRegion real_iomem;
83     union {
84         uint8_t *r_virtbase; /* mmapped access address for memory regions */
85         uint32_t r_baseport; /* the base guest port for I/O regions */
86     } u;
87     pcibus_t e_size;    /* emulated size of region in bytes */
88     pcibus_t r_size;    /* real size of region in bytes */
89     PCIRegion *region;
90 } AssignedDevRegion;
91
92 #define ASSIGNED_DEVICE_PREFER_MSI_BIT  0
93 #define ASSIGNED_DEVICE_SHARE_INTX_BIT  1
94
95 #define ASSIGNED_DEVICE_PREFER_MSI_MASK (1 << ASSIGNED_DEVICE_PREFER_MSI_BIT)
96 #define ASSIGNED_DEVICE_SHARE_INTX_MASK (1 << ASSIGNED_DEVICE_SHARE_INTX_BIT)
97
98 typedef struct MSIXTableEntry {
99     uint32_t addr_lo;
100     uint32_t addr_hi;
101     uint32_t data;
102     uint32_t ctrl;
103 } MSIXTableEntry;
104
105 typedef enum AssignedIRQType {
106     ASSIGNED_IRQ_NONE = 0,
107     ASSIGNED_IRQ_INTX_HOST_INTX,
108     ASSIGNED_IRQ_INTX_HOST_MSI,
109     ASSIGNED_IRQ_MSI,
110     ASSIGNED_IRQ_MSIX
111 } AssignedIRQType;
112
113 typedef struct AssignedDevice {
114     PCIDevice dev;
115     PCIHostDeviceAddress host;
116     uint32_t dev_id;
117     uint32_t features;
118     int intpin;
119     AssignedDevRegion v_addrs[PCI_NUM_REGIONS - 1];
120     PCIDevRegions real_device;
121     PCIINTxRoute intx_route;
122     AssignedIRQType assigned_irq_type;
123     struct {
124 #define ASSIGNED_DEVICE_CAP_MSI (1 << 0)
125 #define ASSIGNED_DEVICE_CAP_MSIX (1 << 1)
126         uint32_t available;
127 #define ASSIGNED_DEVICE_MSI_ENABLED (1 << 0)
128 #define ASSIGNED_DEVICE_MSIX_ENABLED (1 << 1)
129 #define ASSIGNED_DEVICE_MSIX_MASKED (1 << 2)
130         uint32_t state;
131     } cap;
132     uint8_t emulate_config_read[PCI_CONFIG_SPACE_SIZE];
133     uint8_t emulate_config_write[PCI_CONFIG_SPACE_SIZE];
134     int msi_virq_nr;
135     int *msi_virq;
136     MSIXTableEntry *msix_table;
137     hwaddr msix_table_addr;
138     uint16_t msix_max;
139     MemoryRegion mmio;
140     char *configfd_name;
141     int32_t bootindex;
142 } AssignedDevice;
143
144 static void assigned_dev_update_irq_routing(PCIDevice *dev);
145
146 static void assigned_dev_load_option_rom(AssignedDevice *dev);
147
148 static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev);
149
150 static uint64_t assigned_dev_ioport_rw(AssignedDevRegion *dev_region,
151                                        hwaddr addr, int size,
152                                        uint64_t *data)
153 {
154     uint64_t val = 0;
155     int fd = dev_region->region->resource_fd;
156
157     if (fd >= 0) {
158         if (data) {
159             DEBUG("pwrite data=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx
160                   ", addr="TARGET_FMT_plx"\n", *data, size, addr, addr);
161             if (pwrite(fd, data, size, addr) != size) {
162                 error_report("%s - pwrite failed %s",
163                              __func__, strerror(errno));
164             }
165         } else {
166             if (pread(fd, &val, size, addr) != size) {
167                 error_report("%s - pread failed %s",
168                              __func__, strerror(errno));
169                 val = (1UL << (size * 8)) - 1;
170             }
171             DEBUG("pread val=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx
172                   ", addr=" TARGET_FMT_plx "\n", val, size, addr, addr);
173         }
174     } else {
175         uint32_t port = addr + dev_region->u.r_baseport;
176
177         if (data) {
178             DEBUG("out data=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx
179                   ", host=%x\n", *data, size, addr, port);
180             switch (size) {
181             case 1:
182                 outb(*data, port);
183                 break;
184             case 2:
185                 outw(*data, port);
186                 break;
187             case 4:
188                 outl(*data, port);
189                 break;
190             }
191         } else {
192             switch (size) {
193             case 1:
194                 val = inb(port);
195                 break;
196             case 2:
197                 val = inw(port);
198                 break;
199             case 4:
200                 val = inl(port);
201                 break;
202             }
203             DEBUG("in data=%" PRIx64 ", size=%d, e_phys=" TARGET_FMT_plx
204                   ", host=%x\n", val, size, addr, port);
205         }
206     }
207     return val;
208 }
209
210 static void assigned_dev_ioport_write(void *opaque, hwaddr addr,
211                                       uint64_t data, unsigned size)
212 {
213     assigned_dev_ioport_rw(opaque, addr, size, &data);
214 }
215
216 static uint64_t assigned_dev_ioport_read(void *opaque,
217                                          hwaddr addr, unsigned size)
218 {
219     return assigned_dev_ioport_rw(opaque, addr, size, NULL);
220 }
221
222 static uint32_t slow_bar_readb(void *opaque, hwaddr addr)
223 {
224     AssignedDevRegion *d = opaque;
225     uint8_t *in = d->u.r_virtbase + addr;
226     uint32_t r;
227
228     r = *in;
229     DEBUG("slow_bar_readl addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
230
231     return r;
232 }
233
234 static uint32_t slow_bar_readw(void *opaque, hwaddr addr)
235 {
236     AssignedDevRegion *d = opaque;
237     uint16_t *in = (uint16_t *)(d->u.r_virtbase + addr);
238     uint32_t r;
239
240     r = *in;
241     DEBUG("slow_bar_readl addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
242
243     return r;
244 }
245
246 static uint32_t slow_bar_readl(void *opaque, hwaddr addr)
247 {
248     AssignedDevRegion *d = opaque;
249     uint32_t *in = (uint32_t *)(d->u.r_virtbase + addr);
250     uint32_t r;
251
252     r = *in;
253     DEBUG("slow_bar_readl addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);
254
255     return r;
256 }
257
258 static void slow_bar_writeb(void *opaque, hwaddr addr, uint32_t val)
259 {
260     AssignedDevRegion *d = opaque;
261     uint8_t *out = d->u.r_virtbase + addr;
262
263     DEBUG("slow_bar_writeb addr=0x" TARGET_FMT_plx " val=0x%02x\n", addr, val);
264     *out = val;
265 }
266
267 static void slow_bar_writew(void *opaque, hwaddr addr, uint32_t val)
268 {
269     AssignedDevRegion *d = opaque;
270     uint16_t *out = (uint16_t *)(d->u.r_virtbase + addr);
271
272     DEBUG("slow_bar_writew addr=0x" TARGET_FMT_plx " val=0x%04x\n", addr, val);
273     *out = val;
274 }
275
276 static void slow_bar_writel(void *opaque, hwaddr addr, uint32_t val)
277 {
278     AssignedDevRegion *d = opaque;
279     uint32_t *out = (uint32_t *)(d->u.r_virtbase + addr);
280
281     DEBUG("slow_bar_writel addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, val);
282     *out = val;
283 }
284
285 static const MemoryRegionOps slow_bar_ops = {
286     .old_mmio = {
287         .read = { slow_bar_readb, slow_bar_readw, slow_bar_readl, },
288         .write = { slow_bar_writeb, slow_bar_writew, slow_bar_writel, },
289     },
290     .endianness = DEVICE_NATIVE_ENDIAN,
291 };
292
293 static void assigned_dev_iomem_setup(PCIDevice *pci_dev, int region_num,
294                                      pcibus_t e_size)
295 {
296     AssignedDevice *r_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
297     AssignedDevRegion *region = &r_dev->v_addrs[region_num];
298     PCIRegion *real_region = &r_dev->real_device.regions[region_num];
299
300     if (e_size > 0) {
301         memory_region_init(&region->container, "assigned-dev-container",
302                            e_size);
303         memory_region_add_subregion(&region->container, 0, &region->real_iomem);
304
305         /* deal with MSI-X MMIO page */
306         if (real_region->base_addr <= r_dev->msix_table_addr &&
307                 real_region->base_addr + real_region->size >
308                 r_dev->msix_table_addr) {
309             uint64_t offset = r_dev->msix_table_addr - real_region->base_addr;
310
311             memory_region_add_subregion_overlap(&region->container,
312                                                 offset,
313                                                 &r_dev->mmio,
314                                                 1);
315         }
316     }
317 }
318
319 static const MemoryRegionOps assigned_dev_ioport_ops = {
320     .read = assigned_dev_ioport_read,
321     .write = assigned_dev_ioport_write,
322     .endianness = DEVICE_NATIVE_ENDIAN,
323 };
324
325 static void assigned_dev_ioport_setup(PCIDevice *pci_dev, int region_num,
326                                       pcibus_t size)
327 {
328     AssignedDevice *r_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
329     AssignedDevRegion *region = &r_dev->v_addrs[region_num];
330
331     region->e_size = size;
332     memory_region_init(&region->container, "assigned-dev-container", size);
333     memory_region_init_io(&region->real_iomem, &assigned_dev_ioport_ops,
334                           r_dev->v_addrs + region_num,
335                           "assigned-dev-iomem", size);
336     memory_region_add_subregion(&region->container, 0, &region->real_iomem);
337 }
338
339 static uint32_t assigned_dev_pci_read(PCIDevice *d, int pos, int len)
340 {
341     AssignedDevice *pci_dev = DO_UPCAST(AssignedDevice, dev, d);
342     uint32_t val;
343     ssize_t ret;
344     int fd = pci_dev->real_device.config_fd;
345
346 again:
347     ret = pread(fd, &val, len, pos);
348     if (ret != len) {
349         if ((ret < 0) && (errno == EINTR || errno == EAGAIN)) {
350             goto again;
351         }
352
353         hw_error("pci read failed, ret = %zd errno = %d\n", ret, errno);
354     }
355
356     return val;
357 }
358
359 static uint8_t assigned_dev_pci_read_byte(PCIDevice *d, int pos)
360 {
361     return (uint8_t)assigned_dev_pci_read(d, pos, 1);
362 }
363
364 static void assigned_dev_pci_write(PCIDevice *d, int pos, uint32_t val, int len)
365 {
366     AssignedDevice *pci_dev = DO_UPCAST(AssignedDevice, dev, d);
367     ssize_t ret;
368     int fd = pci_dev->real_device.config_fd;
369
370 again:
371     ret = pwrite(fd, &val, len, pos);
372     if (ret != len) {
373         if ((ret < 0) && (errno == EINTR || errno == EAGAIN)) {
374             goto again;
375         }
376
377         hw_error("pci write failed, ret = %zd errno = %d\n", ret, errno);
378     }
379 }
380
381 static void assigned_dev_emulate_config_read(AssignedDevice *dev,
382                                              uint32_t offset, uint32_t len)
383 {
384     memset(dev->emulate_config_read + offset, 0xff, len);
385 }
386
387 static void assigned_dev_direct_config_read(AssignedDevice *dev,
388                                             uint32_t offset, uint32_t len)
389 {
390     memset(dev->emulate_config_read + offset, 0, len);
391 }
392
393 static void assigned_dev_direct_config_write(AssignedDevice *dev,
394                                              uint32_t offset, uint32_t len)
395 {
396     memset(dev->emulate_config_write + offset, 0, len);
397 }
398
399 static uint8_t pci_find_cap_offset(PCIDevice *d, uint8_t cap, uint8_t start)
400 {
401     int id;
402     int max_cap = 48;
403     int pos = start ? start : PCI_CAPABILITY_LIST;
404     int status;
405
406     status = assigned_dev_pci_read_byte(d, PCI_STATUS);
407     if ((status & PCI_STATUS_CAP_LIST) == 0) {
408         return 0;
409     }
410
411     while (max_cap--) {
412         pos = assigned_dev_pci_read_byte(d, pos);
413         if (pos < 0x40) {
414             break;
415         }
416
417         pos &= ~3;
418         id = assigned_dev_pci_read_byte(d, pos + PCI_CAP_LIST_ID);
419
420         if (id == 0xff) {
421             break;
422         }
423         if (id == cap) {
424             return pos;
425         }
426
427         pos += PCI_CAP_LIST_NEXT;
428     }
429     return 0;
430 }
431
432 static int assigned_dev_register_regions(PCIRegion *io_regions,
433                                          unsigned long regions_num,
434                                          AssignedDevice *pci_dev)
435 {
436     uint32_t i;
437     PCIRegion *cur_region = io_regions;
438
439     for (i = 0; i < regions_num; i++, cur_region++) {
440         if (!cur_region->valid) {
441             continue;
442         }
443
444         /* handle memory io regions */
445         if (cur_region->type & IORESOURCE_MEM) {
446             int t = PCI_BASE_ADDRESS_SPACE_MEMORY;
447             if (cur_region->type & IORESOURCE_PREFETCH) {
448                 t |= PCI_BASE_ADDRESS_MEM_PREFETCH;
449             }
450             if (cur_region->type & IORESOURCE_MEM_64) {
451                 t |= PCI_BASE_ADDRESS_MEM_TYPE_64;
452             }
453
454             /* map physical memory */
455             pci_dev->v_addrs[i].u.r_virtbase = mmap(NULL, cur_region->size,
456                                                     PROT_WRITE | PROT_READ,
457                                                     MAP_SHARED,
458                                                     cur_region->resource_fd,
459                                                     (off_t)0);
460
461             if (pci_dev->v_addrs[i].u.r_virtbase == MAP_FAILED) {
462                 pci_dev->v_addrs[i].u.r_virtbase = NULL;
463                 error_report("%s: Error: Couldn't mmap 0x%" PRIx64 "!",
464                              __func__, cur_region->base_addr);
465                 return -1;
466             }
467
468             pci_dev->v_addrs[i].r_size = cur_region->size;
469             pci_dev->v_addrs[i].e_size = 0;
470
471             /* add offset */
472             pci_dev->v_addrs[i].u.r_virtbase +=
473                 (cur_region->base_addr & 0xFFF);
474
475             if (cur_region->size & 0xFFF) {
476                 error_report("PCI region %d at address 0x%" PRIx64 " has "
477                              "size 0x%" PRIx64 ", which is not a multiple of "
478                              "4K.  You might experience some performance hit "
479                              "due to that.",
480                              i, cur_region->base_addr, cur_region->size);
481                 memory_region_init_io(&pci_dev->v_addrs[i].real_iomem,
482                                       &slow_bar_ops, &pci_dev->v_addrs[i],
483                                       "assigned-dev-slow-bar",
484                                       cur_region->size);
485             } else {
486                 void *virtbase = pci_dev->v_addrs[i].u.r_virtbase;
487                 char name[32];
488                 snprintf(name, sizeof(name), "%s.bar%d",
489                          object_get_typename(OBJECT(pci_dev)), i);
490                 memory_region_init_ram_ptr(&pci_dev->v_addrs[i].real_iomem,
491                                            name, cur_region->size,
492                                            virtbase);
493                 vmstate_register_ram(&pci_dev->v_addrs[i].real_iomem,
494                                      &pci_dev->dev.qdev);
495             }
496
497             assigned_dev_iomem_setup(&pci_dev->dev, i, cur_region->size);
498             pci_register_bar((PCIDevice *) pci_dev, i, t,
499                              &pci_dev->v_addrs[i].container);
500             continue;
501         } else {
502             /* handle port io regions */
503             uint32_t val;
504             int ret;
505
506             /* Test kernel support for ioport resource read/write.  Old
507              * kernels return EIO.  New kernels only allow 1/2/4 byte reads
508              * so should return EINVAL for a 3 byte read */
509             ret = pread(pci_dev->v_addrs[i].region->resource_fd, &val, 3, 0);
510             if (ret >= 0) {
511                 error_report("Unexpected return from I/O port read: %d", ret);
512                 abort();
513             } else if (errno != EINVAL) {
514                 error_report("Kernel doesn't support ioport resource "
515                              "access, hiding this region.");
516                 close(pci_dev->v_addrs[i].region->resource_fd);
517                 cur_region->valid = 0;
518                 continue;
519             }
520
521             pci_dev->v_addrs[i].u.r_baseport = cur_region->base_addr;
522             pci_dev->v_addrs[i].r_size = cur_region->size;
523             pci_dev->v_addrs[i].e_size = 0;
524
525             assigned_dev_ioport_setup(&pci_dev->dev, i, cur_region->size);
526             pci_register_bar((PCIDevice *) pci_dev, i,
527                              PCI_BASE_ADDRESS_SPACE_IO,
528                              &pci_dev->v_addrs[i].container);
529         }
530     }
531
532     /* success */
533     return 0;
534 }
535
536 static int get_real_id(const char *devpath, const char *idname, uint16_t *val)
537 {
538     FILE *f;
539     char name[128];
540     long id;
541
542     snprintf(name, sizeof(name), "%s%s", devpath, idname);
543     f = fopen(name, "r");
544     if (f == NULL) {
545         error_report("%s: %s: %m", __func__, name);
546         return -1;
547     }
548     if (fscanf(f, "%li\n", &id) == 1) {
549         *val = id;
550     } else {
551         return -1;
552     }
553     fclose(f);
554
555     return 0;
556 }
557
558 static int get_real_vendor_id(const char *devpath, uint16_t *val)
559 {
560     return get_real_id(devpath, "vendor", val);
561 }
562
563 static int get_real_device_id(const char *devpath, uint16_t *val)
564 {
565     return get_real_id(devpath, "device", val);
566 }
567
568 static int get_real_device(AssignedDevice *pci_dev, uint16_t r_seg,
569                            uint8_t r_bus, uint8_t r_dev, uint8_t r_func)
570 {
571     char dir[128], name[128];
572     int fd, r = 0, v;
573     FILE *f;
574     uint64_t start, end, size, flags;
575     uint16_t id;
576     PCIRegion *rp;
577     PCIDevRegions *dev = &pci_dev->real_device;
578
579     dev->region_number = 0;
580
581     snprintf(dir, sizeof(dir), "/sys/bus/pci/devices/%04x:%02x:%02x.%x/",
582              r_seg, r_bus, r_dev, r_func);
583
584     snprintf(name, sizeof(name), "%sconfig", dir);
585
586     if (pci_dev->configfd_name && *pci_dev->configfd_name) {
587         dev->config_fd = monitor_handle_fd_param(cur_mon, pci_dev->configfd_name);
588         if (dev->config_fd < 0) {
589             return 1;
590         }
591     } else {
592         dev->config_fd = open(name, O_RDWR);
593
594         if (dev->config_fd == -1) {
595             error_report("%s: %s: %m", __func__, name);
596             return 1;
597         }
598     }
599 again:
600     r = read(dev->config_fd, pci_dev->dev.config,
601              pci_config_size(&pci_dev->dev));
602     if (r < 0) {
603         if (errno == EINTR || errno == EAGAIN) {
604             goto again;
605         }
606         error_report("%s: read failed, errno = %d", __func__, errno);
607     }
608
609     /* Restore or clear multifunction, this is always controlled by qemu */
610     if (pci_dev->dev.cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
611         pci_dev->dev.config[PCI_HEADER_TYPE] |= PCI_HEADER_TYPE_MULTI_FUNCTION;
612     } else {
613         pci_dev->dev.config[PCI_HEADER_TYPE] &= ~PCI_HEADER_TYPE_MULTI_FUNCTION;
614     }
615
616     /* Clear host resource mapping info.  If we choose not to register a
617      * BAR, such as might be the case with the option ROM, we can get
618      * confusing, unwritable, residual addresses from the host here. */
619     memset(&pci_dev->dev.config[PCI_BASE_ADDRESS_0], 0, 24);
620     memset(&pci_dev->dev.config[PCI_ROM_ADDRESS], 0, 4);
621
622     snprintf(name, sizeof(name), "%sresource", dir);
623
624     f = fopen(name, "r");
625     if (f == NULL) {
626         error_report("%s: %s: %m", __func__, name);
627         return 1;
628     }
629
630     for (r = 0; r < PCI_ROM_SLOT; r++) {
631         if (fscanf(f, "%" SCNi64 " %" SCNi64 " %" SCNi64 "\n",
632                    &start, &end, &flags) != 3) {
633             break;
634         }
635
636         rp = dev->regions + r;
637         rp->valid = 0;
638         rp->resource_fd = -1;
639         size = end - start + 1;
640         flags &= IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_PREFETCH
641                  | IORESOURCE_MEM_64;
642         if (size == 0 || (flags & ~IORESOURCE_PREFETCH) == 0) {
643             continue;
644         }
645         if (flags & IORESOURCE_MEM) {
646             flags &= ~IORESOURCE_IO;
647         } else {
648             flags &= ~IORESOURCE_PREFETCH;
649         }
650         snprintf(name, sizeof(name), "%sresource%d", dir, r);
651         fd = open(name, O_RDWR);
652         if (fd == -1) {
653             continue;
654         }
655         rp->resource_fd = fd;
656
657         rp->type = flags;
658         rp->valid = 1;
659         rp->base_addr = start;
660         rp->size = size;
661         pci_dev->v_addrs[r].region = rp;
662         DEBUG("region %d size %" PRIu64 " start 0x%" PRIx64
663               " type %d resource_fd %d\n",
664               r, rp->size, start, rp->type, rp->resource_fd);
665     }
666
667     fclose(f);
668
669     /* read and fill vendor ID */
670     v = get_real_vendor_id(dir, &id);
671     if (v) {
672         return 1;
673     }
674     pci_dev->dev.config[0] = id & 0xff;
675     pci_dev->dev.config[1] = (id & 0xff00) >> 8;
676
677     /* read and fill device ID */
678     v = get_real_device_id(dir, &id);
679     if (v) {
680         return 1;
681     }
682     pci_dev->dev.config[2] = id & 0xff;
683     pci_dev->dev.config[3] = (id & 0xff00) >> 8;
684
685     pci_word_test_and_clear_mask(pci_dev->emulate_config_write + PCI_COMMAND,
686                                  PCI_COMMAND_MASTER | PCI_COMMAND_INTX_DISABLE);
687
688     dev->region_number = r;
689     return 0;
690 }
691
692 static void free_msi_virqs(AssignedDevice *dev)
693 {
694     int i;
695
696     for (i = 0; i < dev->msi_virq_nr; i++) {
697         if (dev->msi_virq[i] >= 0) {
698             kvm_irqchip_release_virq(kvm_state, dev->msi_virq[i]);
699             dev->msi_virq[i] = -1;
700         }
701     }
702     g_free(dev->msi_virq);
703     dev->msi_virq = NULL;
704     dev->msi_virq_nr = 0;
705 }
706
707 static void free_assigned_device(AssignedDevice *dev)
708 {
709     int i;
710
711     if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
712         assigned_dev_unregister_msix_mmio(dev);
713     }
714     for (i = 0; i < dev->real_device.region_number; i++) {
715         PCIRegion *pci_region = &dev->real_device.regions[i];
716         AssignedDevRegion *region = &dev->v_addrs[i];
717
718         if (!pci_region->valid) {
719             continue;
720         }
721         if (pci_region->type & IORESOURCE_IO) {
722             if (region->u.r_baseport) {
723                 memory_region_del_subregion(&region->container,
724                                             &region->real_iomem);
725                 memory_region_destroy(&region->real_iomem);
726                 memory_region_destroy(&region->container);
727             }
728         } else if (pci_region->type & IORESOURCE_MEM) {
729             if (region->u.r_virtbase) {
730                 memory_region_del_subregion(&region->container,
731                                             &region->real_iomem);
732
733                 /* Remove MSI-X table subregion */
734                 if (pci_region->base_addr <= dev->msix_table_addr &&
735                     pci_region->base_addr + pci_region->size >
736                     dev->msix_table_addr) {
737                     memory_region_del_subregion(&region->container,
738                                                 &dev->mmio);
739                 }
740
741                 memory_region_destroy(&region->real_iomem);
742                 memory_region_destroy(&region->container);
743                 if (munmap(region->u.r_virtbase,
744                            (pci_region->size + 0xFFF) & 0xFFFFF000)) {
745                     error_report("Failed to unmap assigned device region: %s",
746                                  strerror(errno));
747                 }
748             }
749         }
750         if (pci_region->resource_fd >= 0) {
751             close(pci_region->resource_fd);
752         }
753     }
754
755     if (dev->real_device.config_fd >= 0) {
756         close(dev->real_device.config_fd);
757     }
758
759     free_msi_virqs(dev);
760 }
761
762 static void assign_failed_examine(AssignedDevice *dev)
763 {
764     char name[PATH_MAX], dir[PATH_MAX], driver[PATH_MAX] = {}, *ns;
765     uint16_t vendor_id, device_id;
766     int r;
767
768     snprintf(dir, sizeof(dir), "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",
769             dev->host.domain, dev->host.bus, dev->host.slot,
770             dev->host.function);
771
772     snprintf(name, sizeof(name), "%sdriver", dir);
773
774     r = readlink(name, driver, sizeof(driver));
775     if ((r <= 0) || r >= sizeof(driver)) {
776         goto fail;
777     }
778
779     ns = strrchr(driver, '/');
780     if (!ns) {
781         goto fail;
782     }
783
784     ns++;
785
786     if (get_real_vendor_id(dir, &vendor_id) ||
787         get_real_device_id(dir, &device_id)) {
788         goto fail;
789     }
790
791     error_report("*** The driver '%s' is occupying your device "
792                  "%04x:%02x:%02x.%x.",
793                  ns, dev->host.domain, dev->host.bus, dev->host.slot,
794                  dev->host.function);
795     error_report("***");
796     error_report("*** You can try the following commands to free it:");
797     error_report("***");
798     error_report("*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub/"
799                  "new_id", vendor_id, device_id);
800     error_report("*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/"
801                  "%s/unbind",
802                  dev->host.domain, dev->host.bus, dev->host.slot,
803                  dev->host.function, ns);
804     error_report("*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/"
805                  "pci-stub/bind",
806                  dev->host.domain, dev->host.bus, dev->host.slot,
807                  dev->host.function);
808     error_report("*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub"
809                  "/remove_id", vendor_id, device_id);
810     error_report("***");
811
812     return;
813
814 fail:
815     error_report("Couldn't find out why.");
816 }
817
818 static int assign_device(AssignedDevice *dev)
819 {
820     uint32_t flags = KVM_DEV_ASSIGN_ENABLE_IOMMU;
821     int r;
822
823     /* Only pass non-zero PCI segment to capable module */
824     if (!kvm_check_extension(kvm_state, KVM_CAP_PCI_SEGMENT) &&
825         dev->host.domain) {
826         error_report("Can't assign device inside non-zero PCI segment "
827                      "as this KVM module doesn't support it.");
828         return -ENODEV;
829     }
830
831     if (!kvm_check_extension(kvm_state, KVM_CAP_IOMMU)) {
832         error_report("No IOMMU found.  Unable to assign device \"%s\"",
833                      dev->dev.qdev.id);
834         return -ENODEV;
835     }
836
837     if (dev->features & ASSIGNED_DEVICE_SHARE_INTX_MASK &&
838         kvm_has_intx_set_mask()) {
839         flags |= KVM_DEV_ASSIGN_PCI_2_3;
840     }
841
842     r = kvm_device_pci_assign(kvm_state, &dev->host, flags, &dev->dev_id);
843     if (r < 0) {
844         error_report("Failed to assign device \"%s\" : %s",
845                      dev->dev.qdev.id, strerror(-r));
846
847         switch (r) {
848         case -EBUSY:
849             assign_failed_examine(dev);
850             break;
851         default:
852             break;
853         }
854     }
855     return r;
856 }
857
858 static bool check_irqchip_in_kernel(void)
859 {
860     if (kvm_irqchip_in_kernel()) {
861         return true;
862     }
863     error_report("pci-assign: error: requires KVM with in-kernel irqchip "
864                  "enabled");
865     return false;
866 }
867
868 static int assign_intx(AssignedDevice *dev)
869 {
870     AssignedIRQType new_type;
871     PCIINTxRoute intx_route;
872     bool intx_host_msi;
873     int r;
874
875     /* Interrupt PIN 0 means don't use INTx */
876     if (assigned_dev_pci_read_byte(&dev->dev, PCI_INTERRUPT_PIN) == 0) {
877         pci_device_set_intx_routing_notifier(&dev->dev, NULL);
878         return 0;
879     }
880
881     if (!check_irqchip_in_kernel()) {
882         return -ENOTSUP;
883     }
884
885     pci_device_set_intx_routing_notifier(&dev->dev,
886                                          assigned_dev_update_irq_routing);
887
888     intx_route = pci_device_route_intx_to_irq(&dev->dev, dev->intpin);
889     assert(intx_route.mode != PCI_INTX_INVERTED);
890
891     if (!pci_intx_route_changed(&dev->intx_route, &intx_route)) {
892         return 0;
893     }
894
895     switch (dev->assigned_irq_type) {
896     case ASSIGNED_IRQ_INTX_HOST_INTX:
897     case ASSIGNED_IRQ_INTX_HOST_MSI:
898         intx_host_msi = dev->assigned_irq_type == ASSIGNED_IRQ_INTX_HOST_MSI;
899         r = kvm_device_intx_deassign(kvm_state, dev->dev_id, intx_host_msi);
900         break;
901     case ASSIGNED_IRQ_MSI:
902         r = kvm_device_msi_deassign(kvm_state, dev->dev_id);
903         break;
904     case ASSIGNED_IRQ_MSIX:
905         r = kvm_device_msix_deassign(kvm_state, dev->dev_id);
906         break;
907     default:
908         r = 0;
909         break;
910     }
911     if (r) {
912         perror("assign_intx: deassignment of previous interrupt failed");
913     }
914     dev->assigned_irq_type = ASSIGNED_IRQ_NONE;
915
916     if (intx_route.mode == PCI_INTX_DISABLED) {
917         dev->intx_route = intx_route;
918         return 0;
919     }
920
921 retry:
922     if (dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK &&
923         dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
924         intx_host_msi = true;
925         new_type = ASSIGNED_IRQ_INTX_HOST_MSI;
926     } else {
927         intx_host_msi = false;
928         new_type = ASSIGNED_IRQ_INTX_HOST_INTX;
929     }
930
931     r = kvm_device_intx_assign(kvm_state, dev->dev_id, intx_host_msi,
932                                intx_route.irq);
933     if (r < 0) {
934         if (r == -EIO && !(dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK) &&
935             dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
936             /* Retry with host-side MSI. There might be an IRQ conflict and
937              * either the kernel or the device doesn't support sharing. */
938             error_report("Host-side INTx sharing not supported, "
939                          "using MSI instead");
940             error_printf("Some devices do not work properly in this mode.\n");
941             dev->features |= ASSIGNED_DEVICE_PREFER_MSI_MASK;
942             goto retry;
943         }
944         error_report("Failed to assign irq for \"%s\": %s",
945                      dev->dev.qdev.id, strerror(-r));
946         error_report("Perhaps you are assigning a device "
947                      "that shares an IRQ with another device?");
948         return r;
949     }
950
951     dev->intx_route = intx_route;
952     dev->assigned_irq_type = new_type;
953     return r;
954 }
955
956 static void deassign_device(AssignedDevice *dev)
957 {
958     int r;
959
960     r = kvm_device_pci_deassign(kvm_state, dev->dev_id);
961     assert(r == 0);
962 }
963
964 /* The pci config space got updated. Check if irq numbers have changed
965  * for our devices
966  */
967 static void assigned_dev_update_irq_routing(PCIDevice *dev)
968 {
969     AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, dev);
970     Error *err = NULL;
971     int r;
972
973     r = assign_intx(assigned_dev);
974     if (r < 0) {
975         qdev_unplug(&dev->qdev, &err);
976         assert(!err);
977     }
978 }
979
980 static void assigned_dev_update_msi(PCIDevice *pci_dev)
981 {
982     AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
983     uint8_t ctrl_byte = pci_get_byte(pci_dev->config + pci_dev->msi_cap +
984                                      PCI_MSI_FLAGS);
985     int r;
986
987     /* Some guests gratuitously disable MSI even if they're not using it,
988      * try to catch this by only deassigning irqs if the guest is using
989      * MSI or intends to start. */
990     if (assigned_dev->assigned_irq_type == ASSIGNED_IRQ_MSI ||
991         (ctrl_byte & PCI_MSI_FLAGS_ENABLE)) {
992         r = kvm_device_msi_deassign(kvm_state, assigned_dev->dev_id);
993         /* -ENXIO means no assigned irq */
994         if (r && r != -ENXIO) {
995             perror("assigned_dev_update_msi: deassign irq");
996         }
997
998         free_msi_virqs(assigned_dev);
999
1000         assigned_dev->assigned_irq_type = ASSIGNED_IRQ_NONE;
1001         pci_device_set_intx_routing_notifier(pci_dev, NULL);
1002     }
1003
1004     if (ctrl_byte & PCI_MSI_FLAGS_ENABLE) {
1005         MSIMessage msg = msi_get_message(pci_dev, 0);
1006         int virq;
1007
1008         virq = kvm_irqchip_add_msi_route(kvm_state, msg);
1009         if (virq < 0) {
1010             perror("assigned_dev_update_msi: kvm_irqchip_add_msi_route");
1011             return;
1012         }
1013
1014         assigned_dev->msi_virq = g_malloc(sizeof(*assigned_dev->msi_virq));
1015         assigned_dev->msi_virq_nr = 1;
1016         assigned_dev->msi_virq[0] = virq;
1017         if (kvm_device_msi_assign(kvm_state, assigned_dev->dev_id, virq) < 0) {
1018             perror("assigned_dev_update_msi: kvm_device_msi_assign");
1019         }
1020
1021         assigned_dev->intx_route.mode = PCI_INTX_DISABLED;
1022         assigned_dev->intx_route.irq = -1;
1023         assigned_dev->assigned_irq_type = ASSIGNED_IRQ_MSI;
1024     } else {
1025         assign_intx(assigned_dev);
1026     }
1027 }
1028
1029 static void assigned_dev_update_msi_msg(PCIDevice *pci_dev)
1030 {
1031     AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1032     uint8_t ctrl_byte = pci_get_byte(pci_dev->config + pci_dev->msi_cap +
1033                                      PCI_MSI_FLAGS);
1034
1035     if (assigned_dev->assigned_irq_type != ASSIGNED_IRQ_MSI ||
1036         !(ctrl_byte & PCI_MSI_FLAGS_ENABLE)) {
1037         return;
1038     }
1039
1040     kvm_irqchip_update_msi_route(kvm_state, assigned_dev->msi_virq[0],
1041                                  msi_get_message(pci_dev, 0));
1042 }
1043
1044 static bool assigned_dev_msix_masked(MSIXTableEntry *entry)
1045 {
1046     return (entry->ctrl & cpu_to_le32(0x1)) != 0;
1047 }
1048
1049 /*
1050  * When MSI-X is first enabled the vector table typically has all the
1051  * vectors masked, so we can't use that as the obvious test to figure out
1052  * how many vectors to initially enable.  Instead we look at the data field
1053  * because this is what worked for pci-assign for a long time.  This makes
1054  * sure the physical MSI-X state tracks the guest's view, which is important
1055  * for some VF/PF and PF/fw communication channels.
1056  */
1057 static bool assigned_dev_msix_skipped(MSIXTableEntry *entry)
1058 {
1059     return !entry->data;
1060 }
1061
1062 static int assigned_dev_update_msix_mmio(PCIDevice *pci_dev)
1063 {
1064     AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1065     uint16_t entries_nr = 0;
1066     int i, r = 0;
1067     MSIXTableEntry *entry = adev->msix_table;
1068     MSIMessage msg;
1069
1070     /* Get the usable entry number for allocating */
1071     for (i = 0; i < adev->msix_max; i++, entry++) {
1072         if (assigned_dev_msix_skipped(entry)) {
1073             continue;
1074         }
1075         entries_nr++;
1076     }
1077
1078     DEBUG("MSI-X entries: %d\n", entries_nr);
1079
1080     /* It's valid to enable MSI-X with all entries masked */
1081     if (!entries_nr) {
1082         return 0;
1083     }
1084
1085     r = kvm_device_msix_init_vectors(kvm_state, adev->dev_id, entries_nr);
1086     if (r != 0) {
1087         error_report("fail to set MSI-X entry number for MSIX! %s",
1088                      strerror(-r));
1089         return r;
1090     }
1091
1092     free_msi_virqs(adev);
1093
1094     adev->msi_virq_nr = adev->msix_max;
1095     adev->msi_virq = g_malloc(adev->msix_max * sizeof(*adev->msi_virq));
1096
1097     entry = adev->msix_table;
1098     for (i = 0; i < adev->msix_max; i++, entry++) {
1099         adev->msi_virq[i] = -1;
1100
1101         if (assigned_dev_msix_skipped(entry)) {
1102             continue;
1103         }
1104
1105         msg.address = entry->addr_lo | ((uint64_t)entry->addr_hi << 32);
1106         msg.data = entry->data;
1107         r = kvm_irqchip_add_msi_route(kvm_state, msg);
1108         if (r < 0) {
1109             return r;
1110         }
1111         adev->msi_virq[i] = r;
1112
1113         DEBUG("MSI-X vector %d, gsi %d, addr %08x_%08x, data %08x\n", i,
1114               r, entry->addr_hi, entry->addr_lo, entry->data);
1115
1116         r = kvm_device_msix_set_vector(kvm_state, adev->dev_id, i,
1117                                        adev->msi_virq[i]);
1118         if (r) {
1119             error_report("fail to set MSI-X entry! %s", strerror(-r));
1120             break;
1121         }
1122     }
1123
1124     return r;
1125 }
1126
1127 static void assigned_dev_update_msix(PCIDevice *pci_dev)
1128 {
1129     AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1130     uint16_t ctrl_word = pci_get_word(pci_dev->config + pci_dev->msix_cap +
1131                                       PCI_MSIX_FLAGS);
1132     int r;
1133
1134     /* Some guests gratuitously disable MSIX even if they're not using it,
1135      * try to catch this by only deassigning irqs if the guest is using
1136      * MSIX or intends to start. */
1137     if ((assigned_dev->assigned_irq_type == ASSIGNED_IRQ_MSIX) ||
1138         (ctrl_word & PCI_MSIX_FLAGS_ENABLE)) {
1139         r = kvm_device_msix_deassign(kvm_state, assigned_dev->dev_id);
1140         /* -ENXIO means no assigned irq */
1141         if (r && r != -ENXIO) {
1142             perror("assigned_dev_update_msix: deassign irq");
1143         }
1144
1145         free_msi_virqs(assigned_dev);
1146
1147         assigned_dev->assigned_irq_type = ASSIGNED_IRQ_NONE;
1148         pci_device_set_intx_routing_notifier(pci_dev, NULL);
1149     }
1150
1151     if (ctrl_word & PCI_MSIX_FLAGS_ENABLE) {
1152         if (assigned_dev_update_msix_mmio(pci_dev) < 0) {
1153             perror("assigned_dev_update_msix_mmio");
1154             return;
1155         }
1156
1157         if (assigned_dev->msi_virq_nr > 0) {
1158             if (kvm_device_msix_assign(kvm_state, assigned_dev->dev_id) < 0) {
1159                 perror("assigned_dev_enable_msix: assign irq");
1160                 return;
1161             }
1162         }
1163         assigned_dev->intx_route.mode = PCI_INTX_DISABLED;
1164         assigned_dev->intx_route.irq = -1;
1165         assigned_dev->assigned_irq_type = ASSIGNED_IRQ_MSIX;
1166     } else {
1167         assign_intx(assigned_dev);
1168     }
1169 }
1170
1171 static uint32_t assigned_dev_pci_read_config(PCIDevice *pci_dev,
1172                                              uint32_t address, int len)
1173 {
1174     AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1175     uint32_t virt_val = pci_default_read_config(pci_dev, address, len);
1176     uint32_t real_val, emulate_mask, full_emulation_mask;
1177
1178     emulate_mask = 0;
1179     memcpy(&emulate_mask, assigned_dev->emulate_config_read + address, len);
1180     emulate_mask = le32_to_cpu(emulate_mask);
1181
1182     full_emulation_mask = 0xffffffff >> (32 - len * 8);
1183
1184     if (emulate_mask != full_emulation_mask) {
1185         real_val = assigned_dev_pci_read(pci_dev, address, len);
1186         return (virt_val & emulate_mask) | (real_val & ~emulate_mask);
1187     } else {
1188         return virt_val;
1189     }
1190 }
1191
1192 static void assigned_dev_pci_write_config(PCIDevice *pci_dev, uint32_t address,
1193                                           uint32_t val, int len)
1194 {
1195     AssignedDevice *assigned_dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1196     uint16_t old_cmd = pci_get_word(pci_dev->config + PCI_COMMAND);
1197     uint32_t emulate_mask, full_emulation_mask;
1198     int ret;
1199
1200     pci_default_write_config(pci_dev, address, val, len);
1201
1202     if (kvm_has_intx_set_mask() &&
1203         range_covers_byte(address, len, PCI_COMMAND + 1)) {
1204         bool intx_masked = (pci_get_word(pci_dev->config + PCI_COMMAND) &
1205                             PCI_COMMAND_INTX_DISABLE);
1206
1207         if (intx_masked != !!(old_cmd & PCI_COMMAND_INTX_DISABLE)) {
1208             ret = kvm_device_intx_set_mask(kvm_state, assigned_dev->dev_id,
1209                                            intx_masked);
1210             if (ret) {
1211                 perror("assigned_dev_pci_write_config: set intx mask");
1212             }
1213         }
1214     }
1215     if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {
1216         if (range_covers_byte(address, len,
1217                               pci_dev->msi_cap + PCI_MSI_FLAGS)) {
1218             assigned_dev_update_msi(pci_dev);
1219         } else if (ranges_overlap(address, len, /* 32bit MSI only */
1220                                   pci_dev->msi_cap + PCI_MSI_ADDRESS_LO, 6)) {
1221             assigned_dev_update_msi_msg(pci_dev);
1222         }
1223     }
1224     if (assigned_dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1225         if (range_covers_byte(address, len,
1226                               pci_dev->msix_cap + PCI_MSIX_FLAGS + 1)) {
1227             assigned_dev_update_msix(pci_dev);
1228         }
1229     }
1230
1231     emulate_mask = 0;
1232     memcpy(&emulate_mask, assigned_dev->emulate_config_write + address, len);
1233     emulate_mask = le32_to_cpu(emulate_mask);
1234
1235     full_emulation_mask = 0xffffffff >> (32 - len * 8);
1236
1237     if (emulate_mask != full_emulation_mask) {
1238         if (emulate_mask) {
1239             val &= ~emulate_mask;
1240             val |= assigned_dev_pci_read(pci_dev, address, len) & emulate_mask;
1241         }
1242         assigned_dev_pci_write(pci_dev, address, val, len);
1243     }
1244 }
1245
1246 static void assigned_dev_setup_cap_read(AssignedDevice *dev, uint32_t offset,
1247                                         uint32_t len)
1248 {
1249     assigned_dev_direct_config_read(dev, offset, len);
1250     assigned_dev_emulate_config_read(dev, offset + PCI_CAP_LIST_NEXT, 1);
1251 }
1252
1253 static int assigned_device_pci_cap_init(PCIDevice *pci_dev)
1254 {
1255     AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1256     PCIRegion *pci_region = dev->real_device.regions;
1257     int ret, pos;
1258
1259     /* Clear initial capabilities pointer and status copied from hw */
1260     pci_set_byte(pci_dev->config + PCI_CAPABILITY_LIST, 0);
1261     pci_set_word(pci_dev->config + PCI_STATUS,
1262                  pci_get_word(pci_dev->config + PCI_STATUS) &
1263                  ~PCI_STATUS_CAP_LIST);
1264
1265     /* Expose MSI capability
1266      * MSI capability is the 1st capability in capability config */
1267     pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSI, 0);
1268     if (pos != 0 && kvm_check_extension(kvm_state, KVM_CAP_ASSIGN_DEV_IRQ)) {
1269         if (!check_irqchip_in_kernel()) {
1270             return -ENOTSUP;
1271         }
1272         dev->cap.available |= ASSIGNED_DEVICE_CAP_MSI;
1273         /* Only 32-bit/no-mask currently supported */
1274         ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSI, pos, 10);
1275         if (ret < 0) {
1276             return ret;
1277         }
1278         pci_dev->msi_cap = pos;
1279
1280         pci_set_word(pci_dev->config + pos + PCI_MSI_FLAGS,
1281                      pci_get_word(pci_dev->config + pos + PCI_MSI_FLAGS) &
1282                      PCI_MSI_FLAGS_QMASK);
1283         pci_set_long(pci_dev->config + pos + PCI_MSI_ADDRESS_LO, 0);
1284         pci_set_word(pci_dev->config + pos + PCI_MSI_DATA_32, 0);
1285
1286         /* Set writable fields */
1287         pci_set_word(pci_dev->wmask + pos + PCI_MSI_FLAGS,
1288                      PCI_MSI_FLAGS_QSIZE | PCI_MSI_FLAGS_ENABLE);
1289         pci_set_long(pci_dev->wmask + pos + PCI_MSI_ADDRESS_LO, 0xfffffffc);
1290         pci_set_word(pci_dev->wmask + pos + PCI_MSI_DATA_32, 0xffff);
1291     }
1292     /* Expose MSI-X capability */
1293     pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSIX, 0);
1294     if (pos != 0 && kvm_device_msix_supported(kvm_state)) {
1295         int bar_nr;
1296         uint32_t msix_table_entry;
1297
1298         if (!check_irqchip_in_kernel()) {
1299             return -ENOTSUP;
1300         }
1301         dev->cap.available |= ASSIGNED_DEVICE_CAP_MSIX;
1302         ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSIX, pos, 12);
1303         if (ret < 0) {
1304             return ret;
1305         }
1306         pci_dev->msix_cap = pos;
1307
1308         pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS,
1309                      pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) &
1310                      PCI_MSIX_FLAGS_QSIZE);
1311
1312         /* Only enable and function mask bits are writable */
1313         pci_set_word(pci_dev->wmask + pos + PCI_MSIX_FLAGS,
1314                      PCI_MSIX_FLAGS_ENABLE | PCI_MSIX_FLAGS_MASKALL);
1315
1316         msix_table_entry = pci_get_long(pci_dev->config + pos + PCI_MSIX_TABLE);
1317         bar_nr = msix_table_entry & PCI_MSIX_FLAGS_BIRMASK;
1318         msix_table_entry &= ~PCI_MSIX_FLAGS_BIRMASK;
1319         dev->msix_table_addr = pci_region[bar_nr].base_addr + msix_table_entry;
1320         dev->msix_max = pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS);
1321         dev->msix_max &= PCI_MSIX_FLAGS_QSIZE;
1322         dev->msix_max += 1;
1323     }
1324
1325     /* Minimal PM support, nothing writable, device appears to NAK changes */
1326     pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PM, 0);
1327     if (pos) {
1328         uint16_t pmc;
1329
1330         ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, pos, PCI_PM_SIZEOF);
1331         if (ret < 0) {
1332             return ret;
1333         }
1334
1335         assigned_dev_setup_cap_read(dev, pos, PCI_PM_SIZEOF);
1336
1337         pmc = pci_get_word(pci_dev->config + pos + PCI_CAP_FLAGS);
1338         pmc &= (PCI_PM_CAP_VER_MASK | PCI_PM_CAP_DSI);
1339         pci_set_word(pci_dev->config + pos + PCI_CAP_FLAGS, pmc);
1340
1341         /* assign_device will bring the device up to D0, so we don't need
1342          * to worry about doing that ourselves here. */
1343         pci_set_word(pci_dev->config + pos + PCI_PM_CTRL,
1344                      PCI_PM_CTRL_NO_SOFT_RESET);
1345
1346         pci_set_byte(pci_dev->config + pos + PCI_PM_PPB_EXTENSIONS, 0);
1347         pci_set_byte(pci_dev->config + pos + PCI_PM_DATA_REGISTER, 0);
1348     }
1349
1350     pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_EXP, 0);
1351     if (pos) {
1352         uint8_t version, size = 0;
1353         uint16_t type, devctl, lnksta;
1354         uint32_t devcap, lnkcap;
1355
1356         version = pci_get_byte(pci_dev->config + pos + PCI_EXP_FLAGS);
1357         version &= PCI_EXP_FLAGS_VERS;
1358         if (version == 1) {
1359             size = 0x14;
1360         } else if (version == 2) {
1361             /*
1362              * Check for non-std size, accept reduced size to 0x34,
1363              * which is what bcm5761 implemented, violating the
1364              * PCIe v3.0 spec that regs should exist and be read as 0,
1365              * not optionally provided and shorten the struct size.
1366              */
1367             size = MIN(0x3c, PCI_CONFIG_SPACE_SIZE - pos);
1368             if (size < 0x34) {
1369                 error_report("%s: Invalid size PCIe cap-id 0x%x",
1370                              __func__, PCI_CAP_ID_EXP);
1371                 return -EINVAL;
1372             } else if (size != 0x3c) {
1373                 error_report("WARNING, %s: PCIe cap-id 0x%x has "
1374                              "non-standard size 0x%x; std size should be 0x3c",
1375                              __func__, PCI_CAP_ID_EXP, size);
1376             }
1377         } else if (version == 0) {
1378             uint16_t vid, did;
1379             vid = pci_get_word(pci_dev->config + PCI_VENDOR_ID);
1380             did = pci_get_word(pci_dev->config + PCI_DEVICE_ID);
1381             if (vid == PCI_VENDOR_ID_INTEL && did == 0x10ed) {
1382                 /*
1383                  * quirk for Intel 82599 VF with invalid PCIe capability
1384                  * version, should really be version 2 (same as PF)
1385                  */
1386                 size = 0x3c;
1387             }
1388         }
1389
1390         if (size == 0) {
1391             error_report("%s: Unsupported PCI express capability version %d",
1392                          __func__, version);
1393             return -EINVAL;
1394         }
1395
1396         ret = pci_add_capability(pci_dev, PCI_CAP_ID_EXP, pos, size);
1397         if (ret < 0) {
1398             return ret;
1399         }
1400
1401         assigned_dev_setup_cap_read(dev, pos, size);
1402
1403         type = pci_get_word(pci_dev->config + pos + PCI_EXP_FLAGS);
1404         type = (type & PCI_EXP_FLAGS_TYPE) >> 4;
1405         if (type != PCI_EXP_TYPE_ENDPOINT &&
1406             type != PCI_EXP_TYPE_LEG_END && type != PCI_EXP_TYPE_RC_END) {
1407             error_report("Device assignment only supports endpoint assignment,"
1408                          " device type %d", type);
1409             return -EINVAL;
1410         }
1411
1412         /* capabilities, pass existing read-only copy
1413          * PCI_EXP_FLAGS_IRQ: updated by hardware, should be direct read */
1414
1415         /* device capabilities: hide FLR */
1416         devcap = pci_get_long(pci_dev->config + pos + PCI_EXP_DEVCAP);
1417         devcap &= ~PCI_EXP_DEVCAP_FLR;
1418         pci_set_long(pci_dev->config + pos + PCI_EXP_DEVCAP, devcap);
1419
1420         /* device control: clear all error reporting enable bits, leaving
1421          *                 only a few host values.  Note, these are
1422          *                 all writable, but not passed to hw.
1423          */
1424         devctl = pci_get_word(pci_dev->config + pos + PCI_EXP_DEVCTL);
1425         devctl = (devctl & (PCI_EXP_DEVCTL_READRQ | PCI_EXP_DEVCTL_PAYLOAD)) |
1426                   PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN;
1427         pci_set_word(pci_dev->config + pos + PCI_EXP_DEVCTL, devctl);
1428         devctl = PCI_EXP_DEVCTL_BCR_FLR | PCI_EXP_DEVCTL_AUX_PME;
1429         pci_set_word(pci_dev->wmask + pos + PCI_EXP_DEVCTL, ~devctl);
1430
1431         /* Clear device status */
1432         pci_set_word(pci_dev->config + pos + PCI_EXP_DEVSTA, 0);
1433
1434         /* Link capabilities, expose links and latencues, clear reporting */
1435         lnkcap = pci_get_long(pci_dev->config + pos + PCI_EXP_LNKCAP);
1436         lnkcap &= (PCI_EXP_LNKCAP_SLS | PCI_EXP_LNKCAP_MLW |
1437                    PCI_EXP_LNKCAP_ASPMS | PCI_EXP_LNKCAP_L0SEL |
1438                    PCI_EXP_LNKCAP_L1EL);
1439         pci_set_long(pci_dev->config + pos + PCI_EXP_LNKCAP, lnkcap);
1440
1441         /* Link control, pass existing read-only copy.  Should be writable? */
1442
1443         /* Link status, only expose current speed and width */
1444         lnksta = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKSTA);
1445         lnksta &= (PCI_EXP_LNKSTA_CLS | PCI_EXP_LNKSTA_NLW);
1446         pci_set_word(pci_dev->config + pos + PCI_EXP_LNKSTA, lnksta);
1447
1448         if (version >= 2) {
1449             /* Slot capabilities, control, status - not needed for endpoints */
1450             pci_set_long(pci_dev->config + pos + PCI_EXP_SLTCAP, 0);
1451             pci_set_word(pci_dev->config + pos + PCI_EXP_SLTCTL, 0);
1452             pci_set_word(pci_dev->config + pos + PCI_EXP_SLTSTA, 0);
1453
1454             /* Root control, capabilities, status - not needed for endpoints */
1455             pci_set_word(pci_dev->config + pos + PCI_EXP_RTCTL, 0);
1456             pci_set_word(pci_dev->config + pos + PCI_EXP_RTCAP, 0);
1457             pci_set_long(pci_dev->config + pos + PCI_EXP_RTSTA, 0);
1458
1459             /* Device capabilities/control 2, pass existing read-only copy */
1460             /* Link control 2, pass existing read-only copy */
1461         }
1462     }
1463
1464     pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PCIX, 0);
1465     if (pos) {
1466         uint16_t cmd;
1467         uint32_t status;
1468
1469         /* Only expose the minimum, 8 byte capability */
1470         ret = pci_add_capability(pci_dev, PCI_CAP_ID_PCIX, pos, 8);
1471         if (ret < 0) {
1472             return ret;
1473         }
1474
1475         assigned_dev_setup_cap_read(dev, pos, 8);
1476
1477         /* Command register, clear upper bits, including extended modes */
1478         cmd = pci_get_word(pci_dev->config + pos + PCI_X_CMD);
1479         cmd &= (PCI_X_CMD_DPERR_E | PCI_X_CMD_ERO | PCI_X_CMD_MAX_READ |
1480                 PCI_X_CMD_MAX_SPLIT);
1481         pci_set_word(pci_dev->config + pos + PCI_X_CMD, cmd);
1482
1483         /* Status register, update with emulated PCI bus location, clear
1484          * error bits, leave the rest. */
1485         status = pci_get_long(pci_dev->config + pos + PCI_X_STATUS);
1486         status &= ~(PCI_X_STATUS_BUS | PCI_X_STATUS_DEVFN);
1487         status |= (pci_bus_num(pci_dev->bus) << 8) | pci_dev->devfn;
1488         status &= ~(PCI_X_STATUS_SPL_DISC | PCI_X_STATUS_UNX_SPL |
1489                     PCI_X_STATUS_SPL_ERR);
1490         pci_set_long(pci_dev->config + pos + PCI_X_STATUS, status);
1491     }
1492
1493     pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VPD, 0);
1494     if (pos) {
1495         /* Direct R/W passthrough */
1496         ret = pci_add_capability(pci_dev, PCI_CAP_ID_VPD, pos, 8);
1497         if (ret < 0) {
1498             return ret;
1499         }
1500
1501         assigned_dev_setup_cap_read(dev, pos, 8);
1502
1503         /* direct write for cap content */
1504         assigned_dev_direct_config_write(dev, pos + 2, 6);
1505     }
1506
1507     /* Devices can have multiple vendor capabilities, get them all */
1508     for (pos = 0; (pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VNDR, pos));
1509         pos += PCI_CAP_LIST_NEXT) {
1510         uint8_t len = pci_get_byte(pci_dev->config + pos + PCI_CAP_FLAGS);
1511         /* Direct R/W passthrough */
1512         ret = pci_add_capability(pci_dev, PCI_CAP_ID_VNDR, pos, len);
1513         if (ret < 0) {
1514             return ret;
1515         }
1516
1517         assigned_dev_setup_cap_read(dev, pos, len);
1518
1519         /* direct write for cap content */
1520         assigned_dev_direct_config_write(dev, pos + 2, len - 2);
1521     }
1522
1523     /* If real and virtual capability list status bits differ, virtualize the
1524      * access. */
1525     if ((pci_get_word(pci_dev->config + PCI_STATUS) & PCI_STATUS_CAP_LIST) !=
1526         (assigned_dev_pci_read_byte(pci_dev, PCI_STATUS) &
1527          PCI_STATUS_CAP_LIST)) {
1528         dev->emulate_config_read[PCI_STATUS] |= PCI_STATUS_CAP_LIST;
1529     }
1530
1531     return 0;
1532 }
1533
1534 static uint64_t
1535 assigned_dev_msix_mmio_read(void *opaque, hwaddr addr,
1536                             unsigned size)
1537 {
1538     AssignedDevice *adev = opaque;
1539     uint64_t val;
1540
1541     memcpy(&val, (void *)((uint8_t *)adev->msix_table + addr), size);
1542
1543     return val;
1544 }
1545
1546 static void assigned_dev_msix_mmio_write(void *opaque, hwaddr addr,
1547                                          uint64_t val, unsigned size)
1548 {
1549     AssignedDevice *adev = opaque;
1550     PCIDevice *pdev = &adev->dev;
1551     uint16_t ctrl;
1552     MSIXTableEntry orig;
1553     int i = addr >> 4;
1554
1555     if (i >= adev->msix_max) {
1556         return; /* Drop write */
1557     }
1558
1559     ctrl = pci_get_word(pdev->config + pdev->msix_cap + PCI_MSIX_FLAGS);
1560
1561     DEBUG("write to MSI-X table offset 0x%lx, val 0x%lx\n", addr, val);
1562
1563     if (ctrl & PCI_MSIX_FLAGS_ENABLE) {
1564         orig = adev->msix_table[i];
1565     }
1566
1567     memcpy((uint8_t *)adev->msix_table + addr, &val, size);
1568
1569     if (ctrl & PCI_MSIX_FLAGS_ENABLE) {
1570         MSIXTableEntry *entry = &adev->msix_table[i];
1571
1572         if (!assigned_dev_msix_masked(&orig) &&
1573             assigned_dev_msix_masked(entry)) {
1574             /*
1575              * Vector masked, disable it
1576              *
1577              * XXX It's not clear if we can or should actually attempt
1578              * to mask or disable the interrupt.  KVM doesn't have
1579              * support for pending bits and kvm_assign_set_msix_entry
1580              * doesn't modify the device hardware mask.  Interrupts
1581              * while masked are simply not injected to the guest, so
1582              * are lost.  Can we get away with always injecting an
1583              * interrupt on unmask?
1584              */
1585         } else if (assigned_dev_msix_masked(&orig) &&
1586                    !assigned_dev_msix_masked(entry)) {
1587             /* Vector unmasked */
1588             if (i >= adev->msi_virq_nr || adev->msi_virq[i] < 0) {
1589                 /* Previously unassigned vector, start from scratch */
1590                 assigned_dev_update_msix(pdev);
1591                 return;
1592             } else {
1593                 /* Update an existing, previously masked vector */
1594                 MSIMessage msg;
1595                 int ret;
1596
1597                 msg.address = entry->addr_lo |
1598                     ((uint64_t)entry->addr_hi << 32);
1599                 msg.data = entry->data;
1600
1601                 ret = kvm_irqchip_update_msi_route(kvm_state,
1602                                                    adev->msi_virq[i], msg);
1603                 if (ret) {
1604                     error_report("Error updating irq routing entry (%d)", ret);
1605                 }
1606             }
1607         }
1608     }
1609 }
1610
1611 static const MemoryRegionOps assigned_dev_msix_mmio_ops = {
1612     .read = assigned_dev_msix_mmio_read,
1613     .write = assigned_dev_msix_mmio_write,
1614     .endianness = DEVICE_NATIVE_ENDIAN,
1615     .valid = {
1616         .min_access_size = 4,
1617         .max_access_size = 8,
1618     },
1619     .impl = {
1620         .min_access_size = 4,
1621         .max_access_size = 8,
1622     },
1623 };
1624
1625 static void assigned_dev_msix_reset(AssignedDevice *dev)
1626 {
1627     MSIXTableEntry *entry;
1628     int i;
1629
1630     if (!dev->msix_table) {
1631         return;
1632     }
1633
1634     memset(dev->msix_table, 0, MSIX_PAGE_SIZE);
1635
1636     for (i = 0, entry = dev->msix_table; i < dev->msix_max; i++, entry++) {
1637         entry->ctrl = cpu_to_le32(0x1); /* Masked */
1638     }
1639 }
1640
1641 static int assigned_dev_register_msix_mmio(AssignedDevice *dev)
1642 {
1643     dev->msix_table = mmap(NULL, MSIX_PAGE_SIZE, PROT_READ|PROT_WRITE,
1644                            MAP_ANONYMOUS|MAP_PRIVATE, 0, 0);
1645     if (dev->msix_table == MAP_FAILED) {
1646         error_report("fail allocate msix_table! %s", strerror(errno));
1647         return -EFAULT;
1648     }
1649
1650     assigned_dev_msix_reset(dev);
1651
1652     memory_region_init_io(&dev->mmio, &assigned_dev_msix_mmio_ops, dev,
1653                           "assigned-dev-msix", MSIX_PAGE_SIZE);
1654     return 0;
1655 }
1656
1657 static void assigned_dev_unregister_msix_mmio(AssignedDevice *dev)
1658 {
1659     if (!dev->msix_table) {
1660         return;
1661     }
1662
1663     memory_region_destroy(&dev->mmio);
1664
1665     if (munmap(dev->msix_table, MSIX_PAGE_SIZE) == -1) {
1666         error_report("error unmapping msix_table! %s", strerror(errno));
1667     }
1668     dev->msix_table = NULL;
1669 }
1670
1671 static const VMStateDescription vmstate_assigned_device = {
1672     .name = "pci-assign",
1673     .unmigratable = 1,
1674 };
1675
1676 static void reset_assigned_device(DeviceState *dev)
1677 {
1678     PCIDevice *pci_dev = DO_UPCAST(PCIDevice, qdev, dev);
1679     AssignedDevice *adev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1680     char reset_file[64];
1681     const char reset[] = "1";
1682     int fd, ret;
1683
1684     /*
1685      * If a guest is reset without being shutdown, MSI/MSI-X can still
1686      * be running.  We want to return the device to a known state on
1687      * reset, so disable those here.  We especially do not want MSI-X
1688      * enabled since it lives in MMIO space, which is about to get
1689      * disabled.
1690      */
1691     if (adev->assigned_irq_type == ASSIGNED_IRQ_MSIX) {
1692         uint16_t ctrl = pci_get_word(pci_dev->config +
1693                                      pci_dev->msix_cap + PCI_MSIX_FLAGS);
1694
1695         pci_set_word(pci_dev->config + pci_dev->msix_cap + PCI_MSIX_FLAGS,
1696                      ctrl & ~PCI_MSIX_FLAGS_ENABLE);
1697         assigned_dev_update_msix(pci_dev);
1698     } else if (adev->assigned_irq_type == ASSIGNED_IRQ_MSI) {
1699         uint8_t ctrl = pci_get_byte(pci_dev->config +
1700                                     pci_dev->msi_cap + PCI_MSI_FLAGS);
1701
1702         pci_set_byte(pci_dev->config + pci_dev->msi_cap + PCI_MSI_FLAGS,
1703                      ctrl & ~PCI_MSI_FLAGS_ENABLE);
1704         assigned_dev_update_msi(pci_dev);
1705     }
1706
1707     snprintf(reset_file, sizeof(reset_file),
1708              "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/reset",
1709              adev->host.domain, adev->host.bus, adev->host.slot,
1710              adev->host.function);
1711
1712     /*
1713      * Issue a device reset via pci-sysfs.  Note that we use write(2) here
1714      * and ignore the return value because some kernels have a bug that
1715      * returns 0 rather than bytes written on success, sending us into an
1716      * infinite retry loop using other write mechanisms.
1717      */
1718     fd = open(reset_file, O_WRONLY);
1719     if (fd != -1) {
1720         ret = write(fd, reset, strlen(reset));
1721         (void)ret;
1722         close(fd);
1723     }
1724
1725     /*
1726      * When a 0 is written to the bus master register, the device is logically
1727      * disconnected from the PCI bus. This avoids further DMA transfers.
1728      */
1729     assigned_dev_pci_write_config(pci_dev, PCI_COMMAND, 0, 1);
1730 }
1731
1732 static int assigned_initfn(struct PCIDevice *pci_dev)
1733 {
1734     AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1735     uint8_t e_intx;
1736     int r;
1737
1738     if (!kvm_enabled()) {
1739         error_report("pci-assign: error: requires KVM support");
1740         return -1;
1741     }
1742
1743     if (!dev->host.domain && !dev->host.bus && !dev->host.slot &&
1744         !dev->host.function) {
1745         error_report("pci-assign: error: no host device specified");
1746         return -1;
1747     }
1748
1749     /*
1750      * Set up basic config space access control. Will be further refined during
1751      * device initialization.
1752      */
1753     assigned_dev_emulate_config_read(dev, 0, PCI_CONFIG_SPACE_SIZE);
1754     assigned_dev_direct_config_read(dev, PCI_STATUS, 2);
1755     assigned_dev_direct_config_read(dev, PCI_REVISION_ID, 1);
1756     assigned_dev_direct_config_read(dev, PCI_CLASS_PROG, 3);
1757     assigned_dev_direct_config_read(dev, PCI_CACHE_LINE_SIZE, 1);
1758     assigned_dev_direct_config_read(dev, PCI_LATENCY_TIMER, 1);
1759     assigned_dev_direct_config_read(dev, PCI_BIST, 1);
1760     assigned_dev_direct_config_read(dev, PCI_CARDBUS_CIS, 4);
1761     assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_VENDOR_ID, 2);
1762     assigned_dev_direct_config_read(dev, PCI_SUBSYSTEM_ID, 2);
1763     assigned_dev_direct_config_read(dev, PCI_CAPABILITY_LIST + 1, 7);
1764     assigned_dev_direct_config_read(dev, PCI_MIN_GNT, 1);
1765     assigned_dev_direct_config_read(dev, PCI_MAX_LAT, 1);
1766     memcpy(dev->emulate_config_write, dev->emulate_config_read,
1767            sizeof(dev->emulate_config_read));
1768
1769     if (get_real_device(dev, dev->host.domain, dev->host.bus,
1770                         dev->host.slot, dev->host.function)) {
1771         error_report("pci-assign: Error: Couldn't get real device (%s)!",
1772                      dev->dev.qdev.id);
1773         goto out;
1774     }
1775
1776     if (assigned_device_pci_cap_init(pci_dev) < 0) {
1777         goto out;
1778     }
1779
1780     /* intercept MSI-X entry page in the MMIO */
1781     if (dev->cap.available & ASSIGNED_DEVICE_CAP_MSIX) {
1782         if (assigned_dev_register_msix_mmio(dev)) {
1783             goto out;
1784         }
1785     }
1786
1787     /* handle real device's MMIO/PIO BARs */
1788     if (assigned_dev_register_regions(dev->real_device.regions,
1789                                       dev->real_device.region_number,
1790                                       dev)) {
1791         goto out;
1792     }
1793
1794     /* handle interrupt routing */
1795     e_intx = dev->dev.config[PCI_INTERRUPT_PIN] - 1;
1796     dev->intpin = e_intx;
1797     dev->intx_route.mode = PCI_INTX_DISABLED;
1798     dev->intx_route.irq = -1;
1799
1800     /* assign device to guest */
1801     r = assign_device(dev);
1802     if (r < 0) {
1803         goto out;
1804     }
1805
1806     /* assign legacy INTx to the device */
1807     r = assign_intx(dev);
1808     if (r < 0) {
1809         goto assigned_out;
1810     }
1811
1812     assigned_dev_load_option_rom(dev);
1813
1814     add_boot_device_path(dev->bootindex, &pci_dev->qdev, NULL);
1815
1816     return 0;
1817
1818 assigned_out:
1819     deassign_device(dev);
1820 out:
1821     free_assigned_device(dev);
1822     return -1;
1823 }
1824
1825 static void assigned_exitfn(struct PCIDevice *pci_dev)
1826 {
1827     AssignedDevice *dev = DO_UPCAST(AssignedDevice, dev, pci_dev);
1828
1829     deassign_device(dev);
1830     free_assigned_device(dev);
1831 }
1832
1833 static Property assigned_dev_properties[] = {
1834     DEFINE_PROP_PCI_HOST_DEVADDR("host", AssignedDevice, host),
1835     DEFINE_PROP_BIT("prefer_msi", AssignedDevice, features,
1836                     ASSIGNED_DEVICE_PREFER_MSI_BIT, false),
1837     DEFINE_PROP_BIT("share_intx", AssignedDevice, features,
1838                     ASSIGNED_DEVICE_SHARE_INTX_BIT, true),
1839     DEFINE_PROP_INT32("bootindex", AssignedDevice, bootindex, -1),
1840     DEFINE_PROP_STRING("configfd", AssignedDevice, configfd_name),
1841     DEFINE_PROP_END_OF_LIST(),
1842 };
1843
1844 static void assign_class_init(ObjectClass *klass, void *data)
1845 {
1846     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1847     DeviceClass *dc = DEVICE_CLASS(klass);
1848
1849     k->init         = assigned_initfn;
1850     k->exit         = assigned_exitfn;
1851     k->config_read  = assigned_dev_pci_read_config;
1852     k->config_write = assigned_dev_pci_write_config;
1853     dc->props       = assigned_dev_properties;
1854     dc->vmsd        = &vmstate_assigned_device;
1855     dc->reset       = reset_assigned_device;
1856     dc->desc        = "KVM-based PCI passthrough";
1857 }
1858
1859 static const TypeInfo assign_info = {
1860     .name               = "kvm-pci-assign",
1861     .parent             = TYPE_PCI_DEVICE,
1862     .instance_size      = sizeof(AssignedDevice),
1863     .class_init         = assign_class_init,
1864 };
1865
1866 static void assign_register_types(void)
1867 {
1868     type_register_static(&assign_info);
1869 }
1870
1871 type_init(assign_register_types)
1872
1873 /*
1874  * Scan the assigned devices for the devices that have an option ROM, and then
1875  * load the corresponding ROM data to RAM. If an error occurs while loading an
1876  * option ROM, we just ignore that option ROM and continue with the next one.
1877  */
1878 static void assigned_dev_load_option_rom(AssignedDevice *dev)
1879 {
1880     char name[32], rom_file[64];
1881     FILE *fp;
1882     uint8_t val;
1883     struct stat st;
1884     void *ptr;
1885
1886     /* If loading ROM from file, pci handles it */
1887     if (dev->dev.romfile || !dev->dev.rom_bar) {
1888         return;
1889     }
1890
1891     snprintf(rom_file, sizeof(rom_file),
1892              "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/rom",
1893              dev->host.domain, dev->host.bus, dev->host.slot,
1894              dev->host.function);
1895
1896     if (stat(rom_file, &st)) {
1897         return;
1898     }
1899
1900     if (access(rom_file, F_OK)) {
1901         error_report("pci-assign: Insufficient privileges for %s", rom_file);
1902         return;
1903     }
1904
1905     /* Write "1" to the ROM file to enable it */
1906     fp = fopen(rom_file, "r+");
1907     if (fp == NULL) {
1908         return;
1909     }
1910     val = 1;
1911     if (fwrite(&val, 1, 1, fp) != 1) {
1912         goto close_rom;
1913     }
1914     fseek(fp, 0, SEEK_SET);
1915
1916     snprintf(name, sizeof(name), "%s.rom",
1917             object_get_typename(OBJECT(dev)));
1918     memory_region_init_ram(&dev->dev.rom, name, st.st_size);
1919     vmstate_register_ram(&dev->dev.rom, &dev->dev.qdev);
1920     ptr = memory_region_get_ram_ptr(&dev->dev.rom);
1921     memset(ptr, 0xff, st.st_size);
1922
1923     if (!fread(ptr, 1, st.st_size, fp)) {
1924         error_report("pci-assign: Cannot read from host %s", rom_file);
1925         error_printf("Device option ROM contents are probably invalid "
1926                      "(check dmesg).\nSkip option ROM probe with rombar=0, "
1927                      "or load from file with romfile=\n");
1928         memory_region_destroy(&dev->dev.rom);
1929         goto close_rom;
1930     }
1931
1932     pci_register_bar(&dev->dev, PCI_ROM_SLOT, 0, &dev->dev.rom);
1933     dev->dev.has_rom = true;
1934 close_rom:
1935     /* Write "0" to disable ROM */
1936     fseek(fp, 0, SEEK_SET);
1937     val = 0;
1938     if (!fwrite(&val, 1, 1, fp)) {
1939         DEBUG("%s\n", "Failed to disable pci-sysfs rom file");
1940     }
1941     fclose(fp);
1942 }
This page took 0.138094 seconds and 4 git commands to generate.