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