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