xref: /openbmc/qemu/hw/virtio/virtio-pci.c (revision 7a5951f651ad5f158631a826070b24631e733763)
1 /*
2  * Virtio PCI Bindings
3  *
4  * Copyright IBM, Corp. 2007
5  * Copyright (c) 2009 CodeSourcery
6  *
7  * Authors:
8  *  Anthony Liguori   <aliguori@us.ibm.com>
9  *  Paul Brook        <paul@codesourcery.com>
10  *
11  * This work is licensed under the terms of the GNU GPL, version 2.  See
12  * the COPYING file in the top-level directory.
13  *
14  * Contributions after 2012-01-13 are licensed under the terms of the
15  * GNU GPL, version 2 or (at your option) any later version.
16  */
17 
18 #include "qemu/osdep.h"
19 
20 #include "exec/memop.h"
21 #include "standard-headers/linux/virtio_pci.h"
22 #include "standard-headers/linux/virtio_ids.h"
23 #include "hw/boards.h"
24 #include "hw/virtio/virtio.h"
25 #include "migration/qemu-file-types.h"
26 #include "hw/pci/pci.h"
27 #include "hw/pci/pci_bus.h"
28 #include "hw/qdev-properties.h"
29 #include "qapi/error.h"
30 #include "qemu/error-report.h"
31 #include "qemu/log.h"
32 #include "qemu/module.h"
33 #include "hw/pci/msi.h"
34 #include "hw/pci/msix.h"
35 #include "hw/loader.h"
36 #include "sysemu/kvm.h"
37 #include "hw/virtio/virtio-pci.h"
38 #include "qemu/range.h"
39 #include "hw/virtio/virtio-bus.h"
40 #include "qapi/visitor.h"
41 #include "sysemu/replay.h"
42 #include "trace.h"
43 
44 #define VIRTIO_PCI_REGION_SIZE(dev)     VIRTIO_PCI_CONFIG_OFF(msix_present(dev))
45 
46 #undef VIRTIO_PCI_CONFIG
47 
48 /* The remaining space is defined by each driver as the per-driver
49  * configuration space */
50 #define VIRTIO_PCI_CONFIG_SIZE(dev)     VIRTIO_PCI_CONFIG_OFF(msix_enabled(dev))
51 
52 static void virtio_pci_bus_new(VirtioBusState *bus, size_t bus_size,
53                                VirtIOPCIProxy *dev);
54 static void virtio_pci_reset(DeviceState *qdev);
55 
56 /* virtio device */
57 /* DeviceState to VirtIOPCIProxy. For use off data-path. TODO: use QOM. */
58 static inline VirtIOPCIProxy *to_virtio_pci_proxy(DeviceState *d)
59 {
60     return container_of(d, VirtIOPCIProxy, pci_dev.qdev);
61 }
62 
63 /* DeviceState to VirtIOPCIProxy. Note: used on datapath,
64  * be careful and test performance if you change this.
65  */
66 static inline VirtIOPCIProxy *to_virtio_pci_proxy_fast(DeviceState *d)
67 {
68     return container_of(d, VirtIOPCIProxy, pci_dev.qdev);
69 }
70 
71 static void virtio_pci_notify(DeviceState *d, uint16_t vector)
72 {
73     VirtIOPCIProxy *proxy = to_virtio_pci_proxy_fast(d);
74 
75     if (msix_enabled(&proxy->pci_dev)) {
76         if (vector != VIRTIO_NO_VECTOR) {
77             msix_notify(&proxy->pci_dev, vector);
78         }
79     } else {
80         VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
81         pci_set_irq(&proxy->pci_dev, qatomic_read(&vdev->isr) & 1);
82     }
83 }
84 
85 static void virtio_pci_save_config(DeviceState *d, QEMUFile *f)
86 {
87     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
88     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
89 
90     pci_device_save(&proxy->pci_dev, f);
91     msix_save(&proxy->pci_dev, f);
92     if (msix_present(&proxy->pci_dev))
93         qemu_put_be16(f, vdev->config_vector);
94 }
95 
96 static const VMStateDescription vmstate_virtio_pci_modern_queue_state = {
97     .name = "virtio_pci/modern_queue_state",
98     .version_id = 1,
99     .minimum_version_id = 1,
100     .fields = (VMStateField[]) {
101         VMSTATE_UINT16(num, VirtIOPCIQueue),
102         VMSTATE_UNUSED(1), /* enabled was stored as be16 */
103         VMSTATE_BOOL(enabled, VirtIOPCIQueue),
104         VMSTATE_UINT32_ARRAY(desc, VirtIOPCIQueue, 2),
105         VMSTATE_UINT32_ARRAY(avail, VirtIOPCIQueue, 2),
106         VMSTATE_UINT32_ARRAY(used, VirtIOPCIQueue, 2),
107         VMSTATE_END_OF_LIST()
108     }
109 };
110 
111 static bool virtio_pci_modern_state_needed(void *opaque)
112 {
113     VirtIOPCIProxy *proxy = opaque;
114 
115     return virtio_pci_modern(proxy);
116 }
117 
118 static const VMStateDescription vmstate_virtio_pci_modern_state_sub = {
119     .name = "virtio_pci/modern_state",
120     .version_id = 1,
121     .minimum_version_id = 1,
122     .needed = &virtio_pci_modern_state_needed,
123     .fields = (VMStateField[]) {
124         VMSTATE_UINT32(dfselect, VirtIOPCIProxy),
125         VMSTATE_UINT32(gfselect, VirtIOPCIProxy),
126         VMSTATE_UINT32_ARRAY(guest_features, VirtIOPCIProxy, 2),
127         VMSTATE_STRUCT_ARRAY(vqs, VirtIOPCIProxy, VIRTIO_QUEUE_MAX, 0,
128                              vmstate_virtio_pci_modern_queue_state,
129                              VirtIOPCIQueue),
130         VMSTATE_END_OF_LIST()
131     }
132 };
133 
134 static const VMStateDescription vmstate_virtio_pci = {
135     .name = "virtio_pci",
136     .version_id = 1,
137     .minimum_version_id = 1,
138     .fields = (VMStateField[]) {
139         VMSTATE_END_OF_LIST()
140     },
141     .subsections = (const VMStateDescription*[]) {
142         &vmstate_virtio_pci_modern_state_sub,
143         NULL
144     }
145 };
146 
147 static bool virtio_pci_has_extra_state(DeviceState *d)
148 {
149     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
150 
151     return proxy->flags & VIRTIO_PCI_FLAG_MIGRATE_EXTRA;
152 }
153 
154 static void virtio_pci_save_extra_state(DeviceState *d, QEMUFile *f)
155 {
156     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
157 
158     vmstate_save_state(f, &vmstate_virtio_pci, proxy, NULL);
159 }
160 
161 static int virtio_pci_load_extra_state(DeviceState *d, QEMUFile *f)
162 {
163     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
164 
165     return vmstate_load_state(f, &vmstate_virtio_pci, proxy, 1);
166 }
167 
168 static void virtio_pci_save_queue(DeviceState *d, int n, QEMUFile *f)
169 {
170     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
171     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
172 
173     if (msix_present(&proxy->pci_dev))
174         qemu_put_be16(f, virtio_queue_vector(vdev, n));
175 }
176 
177 static int virtio_pci_load_config(DeviceState *d, QEMUFile *f)
178 {
179     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
180     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
181     uint16_t vector;
182 
183     int ret;
184     ret = pci_device_load(&proxy->pci_dev, f);
185     if (ret) {
186         return ret;
187     }
188     msix_unuse_all_vectors(&proxy->pci_dev);
189     msix_load(&proxy->pci_dev, f);
190     if (msix_present(&proxy->pci_dev)) {
191         qemu_get_be16s(f, &vector);
192 
193         if (vector != VIRTIO_NO_VECTOR && vector >= proxy->nvectors) {
194             return -EINVAL;
195         }
196     } else {
197         vector = VIRTIO_NO_VECTOR;
198     }
199     vdev->config_vector = vector;
200     if (vector != VIRTIO_NO_VECTOR) {
201         msix_vector_use(&proxy->pci_dev, vector);
202     }
203     return 0;
204 }
205 
206 static int virtio_pci_load_queue(DeviceState *d, int n, QEMUFile *f)
207 {
208     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
209     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
210 
211     uint16_t vector;
212     if (msix_present(&proxy->pci_dev)) {
213         qemu_get_be16s(f, &vector);
214         if (vector != VIRTIO_NO_VECTOR && vector >= proxy->nvectors) {
215             return -EINVAL;
216         }
217     } else {
218         vector = VIRTIO_NO_VECTOR;
219     }
220     virtio_queue_set_vector(vdev, n, vector);
221     if (vector != VIRTIO_NO_VECTOR) {
222         msix_vector_use(&proxy->pci_dev, vector);
223     }
224 
225     return 0;
226 }
227 
228 typedef struct VirtIOPCIIDInfo {
229     /* virtio id */
230     uint16_t vdev_id;
231     /* pci device id for the transitional device */
232     uint16_t trans_devid;
233     uint16_t class_id;
234 } VirtIOPCIIDInfo;
235 
236 static const VirtIOPCIIDInfo virtio_pci_id_info[] = {
237     {
238         .vdev_id = VIRTIO_ID_CRYPTO,
239         .class_id = PCI_CLASS_OTHERS,
240     }, {
241         .vdev_id = VIRTIO_ID_FS,
242         .class_id = PCI_CLASS_STORAGE_OTHER,
243     }, {
244         .vdev_id = VIRTIO_ID_NET,
245         .trans_devid = PCI_DEVICE_ID_VIRTIO_NET,
246         .class_id = PCI_CLASS_NETWORK_ETHERNET,
247     }, {
248         .vdev_id = VIRTIO_ID_BLOCK,
249         .trans_devid = PCI_DEVICE_ID_VIRTIO_BLOCK,
250         .class_id = PCI_CLASS_STORAGE_SCSI,
251     }, {
252         .vdev_id = VIRTIO_ID_CONSOLE,
253         .trans_devid = PCI_DEVICE_ID_VIRTIO_CONSOLE,
254         .class_id = PCI_CLASS_COMMUNICATION_OTHER,
255     }, {
256         .vdev_id = VIRTIO_ID_SCSI,
257         .trans_devid = PCI_DEVICE_ID_VIRTIO_SCSI,
258         .class_id = PCI_CLASS_STORAGE_SCSI
259     }, {
260         .vdev_id = VIRTIO_ID_9P,
261         .trans_devid = PCI_DEVICE_ID_VIRTIO_9P,
262         .class_id = PCI_BASE_CLASS_NETWORK,
263     }, {
264         .vdev_id = VIRTIO_ID_BALLOON,
265         .trans_devid = PCI_DEVICE_ID_VIRTIO_BALLOON,
266         .class_id = PCI_CLASS_OTHERS,
267     }, {
268         .vdev_id = VIRTIO_ID_RNG,
269         .trans_devid = PCI_DEVICE_ID_VIRTIO_RNG,
270         .class_id = PCI_CLASS_OTHERS,
271     },
272 };
273 
274 static const VirtIOPCIIDInfo *virtio_pci_get_id_info(uint16_t vdev_id)
275 {
276     const VirtIOPCIIDInfo *info = NULL;
277     int i;
278 
279     for (i = 0; i < ARRAY_SIZE(virtio_pci_id_info); i++) {
280         if (virtio_pci_id_info[i].vdev_id == vdev_id) {
281             info = &virtio_pci_id_info[i];
282             break;
283         }
284     }
285 
286     if (!info) {
287         /* The device id is invalid or not added to the id_info yet. */
288         error_report("Invalid virtio device(id %u)", vdev_id);
289         abort();
290     }
291 
292     return info;
293 }
294 
295 /*
296  * Get the Transitional Device ID for the specific device, return
297  * zero if the device is non-transitional.
298  */
299 uint16_t virtio_pci_get_trans_devid(uint16_t device_id)
300 {
301     return virtio_pci_get_id_info(device_id)->trans_devid;
302 }
303 
304 /*
305  * Get the Class ID for the specific device.
306  */
307 uint16_t virtio_pci_get_class_id(uint16_t device_id)
308 {
309     return virtio_pci_get_id_info(device_id)->class_id;
310 }
311 
312 static bool virtio_pci_ioeventfd_enabled(DeviceState *d)
313 {
314     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
315 
316     return (proxy->flags & VIRTIO_PCI_FLAG_USE_IOEVENTFD) != 0;
317 }
318 
319 #define QEMU_VIRTIO_PCI_QUEUE_MEM_MULT 0x1000
320 
321 static inline int virtio_pci_queue_mem_mult(struct VirtIOPCIProxy *proxy)
322 {
323     return (proxy->flags & VIRTIO_PCI_FLAG_PAGE_PER_VQ) ?
324         QEMU_VIRTIO_PCI_QUEUE_MEM_MULT : 4;
325 }
326 
327 static int virtio_pci_ioeventfd_assign(DeviceState *d, EventNotifier *notifier,
328                                        int n, bool assign)
329 {
330     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
331     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
332     VirtQueue *vq = virtio_get_queue(vdev, n);
333     bool legacy = virtio_pci_legacy(proxy);
334     bool modern = virtio_pci_modern(proxy);
335     bool fast_mmio = kvm_ioeventfd_any_length_enabled();
336     bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;
337     MemoryRegion *modern_mr = &proxy->notify.mr;
338     MemoryRegion *modern_notify_mr = &proxy->notify_pio.mr;
339     MemoryRegion *legacy_mr = &proxy->bar;
340     hwaddr modern_addr = virtio_pci_queue_mem_mult(proxy) *
341                          virtio_get_queue_index(vq);
342     hwaddr legacy_addr = VIRTIO_PCI_QUEUE_NOTIFY;
343 
344     if (assign) {
345         if (modern) {
346             if (fast_mmio) {
347                 memory_region_add_eventfd(modern_mr, modern_addr, 0,
348                                           false, n, notifier);
349             } else {
350                 memory_region_add_eventfd(modern_mr, modern_addr, 2,
351                                           false, n, notifier);
352             }
353             if (modern_pio) {
354                 memory_region_add_eventfd(modern_notify_mr, 0, 2,
355                                               true, n, notifier);
356             }
357         }
358         if (legacy) {
359             memory_region_add_eventfd(legacy_mr, legacy_addr, 2,
360                                       true, n, notifier);
361         }
362     } else {
363         if (modern) {
364             if (fast_mmio) {
365                 memory_region_del_eventfd(modern_mr, modern_addr, 0,
366                                           false, n, notifier);
367             } else {
368                 memory_region_del_eventfd(modern_mr, modern_addr, 2,
369                                           false, n, notifier);
370             }
371             if (modern_pio) {
372                 memory_region_del_eventfd(modern_notify_mr, 0, 2,
373                                           true, n, notifier);
374             }
375         }
376         if (legacy) {
377             memory_region_del_eventfd(legacy_mr, legacy_addr, 2,
378                                       true, n, notifier);
379         }
380     }
381     return 0;
382 }
383 
384 static void virtio_pci_start_ioeventfd(VirtIOPCIProxy *proxy)
385 {
386     virtio_bus_start_ioeventfd(&proxy->bus);
387 }
388 
389 static void virtio_pci_stop_ioeventfd(VirtIOPCIProxy *proxy)
390 {
391     virtio_bus_stop_ioeventfd(&proxy->bus);
392 }
393 
394 static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val)
395 {
396     VirtIOPCIProxy *proxy = opaque;
397     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
398     uint16_t vector;
399     hwaddr pa;
400 
401     switch (addr) {
402     case VIRTIO_PCI_GUEST_FEATURES:
403         /* Guest does not negotiate properly?  We have to assume nothing. */
404         if (val & (1 << VIRTIO_F_BAD_FEATURE)) {
405             val = virtio_bus_get_vdev_bad_features(&proxy->bus);
406         }
407         virtio_set_features(vdev, val);
408         break;
409     case VIRTIO_PCI_QUEUE_PFN:
410         pa = (hwaddr)val << VIRTIO_PCI_QUEUE_ADDR_SHIFT;
411         if (pa == 0) {
412             virtio_pci_reset(DEVICE(proxy));
413         }
414         else
415             virtio_queue_set_addr(vdev, vdev->queue_sel, pa);
416         break;
417     case VIRTIO_PCI_QUEUE_SEL:
418         if (val < VIRTIO_QUEUE_MAX)
419             vdev->queue_sel = val;
420         break;
421     case VIRTIO_PCI_QUEUE_NOTIFY:
422         if (val < VIRTIO_QUEUE_MAX) {
423             virtio_queue_notify(vdev, val);
424         }
425         break;
426     case VIRTIO_PCI_STATUS:
427         if (!(val & VIRTIO_CONFIG_S_DRIVER_OK)) {
428             virtio_pci_stop_ioeventfd(proxy);
429         }
430 
431         virtio_set_status(vdev, val & 0xFF);
432 
433         if (val & VIRTIO_CONFIG_S_DRIVER_OK) {
434             virtio_pci_start_ioeventfd(proxy);
435         }
436 
437         if (vdev->status == 0) {
438             virtio_pci_reset(DEVICE(proxy));
439         }
440 
441         /* Linux before 2.6.34 drives the device without enabling
442            the PCI device bus master bit. Enable it automatically
443            for the guest. This is a PCI spec violation but so is
444            initiating DMA with bus master bit clear. */
445         if (val == (VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER)) {
446             pci_default_write_config(&proxy->pci_dev, PCI_COMMAND,
447                                      proxy->pci_dev.config[PCI_COMMAND] |
448                                      PCI_COMMAND_MASTER, 1);
449         }
450         break;
451     case VIRTIO_MSI_CONFIG_VECTOR:
452         if (vdev->config_vector != VIRTIO_NO_VECTOR) {
453             msix_vector_unuse(&proxy->pci_dev, vdev->config_vector);
454         }
455         /* Make it possible for guest to discover an error took place. */
456         if (val < proxy->nvectors) {
457             msix_vector_use(&proxy->pci_dev, val);
458         } else {
459             val = VIRTIO_NO_VECTOR;
460         }
461         vdev->config_vector = val;
462         break;
463     case VIRTIO_MSI_QUEUE_VECTOR:
464         vector = virtio_queue_vector(vdev, vdev->queue_sel);
465         if (vector != VIRTIO_NO_VECTOR) {
466             msix_vector_unuse(&proxy->pci_dev, vector);
467         }
468         /* Make it possible for guest to discover an error took place. */
469         if (val < proxy->nvectors) {
470             msix_vector_use(&proxy->pci_dev, val);
471         } else {
472             val = VIRTIO_NO_VECTOR;
473         }
474         virtio_queue_set_vector(vdev, vdev->queue_sel, val);
475         break;
476     default:
477         qemu_log_mask(LOG_GUEST_ERROR,
478                       "%s: unexpected address 0x%x value 0x%x\n",
479                       __func__, addr, val);
480         break;
481     }
482 }
483 
484 static uint32_t virtio_ioport_read(VirtIOPCIProxy *proxy, uint32_t addr)
485 {
486     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
487     uint32_t ret = 0xFFFFFFFF;
488 
489     switch (addr) {
490     case VIRTIO_PCI_HOST_FEATURES:
491         ret = vdev->host_features;
492         break;
493     case VIRTIO_PCI_GUEST_FEATURES:
494         ret = vdev->guest_features;
495         break;
496     case VIRTIO_PCI_QUEUE_PFN:
497         ret = virtio_queue_get_addr(vdev, vdev->queue_sel)
498               >> VIRTIO_PCI_QUEUE_ADDR_SHIFT;
499         break;
500     case VIRTIO_PCI_QUEUE_NUM:
501         ret = virtio_queue_get_num(vdev, vdev->queue_sel);
502         break;
503     case VIRTIO_PCI_QUEUE_SEL:
504         ret = vdev->queue_sel;
505         break;
506     case VIRTIO_PCI_STATUS:
507         ret = vdev->status;
508         break;
509     case VIRTIO_PCI_ISR:
510         /* reading from the ISR also clears it. */
511         ret = qatomic_xchg(&vdev->isr, 0);
512         pci_irq_deassert(&proxy->pci_dev);
513         break;
514     case VIRTIO_MSI_CONFIG_VECTOR:
515         ret = vdev->config_vector;
516         break;
517     case VIRTIO_MSI_QUEUE_VECTOR:
518         ret = virtio_queue_vector(vdev, vdev->queue_sel);
519         break;
520     default:
521         break;
522     }
523 
524     return ret;
525 }
526 
527 static uint64_t virtio_pci_config_read(void *opaque, hwaddr addr,
528                                        unsigned size)
529 {
530     VirtIOPCIProxy *proxy = opaque;
531     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
532     uint32_t config = VIRTIO_PCI_CONFIG_SIZE(&proxy->pci_dev);
533     uint64_t val = 0;
534 
535     if (vdev == NULL) {
536         return UINT64_MAX;
537     }
538 
539     if (addr < config) {
540         return virtio_ioport_read(proxy, addr);
541     }
542     addr -= config;
543 
544     switch (size) {
545     case 1:
546         val = virtio_config_readb(vdev, addr);
547         break;
548     case 2:
549         val = virtio_config_readw(vdev, addr);
550         if (virtio_is_big_endian(vdev)) {
551             val = bswap16(val);
552         }
553         break;
554     case 4:
555         val = virtio_config_readl(vdev, addr);
556         if (virtio_is_big_endian(vdev)) {
557             val = bswap32(val);
558         }
559         break;
560     }
561     return val;
562 }
563 
564 static void virtio_pci_config_write(void *opaque, hwaddr addr,
565                                     uint64_t val, unsigned size)
566 {
567     VirtIOPCIProxy *proxy = opaque;
568     uint32_t config = VIRTIO_PCI_CONFIG_SIZE(&proxy->pci_dev);
569     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
570 
571     if (vdev == NULL) {
572         return;
573     }
574 
575     if (addr < config) {
576         virtio_ioport_write(proxy, addr, val);
577         return;
578     }
579     addr -= config;
580     /*
581      * Virtio-PCI is odd. Ioports are LE but config space is target native
582      * endian.
583      */
584     switch (size) {
585     case 1:
586         virtio_config_writeb(vdev, addr, val);
587         break;
588     case 2:
589         if (virtio_is_big_endian(vdev)) {
590             val = bswap16(val);
591         }
592         virtio_config_writew(vdev, addr, val);
593         break;
594     case 4:
595         if (virtio_is_big_endian(vdev)) {
596             val = bswap32(val);
597         }
598         virtio_config_writel(vdev, addr, val);
599         break;
600     }
601 }
602 
603 static const MemoryRegionOps virtio_pci_config_ops = {
604     .read = virtio_pci_config_read,
605     .write = virtio_pci_config_write,
606     .impl = {
607         .min_access_size = 1,
608         .max_access_size = 4,
609     },
610     .endianness = DEVICE_LITTLE_ENDIAN,
611 };
612 
613 static MemoryRegion *virtio_address_space_lookup(VirtIOPCIProxy *proxy,
614                                                  hwaddr *off, int len)
615 {
616     int i;
617     VirtIOPCIRegion *reg;
618 
619     for (i = 0; i < ARRAY_SIZE(proxy->regs); ++i) {
620         reg = &proxy->regs[i];
621         if (*off >= reg->offset &&
622             *off + len <= reg->offset + reg->size) {
623             *off -= reg->offset;
624             return &reg->mr;
625         }
626     }
627 
628     return NULL;
629 }
630 
631 /* Below are generic functions to do memcpy from/to an address space,
632  * without byteswaps, with input validation.
633  *
634  * As regular address_space_* APIs all do some kind of byteswap at least for
635  * some host/target combinations, we are forced to explicitly convert to a
636  * known-endianness integer value.
637  * It doesn't really matter which endian format to go through, so the code
638  * below selects the endian that causes the least amount of work on the given
639  * host.
640  *
641  * Note: host pointer must be aligned.
642  */
643 static
644 void virtio_address_space_write(VirtIOPCIProxy *proxy, hwaddr addr,
645                                 const uint8_t *buf, int len)
646 {
647     uint64_t val;
648     MemoryRegion *mr;
649 
650     /* address_space_* APIs assume an aligned address.
651      * As address is under guest control, handle illegal values.
652      */
653     addr &= ~(len - 1);
654 
655     mr = virtio_address_space_lookup(proxy, &addr, len);
656     if (!mr) {
657         return;
658     }
659 
660     /* Make sure caller aligned buf properly */
661     assert(!(((uintptr_t)buf) & (len - 1)));
662 
663     switch (len) {
664     case 1:
665         val = pci_get_byte(buf);
666         break;
667     case 2:
668         val = pci_get_word(buf);
669         break;
670     case 4:
671         val = pci_get_long(buf);
672         break;
673     default:
674         /* As length is under guest control, handle illegal values. */
675         return;
676     }
677     memory_region_dispatch_write(mr, addr, val, size_memop(len) | MO_LE,
678                                  MEMTXATTRS_UNSPECIFIED);
679 }
680 
681 static void
682 virtio_address_space_read(VirtIOPCIProxy *proxy, hwaddr addr,
683                           uint8_t *buf, int len)
684 {
685     uint64_t val;
686     MemoryRegion *mr;
687 
688     /* address_space_* APIs assume an aligned address.
689      * As address is under guest control, handle illegal values.
690      */
691     addr &= ~(len - 1);
692 
693     mr = virtio_address_space_lookup(proxy, &addr, len);
694     if (!mr) {
695         return;
696     }
697 
698     /* Make sure caller aligned buf properly */
699     assert(!(((uintptr_t)buf) & (len - 1)));
700 
701     memory_region_dispatch_read(mr, addr, &val, size_memop(len) | MO_LE,
702                                 MEMTXATTRS_UNSPECIFIED);
703     switch (len) {
704     case 1:
705         pci_set_byte(buf, val);
706         break;
707     case 2:
708         pci_set_word(buf, val);
709         break;
710     case 4:
711         pci_set_long(buf, val);
712         break;
713     default:
714         /* As length is under guest control, handle illegal values. */
715         break;
716     }
717 }
718 
719 static void virtio_write_config(PCIDevice *pci_dev, uint32_t address,
720                                 uint32_t val, int len)
721 {
722     VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev);
723     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
724     struct virtio_pci_cfg_cap *cfg;
725 
726     pci_default_write_config(pci_dev, address, val, len);
727 
728     if (proxy->flags & VIRTIO_PCI_FLAG_INIT_FLR) {
729         pcie_cap_flr_write_config(pci_dev, address, val, len);
730     }
731 
732     if (range_covers_byte(address, len, PCI_COMMAND)) {
733         if (!(pci_dev->config[PCI_COMMAND] & PCI_COMMAND_MASTER)) {
734             virtio_set_disabled(vdev, true);
735             virtio_pci_stop_ioeventfd(proxy);
736             virtio_set_status(vdev, vdev->status & ~VIRTIO_CONFIG_S_DRIVER_OK);
737         } else {
738             virtio_set_disabled(vdev, false);
739         }
740     }
741 
742     if (proxy->config_cap &&
743         ranges_overlap(address, len, proxy->config_cap + offsetof(struct virtio_pci_cfg_cap,
744                                                                   pci_cfg_data),
745                        sizeof cfg->pci_cfg_data)) {
746         uint32_t off;
747         uint32_t len;
748 
749         cfg = (void *)(proxy->pci_dev.config + proxy->config_cap);
750         off = le32_to_cpu(cfg->cap.offset);
751         len = le32_to_cpu(cfg->cap.length);
752 
753         if (len == 1 || len == 2 || len == 4) {
754             assert(len <= sizeof cfg->pci_cfg_data);
755             virtio_address_space_write(proxy, off, cfg->pci_cfg_data, len);
756         }
757     }
758 }
759 
760 static uint32_t virtio_read_config(PCIDevice *pci_dev,
761                                    uint32_t address, int len)
762 {
763     VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev);
764     struct virtio_pci_cfg_cap *cfg;
765 
766     if (proxy->config_cap &&
767         ranges_overlap(address, len, proxy->config_cap + offsetof(struct virtio_pci_cfg_cap,
768                                                                   pci_cfg_data),
769                        sizeof cfg->pci_cfg_data)) {
770         uint32_t off;
771         uint32_t len;
772 
773         cfg = (void *)(proxy->pci_dev.config + proxy->config_cap);
774         off = le32_to_cpu(cfg->cap.offset);
775         len = le32_to_cpu(cfg->cap.length);
776 
777         if (len == 1 || len == 2 || len == 4) {
778             assert(len <= sizeof cfg->pci_cfg_data);
779             virtio_address_space_read(proxy, off, cfg->pci_cfg_data, len);
780         }
781     }
782 
783     return pci_default_read_config(pci_dev, address, len);
784 }
785 
786 static int kvm_virtio_pci_vq_vector_use(VirtIOPCIProxy *proxy,
787                                         unsigned int vector)
788 {
789     VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];
790     int ret;
791 
792     if (irqfd->users == 0) {
793         KVMRouteChange c = kvm_irqchip_begin_route_changes(kvm_state);
794         ret = kvm_irqchip_add_msi_route(&c, vector, &proxy->pci_dev);
795         if (ret < 0) {
796             return ret;
797         }
798         kvm_irqchip_commit_route_changes(&c);
799         irqfd->virq = ret;
800     }
801     irqfd->users++;
802     return 0;
803 }
804 
805 static void kvm_virtio_pci_vq_vector_release(VirtIOPCIProxy *proxy,
806                                              unsigned int vector)
807 {
808     VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];
809     if (--irqfd->users == 0) {
810         kvm_irqchip_release_virq(kvm_state, irqfd->virq);
811     }
812 }
813 
814 static int kvm_virtio_pci_irqfd_use(VirtIOPCIProxy *proxy,
815                                  EventNotifier *n,
816                                  unsigned int vector)
817 {
818     VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];
819     return kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, n, NULL, irqfd->virq);
820 }
821 
822 static void kvm_virtio_pci_irqfd_release(VirtIOPCIProxy *proxy,
823                                       EventNotifier *n ,
824                                       unsigned int vector)
825 {
826     VirtIOIRQFD *irqfd = &proxy->vector_irqfd[vector];
827     int ret;
828 
829     ret = kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, n, irqfd->virq);
830     assert(ret == 0);
831 }
832 static int virtio_pci_get_notifier(VirtIOPCIProxy *proxy, int queue_no,
833                                       EventNotifier **n, unsigned int *vector)
834 {
835     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
836     VirtQueue *vq;
837 
838     if (queue_no == VIRTIO_CONFIG_IRQ_IDX) {
839         *n = virtio_config_get_guest_notifier(vdev);
840         *vector = vdev->config_vector;
841     } else {
842         if (!virtio_queue_get_num(vdev, queue_no)) {
843             return -1;
844         }
845         *vector = virtio_queue_vector(vdev, queue_no);
846         vq = virtio_get_queue(vdev, queue_no);
847         *n = virtio_queue_get_guest_notifier(vq);
848     }
849     return 0;
850 }
851 
852 static int kvm_virtio_pci_vector_use_one(VirtIOPCIProxy *proxy, int queue_no)
853 {
854     unsigned int vector;
855     int ret;
856     EventNotifier *n;
857     PCIDevice *dev = &proxy->pci_dev;
858     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
859     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
860 
861     ret = virtio_pci_get_notifier(proxy, queue_no, &n, &vector);
862     if (ret < 0) {
863         return ret;
864     }
865     if (vector >= msix_nr_vectors_allocated(dev)) {
866         return 0;
867     }
868     ret = kvm_virtio_pci_vq_vector_use(proxy, vector);
869     if (ret < 0) {
870         goto undo;
871     }
872     /*
873      * If guest supports masking, set up irqfd now.
874      * Otherwise, delay until unmasked in the frontend.
875      */
876     if (vdev->use_guest_notifier_mask && k->guest_notifier_mask) {
877         ret = kvm_virtio_pci_irqfd_use(proxy, n, vector);
878         if (ret < 0) {
879             kvm_virtio_pci_vq_vector_release(proxy, vector);
880             goto undo;
881         }
882     }
883 
884     return 0;
885 undo:
886 
887     vector = virtio_queue_vector(vdev, queue_no);
888     if (vector >= msix_nr_vectors_allocated(dev)) {
889         return ret;
890     }
891     if (vdev->use_guest_notifier_mask && k->guest_notifier_mask) {
892         ret = virtio_pci_get_notifier(proxy, queue_no, &n, &vector);
893         if (ret < 0) {
894             return ret;
895         }
896         kvm_virtio_pci_irqfd_release(proxy, n, vector);
897     }
898     return ret;
899 }
900 static int kvm_virtio_pci_vector_vq_use(VirtIOPCIProxy *proxy, int nvqs)
901 {
902     int queue_no;
903     int ret = 0;
904     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
905 
906     for (queue_no = 0; queue_no < nvqs; queue_no++) {
907         if (!virtio_queue_get_num(vdev, queue_no)) {
908             return -1;
909         }
910         ret = kvm_virtio_pci_vector_use_one(proxy, queue_no);
911     }
912     return ret;
913 }
914 
915 static int kvm_virtio_pci_vector_config_use(VirtIOPCIProxy *proxy)
916 {
917     return kvm_virtio_pci_vector_use_one(proxy, VIRTIO_CONFIG_IRQ_IDX);
918 }
919 
920 static void kvm_virtio_pci_vector_release_one(VirtIOPCIProxy *proxy,
921                                               int queue_no)
922 {
923     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
924     unsigned int vector;
925     EventNotifier *n;
926     int ret;
927     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
928     PCIDevice *dev = &proxy->pci_dev;
929 
930     ret = virtio_pci_get_notifier(proxy, queue_no, &n, &vector);
931     if (ret < 0) {
932         return;
933     }
934     if (vector >= msix_nr_vectors_allocated(dev)) {
935         return;
936     }
937     if (vdev->use_guest_notifier_mask && k->guest_notifier_mask) {
938         kvm_virtio_pci_irqfd_release(proxy, n, vector);
939     }
940     kvm_virtio_pci_vq_vector_release(proxy, vector);
941 }
942 
943 static void kvm_virtio_pci_vector_vq_release(VirtIOPCIProxy *proxy, int nvqs)
944 {
945     int queue_no;
946     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
947 
948     for (queue_no = 0; queue_no < nvqs; queue_no++) {
949         if (!virtio_queue_get_num(vdev, queue_no)) {
950             break;
951         }
952         kvm_virtio_pci_vector_release_one(proxy, queue_no);
953     }
954 }
955 
956 static void kvm_virtio_pci_vector_config_release(VirtIOPCIProxy *proxy)
957 {
958     kvm_virtio_pci_vector_release_one(proxy, VIRTIO_CONFIG_IRQ_IDX);
959 }
960 
961 static int virtio_pci_one_vector_unmask(VirtIOPCIProxy *proxy,
962                                        unsigned int queue_no,
963                                        unsigned int vector,
964                                        MSIMessage msg,
965                                        EventNotifier *n)
966 {
967     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
968     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
969     VirtIOIRQFD *irqfd;
970     int ret = 0;
971 
972     if (proxy->vector_irqfd) {
973         irqfd = &proxy->vector_irqfd[vector];
974         if (irqfd->msg.data != msg.data || irqfd->msg.address != msg.address) {
975             ret = kvm_irqchip_update_msi_route(kvm_state, irqfd->virq, msg,
976                                                &proxy->pci_dev);
977             if (ret < 0) {
978                 return ret;
979             }
980             kvm_irqchip_commit_routes(kvm_state);
981         }
982     }
983 
984     /* If guest supports masking, irqfd is already setup, unmask it.
985      * Otherwise, set it up now.
986      */
987     if (vdev->use_guest_notifier_mask && k->guest_notifier_mask) {
988         k->guest_notifier_mask(vdev, queue_no, false);
989         /* Test after unmasking to avoid losing events. */
990         if (k->guest_notifier_pending &&
991             k->guest_notifier_pending(vdev, queue_no)) {
992             event_notifier_set(n);
993         }
994     } else {
995         ret = kvm_virtio_pci_irqfd_use(proxy, n, vector);
996     }
997     return ret;
998 }
999 
1000 static void virtio_pci_one_vector_mask(VirtIOPCIProxy *proxy,
1001                                              unsigned int queue_no,
1002                                              unsigned int vector,
1003                                              EventNotifier *n)
1004 {
1005     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1006     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1007 
1008     /* If guest supports masking, keep irqfd but mask it.
1009      * Otherwise, clean it up now.
1010      */
1011     if (vdev->use_guest_notifier_mask && k->guest_notifier_mask) {
1012         k->guest_notifier_mask(vdev, queue_no, true);
1013     } else {
1014         kvm_virtio_pci_irqfd_release(proxy, n, vector);
1015     }
1016 }
1017 
1018 static int virtio_pci_vector_unmask(PCIDevice *dev, unsigned vector,
1019                                     MSIMessage msg)
1020 {
1021     VirtIOPCIProxy *proxy = container_of(dev, VirtIOPCIProxy, pci_dev);
1022     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1023     VirtQueue *vq = virtio_vector_first_queue(vdev, vector);
1024     EventNotifier *n;
1025     int ret, index, unmasked = 0;
1026 
1027     while (vq) {
1028         index = virtio_get_queue_index(vq);
1029         if (!virtio_queue_get_num(vdev, index)) {
1030             break;
1031         }
1032         if (index < proxy->nvqs_with_notifiers) {
1033             n = virtio_queue_get_guest_notifier(vq);
1034             ret = virtio_pci_one_vector_unmask(proxy, index, vector, msg, n);
1035             if (ret < 0) {
1036                 goto undo;
1037             }
1038             ++unmasked;
1039         }
1040         vq = virtio_vector_next_queue(vq);
1041     }
1042     /* unmask config intr */
1043     if (vector == vdev->config_vector) {
1044         n = virtio_config_get_guest_notifier(vdev);
1045         ret = virtio_pci_one_vector_unmask(proxy, VIRTIO_CONFIG_IRQ_IDX, vector,
1046                                            msg, n);
1047         if (ret < 0) {
1048             goto undo_config;
1049         }
1050     }
1051     return 0;
1052 undo_config:
1053     n = virtio_config_get_guest_notifier(vdev);
1054     virtio_pci_one_vector_mask(proxy, VIRTIO_CONFIG_IRQ_IDX, vector, n);
1055 undo:
1056     vq = virtio_vector_first_queue(vdev, vector);
1057     while (vq && unmasked >= 0) {
1058         index = virtio_get_queue_index(vq);
1059         if (index < proxy->nvqs_with_notifiers) {
1060             n = virtio_queue_get_guest_notifier(vq);
1061             virtio_pci_one_vector_mask(proxy, index, vector, n);
1062             --unmasked;
1063         }
1064         vq = virtio_vector_next_queue(vq);
1065     }
1066     return ret;
1067 }
1068 
1069 static void virtio_pci_vector_mask(PCIDevice *dev, unsigned vector)
1070 {
1071     VirtIOPCIProxy *proxy = container_of(dev, VirtIOPCIProxy, pci_dev);
1072     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1073     VirtQueue *vq = virtio_vector_first_queue(vdev, vector);
1074     EventNotifier *n;
1075     int index;
1076 
1077     while (vq) {
1078         index = virtio_get_queue_index(vq);
1079         n = virtio_queue_get_guest_notifier(vq);
1080         if (!virtio_queue_get_num(vdev, index)) {
1081             break;
1082         }
1083         if (index < proxy->nvqs_with_notifiers) {
1084             virtio_pci_one_vector_mask(proxy, index, vector, n);
1085         }
1086         vq = virtio_vector_next_queue(vq);
1087     }
1088 
1089     if (vector == vdev->config_vector) {
1090         n = virtio_config_get_guest_notifier(vdev);
1091         virtio_pci_one_vector_mask(proxy, VIRTIO_CONFIG_IRQ_IDX, vector, n);
1092     }
1093 }
1094 
1095 static void virtio_pci_vector_poll(PCIDevice *dev,
1096                                    unsigned int vector_start,
1097                                    unsigned int vector_end)
1098 {
1099     VirtIOPCIProxy *proxy = container_of(dev, VirtIOPCIProxy, pci_dev);
1100     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1101     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1102     int queue_no;
1103     unsigned int vector;
1104     EventNotifier *notifier;
1105     int ret;
1106 
1107     for (queue_no = 0; queue_no < proxy->nvqs_with_notifiers; queue_no++) {
1108         ret = virtio_pci_get_notifier(proxy, queue_no, &notifier, &vector);
1109         if (ret < 0) {
1110             break;
1111         }
1112         if (vector < vector_start || vector >= vector_end ||
1113             !msix_is_masked(dev, vector)) {
1114             continue;
1115         }
1116         if (k->guest_notifier_pending) {
1117             if (k->guest_notifier_pending(vdev, queue_no)) {
1118                 msix_set_pending(dev, vector);
1119             }
1120         } else if (event_notifier_test_and_clear(notifier)) {
1121             msix_set_pending(dev, vector);
1122         }
1123     }
1124     /* poll the config intr */
1125     ret = virtio_pci_get_notifier(proxy, VIRTIO_CONFIG_IRQ_IDX, &notifier,
1126                                   &vector);
1127     if (ret < 0) {
1128         return;
1129     }
1130     if (vector < vector_start || vector >= vector_end ||
1131         !msix_is_masked(dev, vector)) {
1132         return;
1133     }
1134     if (k->guest_notifier_pending) {
1135         if (k->guest_notifier_pending(vdev, VIRTIO_CONFIG_IRQ_IDX)) {
1136             msix_set_pending(dev, vector);
1137         }
1138     } else if (event_notifier_test_and_clear(notifier)) {
1139         msix_set_pending(dev, vector);
1140     }
1141 }
1142 
1143 void virtio_pci_set_guest_notifier_fd_handler(VirtIODevice *vdev, VirtQueue *vq,
1144                                               int n, bool assign,
1145                                               bool with_irqfd)
1146 {
1147     if (n == VIRTIO_CONFIG_IRQ_IDX) {
1148         virtio_config_set_guest_notifier_fd_handler(vdev, assign, with_irqfd);
1149     } else {
1150         virtio_queue_set_guest_notifier_fd_handler(vq, assign, with_irqfd);
1151     }
1152 }
1153 
1154 static int virtio_pci_set_guest_notifier(DeviceState *d, int n, bool assign,
1155                                          bool with_irqfd)
1156 {
1157     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
1158     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1159     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1160     VirtQueue *vq = NULL;
1161     EventNotifier *notifier = NULL;
1162 
1163     if (n == VIRTIO_CONFIG_IRQ_IDX) {
1164         notifier = virtio_config_get_guest_notifier(vdev);
1165     } else {
1166         vq = virtio_get_queue(vdev, n);
1167         notifier = virtio_queue_get_guest_notifier(vq);
1168     }
1169 
1170     if (assign) {
1171         int r = event_notifier_init(notifier, 0);
1172         if (r < 0) {
1173             return r;
1174         }
1175         virtio_pci_set_guest_notifier_fd_handler(vdev, vq, n, true, with_irqfd);
1176     } else {
1177         virtio_pci_set_guest_notifier_fd_handler(vdev, vq, n, false,
1178                                                  with_irqfd);
1179         event_notifier_cleanup(notifier);
1180     }
1181 
1182     if (!msix_enabled(&proxy->pci_dev) &&
1183         vdev->use_guest_notifier_mask &&
1184         vdc->guest_notifier_mask) {
1185         vdc->guest_notifier_mask(vdev, n, !assign);
1186     }
1187 
1188     return 0;
1189 }
1190 
1191 static bool virtio_pci_query_guest_notifiers(DeviceState *d)
1192 {
1193     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
1194     return msix_enabled(&proxy->pci_dev);
1195 }
1196 
1197 static int virtio_pci_set_guest_notifiers(DeviceState *d, int nvqs, bool assign)
1198 {
1199     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
1200     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1201     VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1202     int r, n;
1203     bool with_irqfd = msix_enabled(&proxy->pci_dev) &&
1204         kvm_msi_via_irqfd_enabled();
1205 
1206     nvqs = MIN(nvqs, VIRTIO_QUEUE_MAX);
1207 
1208     /*
1209      * When deassigning, pass a consistent nvqs value to avoid leaking
1210      * notifiers. But first check we've actually been configured, exit
1211      * early if we haven't.
1212      */
1213     if (!assign && !proxy->nvqs_with_notifiers) {
1214         return 0;
1215     }
1216     assert(assign || nvqs == proxy->nvqs_with_notifiers);
1217 
1218     proxy->nvqs_with_notifiers = nvqs;
1219 
1220     /* Must unset vector notifier while guest notifier is still assigned */
1221     if ((proxy->vector_irqfd ||
1222          (vdev->use_guest_notifier_mask && k->guest_notifier_mask)) &&
1223         !assign) {
1224         msix_unset_vector_notifiers(&proxy->pci_dev);
1225         if (proxy->vector_irqfd) {
1226             kvm_virtio_pci_vector_vq_release(proxy, nvqs);
1227             kvm_virtio_pci_vector_config_release(proxy);
1228             g_free(proxy->vector_irqfd);
1229             proxy->vector_irqfd = NULL;
1230         }
1231     }
1232 
1233     for (n = 0; n < nvqs; n++) {
1234         if (!virtio_queue_get_num(vdev, n)) {
1235             break;
1236         }
1237 
1238         r = virtio_pci_set_guest_notifier(d, n, assign, with_irqfd);
1239         if (r < 0) {
1240             goto assign_error;
1241         }
1242     }
1243     r = virtio_pci_set_guest_notifier(d, VIRTIO_CONFIG_IRQ_IDX, assign,
1244                                       with_irqfd);
1245     if (r < 0) {
1246         goto config_assign_error;
1247     }
1248     /* Must set vector notifier after guest notifier has been assigned */
1249     if ((with_irqfd ||
1250          (vdev->use_guest_notifier_mask && k->guest_notifier_mask)) &&
1251         assign) {
1252         if (with_irqfd) {
1253             proxy->vector_irqfd =
1254                 g_malloc0(sizeof(*proxy->vector_irqfd) *
1255                           msix_nr_vectors_allocated(&proxy->pci_dev));
1256             r = kvm_virtio_pci_vector_vq_use(proxy, nvqs);
1257             if (r < 0) {
1258                 goto config_assign_error;
1259             }
1260             r = kvm_virtio_pci_vector_config_use(proxy);
1261             if (r < 0) {
1262                 goto config_error;
1263             }
1264         }
1265 
1266         r = msix_set_vector_notifiers(&proxy->pci_dev, virtio_pci_vector_unmask,
1267                                       virtio_pci_vector_mask,
1268                                       virtio_pci_vector_poll);
1269         if (r < 0) {
1270             goto notifiers_error;
1271         }
1272     }
1273 
1274     return 0;
1275 
1276 notifiers_error:
1277     if (with_irqfd) {
1278         assert(assign);
1279         kvm_virtio_pci_vector_vq_release(proxy, nvqs);
1280     }
1281 config_error:
1282     if (with_irqfd) {
1283         kvm_virtio_pci_vector_config_release(proxy);
1284     }
1285 config_assign_error:
1286     virtio_pci_set_guest_notifier(d, VIRTIO_CONFIG_IRQ_IDX, !assign,
1287                                   with_irqfd);
1288 assign_error:
1289     /* We get here on assignment failure. Recover by undoing for VQs 0 .. n. */
1290     assert(assign);
1291     while (--n >= 0) {
1292         virtio_pci_set_guest_notifier(d, n, !assign, with_irqfd);
1293     }
1294     return r;
1295 }
1296 
1297 static int virtio_pci_set_host_notifier_mr(DeviceState *d, int n,
1298                                            MemoryRegion *mr, bool assign)
1299 {
1300     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
1301     int offset;
1302 
1303     if (n >= VIRTIO_QUEUE_MAX || !virtio_pci_modern(proxy) ||
1304         virtio_pci_queue_mem_mult(proxy) != memory_region_size(mr)) {
1305         return -1;
1306     }
1307 
1308     if (assign) {
1309         offset = virtio_pci_queue_mem_mult(proxy) * n;
1310         memory_region_add_subregion_overlap(&proxy->notify.mr, offset, mr, 1);
1311     } else {
1312         memory_region_del_subregion(&proxy->notify.mr, mr);
1313     }
1314 
1315     return 0;
1316 }
1317 
1318 static void virtio_pci_vmstate_change(DeviceState *d, bool running)
1319 {
1320     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
1321     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1322 
1323     if (running) {
1324         /* Old QEMU versions did not set bus master enable on status write.
1325          * Detect DRIVER set and enable it.
1326          */
1327         if ((proxy->flags & VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION) &&
1328             (vdev->status & VIRTIO_CONFIG_S_DRIVER) &&
1329             !(proxy->pci_dev.config[PCI_COMMAND] & PCI_COMMAND_MASTER)) {
1330             pci_default_write_config(&proxy->pci_dev, PCI_COMMAND,
1331                                      proxy->pci_dev.config[PCI_COMMAND] |
1332                                      PCI_COMMAND_MASTER, 1);
1333         }
1334         virtio_pci_start_ioeventfd(proxy);
1335     } else {
1336         virtio_pci_stop_ioeventfd(proxy);
1337     }
1338 }
1339 
1340 /*
1341  * virtio-pci: This is the PCIDevice which has a virtio-pci-bus.
1342  */
1343 
1344 static int virtio_pci_query_nvectors(DeviceState *d)
1345 {
1346     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1347 
1348     return proxy->nvectors;
1349 }
1350 
1351 static AddressSpace *virtio_pci_get_dma_as(DeviceState *d)
1352 {
1353     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1354     PCIDevice *dev = &proxy->pci_dev;
1355 
1356     return pci_get_address_space(dev);
1357 }
1358 
1359 static bool virtio_pci_iommu_enabled(DeviceState *d)
1360 {
1361     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1362     PCIDevice *dev = &proxy->pci_dev;
1363     AddressSpace *dma_as = pci_device_iommu_address_space(dev);
1364 
1365     if (dma_as == &address_space_memory) {
1366         return false;
1367     }
1368 
1369     return true;
1370 }
1371 
1372 static bool virtio_pci_queue_enabled(DeviceState *d, int n)
1373 {
1374     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1375     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1376 
1377     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1378         return proxy->vqs[n].enabled;
1379     }
1380 
1381     return virtio_queue_enabled_legacy(vdev, n);
1382 }
1383 
1384 static int virtio_pci_add_mem_cap(VirtIOPCIProxy *proxy,
1385                                    struct virtio_pci_cap *cap)
1386 {
1387     PCIDevice *dev = &proxy->pci_dev;
1388     int offset;
1389 
1390     offset = pci_add_capability(dev, PCI_CAP_ID_VNDR, 0,
1391                                 cap->cap_len, &error_abort);
1392 
1393     assert(cap->cap_len >= sizeof *cap);
1394     memcpy(dev->config + offset + PCI_CAP_FLAGS, &cap->cap_len,
1395            cap->cap_len - PCI_CAP_FLAGS);
1396 
1397     return offset;
1398 }
1399 
1400 static uint64_t virtio_pci_common_read(void *opaque, hwaddr addr,
1401                                        unsigned size)
1402 {
1403     VirtIOPCIProxy *proxy = opaque;
1404     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1405     uint32_t val = 0;
1406     int i;
1407 
1408     if (vdev == NULL) {
1409         return UINT64_MAX;
1410     }
1411 
1412     switch (addr) {
1413     case VIRTIO_PCI_COMMON_DFSELECT:
1414         val = proxy->dfselect;
1415         break;
1416     case VIRTIO_PCI_COMMON_DF:
1417         if (proxy->dfselect <= 1) {
1418             VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1419 
1420             val = (vdev->host_features & ~vdc->legacy_features) >>
1421                 (32 * proxy->dfselect);
1422         }
1423         break;
1424     case VIRTIO_PCI_COMMON_GFSELECT:
1425         val = proxy->gfselect;
1426         break;
1427     case VIRTIO_PCI_COMMON_GF:
1428         if (proxy->gfselect < ARRAY_SIZE(proxy->guest_features)) {
1429             val = proxy->guest_features[proxy->gfselect];
1430         }
1431         break;
1432     case VIRTIO_PCI_COMMON_MSIX:
1433         val = vdev->config_vector;
1434         break;
1435     case VIRTIO_PCI_COMMON_NUMQ:
1436         for (i = 0; i < VIRTIO_QUEUE_MAX; ++i) {
1437             if (virtio_queue_get_num(vdev, i)) {
1438                 val = i + 1;
1439             }
1440         }
1441         break;
1442     case VIRTIO_PCI_COMMON_STATUS:
1443         val = vdev->status;
1444         break;
1445     case VIRTIO_PCI_COMMON_CFGGENERATION:
1446         val = vdev->generation;
1447         break;
1448     case VIRTIO_PCI_COMMON_Q_SELECT:
1449         val = vdev->queue_sel;
1450         break;
1451     case VIRTIO_PCI_COMMON_Q_SIZE:
1452         val = virtio_queue_get_num(vdev, vdev->queue_sel);
1453         break;
1454     case VIRTIO_PCI_COMMON_Q_MSIX:
1455         val = virtio_queue_vector(vdev, vdev->queue_sel);
1456         break;
1457     case VIRTIO_PCI_COMMON_Q_ENABLE:
1458         val = proxy->vqs[vdev->queue_sel].enabled;
1459         break;
1460     case VIRTIO_PCI_COMMON_Q_NOFF:
1461         /* Simply map queues in order */
1462         val = vdev->queue_sel;
1463         break;
1464     case VIRTIO_PCI_COMMON_Q_DESCLO:
1465         val = proxy->vqs[vdev->queue_sel].desc[0];
1466         break;
1467     case VIRTIO_PCI_COMMON_Q_DESCHI:
1468         val = proxy->vqs[vdev->queue_sel].desc[1];
1469         break;
1470     case VIRTIO_PCI_COMMON_Q_AVAILLO:
1471         val = proxy->vqs[vdev->queue_sel].avail[0];
1472         break;
1473     case VIRTIO_PCI_COMMON_Q_AVAILHI:
1474         val = proxy->vqs[vdev->queue_sel].avail[1];
1475         break;
1476     case VIRTIO_PCI_COMMON_Q_USEDLO:
1477         val = proxy->vqs[vdev->queue_sel].used[0];
1478         break;
1479     case VIRTIO_PCI_COMMON_Q_USEDHI:
1480         val = proxy->vqs[vdev->queue_sel].used[1];
1481         break;
1482     case VIRTIO_PCI_COMMON_Q_RESET:
1483         val = proxy->vqs[vdev->queue_sel].reset;
1484         break;
1485     default:
1486         val = 0;
1487     }
1488 
1489     return val;
1490 }
1491 
1492 static void virtio_pci_common_write(void *opaque, hwaddr addr,
1493                                     uint64_t val, unsigned size)
1494 {
1495     VirtIOPCIProxy *proxy = opaque;
1496     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1497     uint16_t vector;
1498 
1499     if (vdev == NULL) {
1500         return;
1501     }
1502 
1503     switch (addr) {
1504     case VIRTIO_PCI_COMMON_DFSELECT:
1505         proxy->dfselect = val;
1506         break;
1507     case VIRTIO_PCI_COMMON_GFSELECT:
1508         proxy->gfselect = val;
1509         break;
1510     case VIRTIO_PCI_COMMON_GF:
1511         if (proxy->gfselect < ARRAY_SIZE(proxy->guest_features)) {
1512             proxy->guest_features[proxy->gfselect] = val;
1513             virtio_set_features(vdev,
1514                                 (((uint64_t)proxy->guest_features[1]) << 32) |
1515                                 proxy->guest_features[0]);
1516         }
1517         break;
1518     case VIRTIO_PCI_COMMON_MSIX:
1519         if (vdev->config_vector != VIRTIO_NO_VECTOR) {
1520             msix_vector_unuse(&proxy->pci_dev, vdev->config_vector);
1521         }
1522         /* Make it possible for guest to discover an error took place. */
1523         if (val < proxy->nvectors) {
1524             msix_vector_use(&proxy->pci_dev, val);
1525         } else {
1526             val = VIRTIO_NO_VECTOR;
1527         }
1528         vdev->config_vector = val;
1529         break;
1530     case VIRTIO_PCI_COMMON_STATUS:
1531         if (!(val & VIRTIO_CONFIG_S_DRIVER_OK)) {
1532             virtio_pci_stop_ioeventfd(proxy);
1533         }
1534 
1535         virtio_set_status(vdev, val & 0xFF);
1536 
1537         if (val & VIRTIO_CONFIG_S_DRIVER_OK) {
1538             virtio_pci_start_ioeventfd(proxy);
1539         }
1540 
1541         if (vdev->status == 0) {
1542             virtio_pci_reset(DEVICE(proxy));
1543         }
1544 
1545         break;
1546     case VIRTIO_PCI_COMMON_Q_SELECT:
1547         if (val < VIRTIO_QUEUE_MAX) {
1548             vdev->queue_sel = val;
1549         }
1550         break;
1551     case VIRTIO_PCI_COMMON_Q_SIZE:
1552         proxy->vqs[vdev->queue_sel].num = val;
1553         virtio_queue_set_num(vdev, vdev->queue_sel,
1554                              proxy->vqs[vdev->queue_sel].num);
1555         break;
1556     case VIRTIO_PCI_COMMON_Q_MSIX:
1557         vector = virtio_queue_vector(vdev, vdev->queue_sel);
1558         if (vector != VIRTIO_NO_VECTOR) {
1559             msix_vector_unuse(&proxy->pci_dev, vector);
1560         }
1561         /* Make it possible for guest to discover an error took place. */
1562         if (val < proxy->nvectors) {
1563             msix_vector_use(&proxy->pci_dev, val);
1564         } else {
1565             val = VIRTIO_NO_VECTOR;
1566         }
1567         virtio_queue_set_vector(vdev, vdev->queue_sel, val);
1568         break;
1569     case VIRTIO_PCI_COMMON_Q_ENABLE:
1570         if (val == 1) {
1571             virtio_queue_set_num(vdev, vdev->queue_sel,
1572                                  proxy->vqs[vdev->queue_sel].num);
1573             virtio_queue_set_rings(vdev, vdev->queue_sel,
1574                        ((uint64_t)proxy->vqs[vdev->queue_sel].desc[1]) << 32 |
1575                        proxy->vqs[vdev->queue_sel].desc[0],
1576                        ((uint64_t)proxy->vqs[vdev->queue_sel].avail[1]) << 32 |
1577                        proxy->vqs[vdev->queue_sel].avail[0],
1578                        ((uint64_t)proxy->vqs[vdev->queue_sel].used[1]) << 32 |
1579                        proxy->vqs[vdev->queue_sel].used[0]);
1580             proxy->vqs[vdev->queue_sel].enabled = 1;
1581             proxy->vqs[vdev->queue_sel].reset = 0;
1582             virtio_queue_enable(vdev, vdev->queue_sel);
1583         } else {
1584             virtio_error(vdev, "wrong value for queue_enable %"PRIx64, val);
1585         }
1586         break;
1587     case VIRTIO_PCI_COMMON_Q_DESCLO:
1588         proxy->vqs[vdev->queue_sel].desc[0] = val;
1589         break;
1590     case VIRTIO_PCI_COMMON_Q_DESCHI:
1591         proxy->vqs[vdev->queue_sel].desc[1] = val;
1592         break;
1593     case VIRTIO_PCI_COMMON_Q_AVAILLO:
1594         proxy->vqs[vdev->queue_sel].avail[0] = val;
1595         break;
1596     case VIRTIO_PCI_COMMON_Q_AVAILHI:
1597         proxy->vqs[vdev->queue_sel].avail[1] = val;
1598         break;
1599     case VIRTIO_PCI_COMMON_Q_USEDLO:
1600         proxy->vqs[vdev->queue_sel].used[0] = val;
1601         break;
1602     case VIRTIO_PCI_COMMON_Q_USEDHI:
1603         proxy->vqs[vdev->queue_sel].used[1] = val;
1604         break;
1605     case VIRTIO_PCI_COMMON_Q_RESET:
1606         if (val == 1) {
1607             proxy->vqs[vdev->queue_sel].reset = 1;
1608 
1609             virtio_queue_reset(vdev, vdev->queue_sel);
1610 
1611             proxy->vqs[vdev->queue_sel].reset = 0;
1612             proxy->vqs[vdev->queue_sel].enabled = 0;
1613         }
1614         break;
1615     default:
1616         break;
1617     }
1618 }
1619 
1620 
1621 static uint64_t virtio_pci_notify_read(void *opaque, hwaddr addr,
1622                                        unsigned size)
1623 {
1624     VirtIOPCIProxy *proxy = opaque;
1625     if (virtio_bus_get_device(&proxy->bus) == NULL) {
1626         return UINT64_MAX;
1627     }
1628 
1629     return 0;
1630 }
1631 
1632 static void virtio_pci_notify_write(void *opaque, hwaddr addr,
1633                                     uint64_t val, unsigned size)
1634 {
1635     VirtIOPCIProxy *proxy = opaque;
1636     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1637 
1638     unsigned queue = addr / virtio_pci_queue_mem_mult(proxy);
1639 
1640     if (vdev != NULL && queue < VIRTIO_QUEUE_MAX) {
1641         trace_virtio_pci_notify_write(addr, val, size);
1642         virtio_queue_notify(vdev, queue);
1643     }
1644 }
1645 
1646 static void virtio_pci_notify_write_pio(void *opaque, hwaddr addr,
1647                                         uint64_t val, unsigned size)
1648 {
1649     VirtIOPCIProxy *proxy = opaque;
1650     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1651 
1652     unsigned queue = val;
1653 
1654     if (vdev != NULL && queue < VIRTIO_QUEUE_MAX) {
1655         trace_virtio_pci_notify_write_pio(addr, val, size);
1656         virtio_queue_notify(vdev, queue);
1657     }
1658 }
1659 
1660 static uint64_t virtio_pci_isr_read(void *opaque, hwaddr addr,
1661                                     unsigned size)
1662 {
1663     VirtIOPCIProxy *proxy = opaque;
1664     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1665     uint64_t val;
1666 
1667     if (vdev == NULL) {
1668         return UINT64_MAX;
1669     }
1670 
1671     val = qatomic_xchg(&vdev->isr, 0);
1672     pci_irq_deassert(&proxy->pci_dev);
1673     return val;
1674 }
1675 
1676 static void virtio_pci_isr_write(void *opaque, hwaddr addr,
1677                                  uint64_t val, unsigned size)
1678 {
1679 }
1680 
1681 static uint64_t virtio_pci_device_read(void *opaque, hwaddr addr,
1682                                        unsigned size)
1683 {
1684     VirtIOPCIProxy *proxy = opaque;
1685     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1686     uint64_t val;
1687 
1688     if (vdev == NULL) {
1689         return UINT64_MAX;
1690     }
1691 
1692     switch (size) {
1693     case 1:
1694         val = virtio_config_modern_readb(vdev, addr);
1695         break;
1696     case 2:
1697         val = virtio_config_modern_readw(vdev, addr);
1698         break;
1699     case 4:
1700         val = virtio_config_modern_readl(vdev, addr);
1701         break;
1702     default:
1703         val = 0;
1704         break;
1705     }
1706     return val;
1707 }
1708 
1709 static void virtio_pci_device_write(void *opaque, hwaddr addr,
1710                                     uint64_t val, unsigned size)
1711 {
1712     VirtIOPCIProxy *proxy = opaque;
1713     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1714 
1715     if (vdev == NULL) {
1716         return;
1717     }
1718 
1719     switch (size) {
1720     case 1:
1721         virtio_config_modern_writeb(vdev, addr, val);
1722         break;
1723     case 2:
1724         virtio_config_modern_writew(vdev, addr, val);
1725         break;
1726     case 4:
1727         virtio_config_modern_writel(vdev, addr, val);
1728         break;
1729     }
1730 }
1731 
1732 static void virtio_pci_modern_regions_init(VirtIOPCIProxy *proxy,
1733                                            const char *vdev_name)
1734 {
1735     static const MemoryRegionOps common_ops = {
1736         .read = virtio_pci_common_read,
1737         .write = virtio_pci_common_write,
1738         .impl = {
1739             .min_access_size = 1,
1740             .max_access_size = 4,
1741         },
1742         .endianness = DEVICE_LITTLE_ENDIAN,
1743     };
1744     static const MemoryRegionOps isr_ops = {
1745         .read = virtio_pci_isr_read,
1746         .write = virtio_pci_isr_write,
1747         .impl = {
1748             .min_access_size = 1,
1749             .max_access_size = 4,
1750         },
1751         .endianness = DEVICE_LITTLE_ENDIAN,
1752     };
1753     static const MemoryRegionOps device_ops = {
1754         .read = virtio_pci_device_read,
1755         .write = virtio_pci_device_write,
1756         .impl = {
1757             .min_access_size = 1,
1758             .max_access_size = 4,
1759         },
1760         .endianness = DEVICE_LITTLE_ENDIAN,
1761     };
1762     static const MemoryRegionOps notify_ops = {
1763         .read = virtio_pci_notify_read,
1764         .write = virtio_pci_notify_write,
1765         .impl = {
1766             .min_access_size = 1,
1767             .max_access_size = 4,
1768         },
1769         .endianness = DEVICE_LITTLE_ENDIAN,
1770     };
1771     static const MemoryRegionOps notify_pio_ops = {
1772         .read = virtio_pci_notify_read,
1773         .write = virtio_pci_notify_write_pio,
1774         .impl = {
1775             .min_access_size = 1,
1776             .max_access_size = 4,
1777         },
1778         .endianness = DEVICE_LITTLE_ENDIAN,
1779     };
1780     g_autoptr(GString) name = g_string_new(NULL);
1781 
1782     g_string_printf(name, "virtio-pci-common-%s", vdev_name);
1783     memory_region_init_io(&proxy->common.mr, OBJECT(proxy),
1784                           &common_ops,
1785                           proxy,
1786                           name->str,
1787                           proxy->common.size);
1788 
1789     g_string_printf(name, "virtio-pci-isr-%s", vdev_name);
1790     memory_region_init_io(&proxy->isr.mr, OBJECT(proxy),
1791                           &isr_ops,
1792                           proxy,
1793                           name->str,
1794                           proxy->isr.size);
1795 
1796     g_string_printf(name, "virtio-pci-device-%s", vdev_name);
1797     memory_region_init_io(&proxy->device.mr, OBJECT(proxy),
1798                           &device_ops,
1799                           proxy,
1800                           name->str,
1801                           proxy->device.size);
1802 
1803     g_string_printf(name, "virtio-pci-notify-%s", vdev_name);
1804     memory_region_init_io(&proxy->notify.mr, OBJECT(proxy),
1805                           &notify_ops,
1806                           proxy,
1807                           name->str,
1808                           proxy->notify.size);
1809 
1810     g_string_printf(name, "virtio-pci-notify-pio-%s", vdev_name);
1811     memory_region_init_io(&proxy->notify_pio.mr, OBJECT(proxy),
1812                           &notify_pio_ops,
1813                           proxy,
1814                           name->str,
1815                           proxy->notify_pio.size);
1816 }
1817 
1818 static void virtio_pci_modern_region_map(VirtIOPCIProxy *proxy,
1819                                          VirtIOPCIRegion *region,
1820                                          struct virtio_pci_cap *cap,
1821                                          MemoryRegion *mr,
1822                                          uint8_t bar)
1823 {
1824     memory_region_add_subregion(mr, region->offset, &region->mr);
1825 
1826     cap->cfg_type = region->type;
1827     cap->bar = bar;
1828     cap->offset = cpu_to_le32(region->offset);
1829     cap->length = cpu_to_le32(region->size);
1830     virtio_pci_add_mem_cap(proxy, cap);
1831 
1832 }
1833 
1834 static void virtio_pci_modern_mem_region_map(VirtIOPCIProxy *proxy,
1835                                              VirtIOPCIRegion *region,
1836                                              struct virtio_pci_cap *cap)
1837 {
1838     virtio_pci_modern_region_map(proxy, region, cap,
1839                                  &proxy->modern_bar, proxy->modern_mem_bar_idx);
1840 }
1841 
1842 static void virtio_pci_modern_io_region_map(VirtIOPCIProxy *proxy,
1843                                             VirtIOPCIRegion *region,
1844                                             struct virtio_pci_cap *cap)
1845 {
1846     virtio_pci_modern_region_map(proxy, region, cap,
1847                                  &proxy->io_bar, proxy->modern_io_bar_idx);
1848 }
1849 
1850 static void virtio_pci_modern_mem_region_unmap(VirtIOPCIProxy *proxy,
1851                                                VirtIOPCIRegion *region)
1852 {
1853     memory_region_del_subregion(&proxy->modern_bar,
1854                                 &region->mr);
1855 }
1856 
1857 static void virtio_pci_modern_io_region_unmap(VirtIOPCIProxy *proxy,
1858                                               VirtIOPCIRegion *region)
1859 {
1860     memory_region_del_subregion(&proxy->io_bar,
1861                                 &region->mr);
1862 }
1863 
1864 static void virtio_pci_pre_plugged(DeviceState *d, Error **errp)
1865 {
1866     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1867     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1868 
1869     if (virtio_pci_modern(proxy)) {
1870         virtio_add_feature(&vdev->host_features, VIRTIO_F_VERSION_1);
1871     }
1872 
1873     virtio_add_feature(&vdev->host_features, VIRTIO_F_BAD_FEATURE);
1874 }
1875 
1876 /* This is called by virtio-bus just after the device is plugged. */
1877 static void virtio_pci_device_plugged(DeviceState *d, Error **errp)
1878 {
1879     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1880     VirtioBusState *bus = &proxy->bus;
1881     bool legacy = virtio_pci_legacy(proxy);
1882     bool modern;
1883     bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;
1884     uint8_t *config;
1885     uint32_t size;
1886     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1887 
1888     /*
1889      * Virtio capabilities present without
1890      * VIRTIO_F_VERSION_1 confuses guests
1891      */
1892     if (!proxy->ignore_backend_features &&
1893             !virtio_has_feature(vdev->host_features, VIRTIO_F_VERSION_1)) {
1894         virtio_pci_disable_modern(proxy);
1895 
1896         if (!legacy) {
1897             error_setg(errp, "Device doesn't support modern mode, and legacy"
1898                              " mode is disabled");
1899             error_append_hint(errp, "Set disable-legacy to off\n");
1900 
1901             return;
1902         }
1903     }
1904 
1905     modern = virtio_pci_modern(proxy);
1906 
1907     config = proxy->pci_dev.config;
1908     if (proxy->class_code) {
1909         pci_config_set_class(config, proxy->class_code);
1910     }
1911 
1912     if (legacy) {
1913         if (!virtio_legacy_allowed(vdev)) {
1914             /*
1915              * To avoid migration issues, we allow legacy mode when legacy
1916              * check is disabled in the old machine types (< 5.1).
1917              */
1918             if (virtio_legacy_check_disabled(vdev)) {
1919                 warn_report("device is modern-only, but for backward "
1920                             "compatibility legacy is allowed");
1921             } else {
1922                 error_setg(errp,
1923                            "device is modern-only, use disable-legacy=on");
1924                 return;
1925             }
1926         }
1927         if (virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM)) {
1928             error_setg(errp, "VIRTIO_F_IOMMU_PLATFORM was supported by"
1929                        " neither legacy nor transitional device");
1930             return;
1931         }
1932         /*
1933          * Legacy and transitional devices use specific subsystem IDs.
1934          * Note that the subsystem vendor ID (config + PCI_SUBSYSTEM_VENDOR_ID)
1935          * is set to PCI_SUBVENDOR_ID_REDHAT_QUMRANET by default.
1936          */
1937         pci_set_word(config + PCI_SUBSYSTEM_ID, virtio_bus_get_vdev_id(bus));
1938         if (proxy->trans_devid) {
1939             pci_config_set_device_id(config, proxy->trans_devid);
1940         }
1941     } else {
1942         /* pure virtio-1.0 */
1943         pci_set_word(config + PCI_VENDOR_ID,
1944                      PCI_VENDOR_ID_REDHAT_QUMRANET);
1945         pci_set_word(config + PCI_DEVICE_ID,
1946                      PCI_DEVICE_ID_VIRTIO_10_BASE + virtio_bus_get_vdev_id(bus));
1947         pci_config_set_revision(config, 1);
1948     }
1949     config[PCI_INTERRUPT_PIN] = 1;
1950 
1951 
1952     if (modern) {
1953         struct virtio_pci_cap cap = {
1954             .cap_len = sizeof cap,
1955         };
1956         struct virtio_pci_notify_cap notify = {
1957             .cap.cap_len = sizeof notify,
1958             .notify_off_multiplier =
1959                 cpu_to_le32(virtio_pci_queue_mem_mult(proxy)),
1960         };
1961         struct virtio_pci_cfg_cap cfg = {
1962             .cap.cap_len = sizeof cfg,
1963             .cap.cfg_type = VIRTIO_PCI_CAP_PCI_CFG,
1964         };
1965         struct virtio_pci_notify_cap notify_pio = {
1966             .cap.cap_len = sizeof notify,
1967             .notify_off_multiplier = cpu_to_le32(0x0),
1968         };
1969 
1970         struct virtio_pci_cfg_cap *cfg_mask;
1971 
1972         virtio_pci_modern_regions_init(proxy, vdev->name);
1973 
1974         virtio_pci_modern_mem_region_map(proxy, &proxy->common, &cap);
1975         virtio_pci_modern_mem_region_map(proxy, &proxy->isr, &cap);
1976         virtio_pci_modern_mem_region_map(proxy, &proxy->device, &cap);
1977         virtio_pci_modern_mem_region_map(proxy, &proxy->notify, &notify.cap);
1978 
1979         if (modern_pio) {
1980             memory_region_init(&proxy->io_bar, OBJECT(proxy),
1981                                "virtio-pci-io", 0x4);
1982 
1983             pci_register_bar(&proxy->pci_dev, proxy->modern_io_bar_idx,
1984                              PCI_BASE_ADDRESS_SPACE_IO, &proxy->io_bar);
1985 
1986             virtio_pci_modern_io_region_map(proxy, &proxy->notify_pio,
1987                                             &notify_pio.cap);
1988         }
1989 
1990         pci_register_bar(&proxy->pci_dev, proxy->modern_mem_bar_idx,
1991                          PCI_BASE_ADDRESS_SPACE_MEMORY |
1992                          PCI_BASE_ADDRESS_MEM_PREFETCH |
1993                          PCI_BASE_ADDRESS_MEM_TYPE_64,
1994                          &proxy->modern_bar);
1995 
1996         proxy->config_cap = virtio_pci_add_mem_cap(proxy, &cfg.cap);
1997         cfg_mask = (void *)(proxy->pci_dev.wmask + proxy->config_cap);
1998         pci_set_byte(&cfg_mask->cap.bar, ~0x0);
1999         pci_set_long((uint8_t *)&cfg_mask->cap.offset, ~0x0);
2000         pci_set_long((uint8_t *)&cfg_mask->cap.length, ~0x0);
2001         pci_set_long(cfg_mask->pci_cfg_data, ~0x0);
2002     }
2003 
2004     if (proxy->nvectors) {
2005         int err = msix_init_exclusive_bar(&proxy->pci_dev, proxy->nvectors,
2006                                           proxy->msix_bar_idx, NULL);
2007         if (err) {
2008             /* Notice when a system that supports MSIx can't initialize it */
2009             if (err != -ENOTSUP) {
2010                 warn_report("unable to init msix vectors to %" PRIu32,
2011                             proxy->nvectors);
2012             }
2013             proxy->nvectors = 0;
2014         }
2015     }
2016 
2017     proxy->pci_dev.config_write = virtio_write_config;
2018     proxy->pci_dev.config_read = virtio_read_config;
2019 
2020     if (legacy) {
2021         size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev)
2022             + virtio_bus_get_vdev_config_len(bus);
2023         size = pow2ceil(size);
2024 
2025         memory_region_init_io(&proxy->bar, OBJECT(proxy),
2026                               &virtio_pci_config_ops,
2027                               proxy, "virtio-pci", size);
2028 
2029         pci_register_bar(&proxy->pci_dev, proxy->legacy_io_bar_idx,
2030                          PCI_BASE_ADDRESS_SPACE_IO, &proxy->bar);
2031     }
2032 }
2033 
2034 static void virtio_pci_device_unplugged(DeviceState *d)
2035 {
2036     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
2037     bool modern = virtio_pci_modern(proxy);
2038     bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;
2039 
2040     virtio_pci_stop_ioeventfd(proxy);
2041 
2042     if (modern) {
2043         virtio_pci_modern_mem_region_unmap(proxy, &proxy->common);
2044         virtio_pci_modern_mem_region_unmap(proxy, &proxy->isr);
2045         virtio_pci_modern_mem_region_unmap(proxy, &proxy->device);
2046         virtio_pci_modern_mem_region_unmap(proxy, &proxy->notify);
2047         if (modern_pio) {
2048             virtio_pci_modern_io_region_unmap(proxy, &proxy->notify_pio);
2049         }
2050     }
2051 }
2052 
2053 static void virtio_pci_realize(PCIDevice *pci_dev, Error **errp)
2054 {
2055     VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev);
2056     VirtioPCIClass *k = VIRTIO_PCI_GET_CLASS(pci_dev);
2057     bool pcie_port = pci_bus_is_express(pci_get_bus(pci_dev)) &&
2058                      !pci_bus_is_root(pci_get_bus(pci_dev));
2059 
2060     if (kvm_enabled() && !kvm_has_many_ioeventfds()) {
2061         proxy->flags &= ~VIRTIO_PCI_FLAG_USE_IOEVENTFD;
2062     }
2063 
2064     /* fd-based ioevents can't be synchronized in record/replay */
2065     if (replay_mode != REPLAY_MODE_NONE) {
2066         proxy->flags &= ~VIRTIO_PCI_FLAG_USE_IOEVENTFD;
2067     }
2068 
2069     /*
2070      * virtio pci bar layout used by default.
2071      * subclasses can re-arrange things if needed.
2072      *
2073      *   region 0   --  virtio legacy io bar
2074      *   region 1   --  msi-x bar
2075      *   region 2   --  virtio modern io bar (off by default)
2076      *   region 4+5 --  virtio modern memory (64bit) bar
2077      *
2078      */
2079     proxy->legacy_io_bar_idx  = 0;
2080     proxy->msix_bar_idx       = 1;
2081     proxy->modern_io_bar_idx  = 2;
2082     proxy->modern_mem_bar_idx = 4;
2083 
2084     proxy->common.offset = 0x0;
2085     proxy->common.size = 0x1000;
2086     proxy->common.type = VIRTIO_PCI_CAP_COMMON_CFG;
2087 
2088     proxy->isr.offset = 0x1000;
2089     proxy->isr.size = 0x1000;
2090     proxy->isr.type = VIRTIO_PCI_CAP_ISR_CFG;
2091 
2092     proxy->device.offset = 0x2000;
2093     proxy->device.size = 0x1000;
2094     proxy->device.type = VIRTIO_PCI_CAP_DEVICE_CFG;
2095 
2096     proxy->notify.offset = 0x3000;
2097     proxy->notify.size = virtio_pci_queue_mem_mult(proxy) * VIRTIO_QUEUE_MAX;
2098     proxy->notify.type = VIRTIO_PCI_CAP_NOTIFY_CFG;
2099 
2100     proxy->notify_pio.offset = 0x0;
2101     proxy->notify_pio.size = 0x4;
2102     proxy->notify_pio.type = VIRTIO_PCI_CAP_NOTIFY_CFG;
2103 
2104     /* subclasses can enforce modern, so do this unconditionally */
2105     memory_region_init(&proxy->modern_bar, OBJECT(proxy), "virtio-pci",
2106                        /* PCI BAR regions must be powers of 2 */
2107                        pow2ceil(proxy->notify.offset + proxy->notify.size));
2108 
2109     if (proxy->disable_legacy == ON_OFF_AUTO_AUTO) {
2110         proxy->disable_legacy = pcie_port ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
2111     }
2112 
2113     if (!virtio_pci_modern(proxy) && !virtio_pci_legacy(proxy)) {
2114         error_setg(errp, "device cannot work as neither modern nor legacy mode"
2115                    " is enabled");
2116         error_append_hint(errp, "Set either disable-modern or disable-legacy"
2117                           " to off\n");
2118         return;
2119     }
2120 
2121     if (pcie_port && pci_is_express(pci_dev)) {
2122         int pos;
2123         uint16_t last_pcie_cap_offset = PCI_CONFIG_SPACE_SIZE;
2124 
2125         pos = pcie_endpoint_cap_init(pci_dev, 0);
2126         assert(pos > 0);
2127 
2128         pos = pci_add_capability(pci_dev, PCI_CAP_ID_PM, 0,
2129                                  PCI_PM_SIZEOF, errp);
2130         if (pos < 0) {
2131             return;
2132         }
2133 
2134         pci_dev->exp.pm_cap = pos;
2135 
2136         /*
2137          * Indicates that this function complies with revision 1.2 of the
2138          * PCI Power Management Interface Specification.
2139          */
2140         pci_set_word(pci_dev->config + pos + PCI_PM_PMC, 0x3);
2141 
2142         if (proxy->flags & VIRTIO_PCI_FLAG_AER) {
2143             pcie_aer_init(pci_dev, PCI_ERR_VER, last_pcie_cap_offset,
2144                           PCI_ERR_SIZEOF, NULL);
2145             last_pcie_cap_offset += PCI_ERR_SIZEOF;
2146         }
2147 
2148         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_DEVERR) {
2149             /* Init error enabling flags */
2150             pcie_cap_deverr_init(pci_dev);
2151         }
2152 
2153         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_LNKCTL) {
2154             /* Init Link Control Register */
2155             pcie_cap_lnkctl_init(pci_dev);
2156         }
2157 
2158         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_PM) {
2159             /* Init Power Management Control Register */
2160             pci_set_word(pci_dev->wmask + pos + PCI_PM_CTRL,
2161                          PCI_PM_CTRL_STATE_MASK);
2162         }
2163 
2164         if (proxy->flags & VIRTIO_PCI_FLAG_ATS) {
2165             pcie_ats_init(pci_dev, last_pcie_cap_offset,
2166                           proxy->flags & VIRTIO_PCI_FLAG_ATS_PAGE_ALIGNED);
2167             last_pcie_cap_offset += PCI_EXT_CAP_ATS_SIZEOF;
2168         }
2169 
2170         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_FLR) {
2171             /* Set Function Level Reset capability bit */
2172             pcie_cap_flr_init(pci_dev);
2173         }
2174     } else {
2175         /*
2176          * make future invocations of pci_is_express() return false
2177          * and pci_config_size() return PCI_CONFIG_SPACE_SIZE.
2178          */
2179         pci_dev->cap_present &= ~QEMU_PCI_CAP_EXPRESS;
2180     }
2181 
2182     virtio_pci_bus_new(&proxy->bus, sizeof(proxy->bus), proxy);
2183     if (k->realize) {
2184         k->realize(proxy, errp);
2185     }
2186 }
2187 
2188 static void virtio_pci_exit(PCIDevice *pci_dev)
2189 {
2190     VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev);
2191     bool pcie_port = pci_bus_is_express(pci_get_bus(pci_dev)) &&
2192                      !pci_bus_is_root(pci_get_bus(pci_dev));
2193 
2194     msix_uninit_exclusive_bar(pci_dev);
2195     if (proxy->flags & VIRTIO_PCI_FLAG_AER && pcie_port &&
2196         pci_is_express(pci_dev)) {
2197         pcie_aer_exit(pci_dev);
2198     }
2199 }
2200 
2201 static void virtio_pci_reset(DeviceState *qdev)
2202 {
2203     VirtIOPCIProxy *proxy = VIRTIO_PCI(qdev);
2204     VirtioBusState *bus = VIRTIO_BUS(&proxy->bus);
2205     int i;
2206 
2207     virtio_bus_reset(bus);
2208     msix_unuse_all_vectors(&proxy->pci_dev);
2209 
2210     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
2211         proxy->vqs[i].enabled = 0;
2212         proxy->vqs[i].reset = 0;
2213         proxy->vqs[i].num = 0;
2214         proxy->vqs[i].desc[0] = proxy->vqs[i].desc[1] = 0;
2215         proxy->vqs[i].avail[0] = proxy->vqs[i].avail[1] = 0;
2216         proxy->vqs[i].used[0] = proxy->vqs[i].used[1] = 0;
2217     }
2218 }
2219 
2220 static void virtio_pci_bus_reset_hold(Object *obj)
2221 {
2222     PCIDevice *dev = PCI_DEVICE(obj);
2223     DeviceState *qdev = DEVICE(obj);
2224 
2225     virtio_pci_reset(qdev);
2226 
2227     if (pci_is_express(dev)) {
2228         pcie_cap_deverr_reset(dev);
2229         pcie_cap_lnkctl_reset(dev);
2230 
2231         pci_set_word(dev->config + dev->exp.pm_cap + PCI_PM_CTRL, 0);
2232     }
2233 }
2234 
2235 static Property virtio_pci_properties[] = {
2236     DEFINE_PROP_BIT("virtio-pci-bus-master-bug-migration", VirtIOPCIProxy, flags,
2237                     VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION_BIT, false),
2238     DEFINE_PROP_BIT("migrate-extra", VirtIOPCIProxy, flags,
2239                     VIRTIO_PCI_FLAG_MIGRATE_EXTRA_BIT, true),
2240     DEFINE_PROP_BIT("modern-pio-notify", VirtIOPCIProxy, flags,
2241                     VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY_BIT, false),
2242     DEFINE_PROP_BIT("x-disable-pcie", VirtIOPCIProxy, flags,
2243                     VIRTIO_PCI_FLAG_DISABLE_PCIE_BIT, false),
2244     DEFINE_PROP_BIT("page-per-vq", VirtIOPCIProxy, flags,
2245                     VIRTIO_PCI_FLAG_PAGE_PER_VQ_BIT, false),
2246     DEFINE_PROP_BOOL("x-ignore-backend-features", VirtIOPCIProxy,
2247                      ignore_backend_features, false),
2248     DEFINE_PROP_BIT("ats", VirtIOPCIProxy, flags,
2249                     VIRTIO_PCI_FLAG_ATS_BIT, false),
2250     DEFINE_PROP_BIT("x-ats-page-aligned", VirtIOPCIProxy, flags,
2251                     VIRTIO_PCI_FLAG_ATS_PAGE_ALIGNED_BIT, true),
2252     DEFINE_PROP_BIT("x-pcie-deverr-init", VirtIOPCIProxy, flags,
2253                     VIRTIO_PCI_FLAG_INIT_DEVERR_BIT, true),
2254     DEFINE_PROP_BIT("x-pcie-lnkctl-init", VirtIOPCIProxy, flags,
2255                     VIRTIO_PCI_FLAG_INIT_LNKCTL_BIT, true),
2256     DEFINE_PROP_BIT("x-pcie-pm-init", VirtIOPCIProxy, flags,
2257                     VIRTIO_PCI_FLAG_INIT_PM_BIT, true),
2258     DEFINE_PROP_BIT("x-pcie-flr-init", VirtIOPCIProxy, flags,
2259                     VIRTIO_PCI_FLAG_INIT_FLR_BIT, true),
2260     DEFINE_PROP_BIT("aer", VirtIOPCIProxy, flags,
2261                     VIRTIO_PCI_FLAG_AER_BIT, false),
2262     DEFINE_PROP_END_OF_LIST(),
2263 };
2264 
2265 static void virtio_pci_dc_realize(DeviceState *qdev, Error **errp)
2266 {
2267     VirtioPCIClass *vpciklass = VIRTIO_PCI_GET_CLASS(qdev);
2268     VirtIOPCIProxy *proxy = VIRTIO_PCI(qdev);
2269     PCIDevice *pci_dev = &proxy->pci_dev;
2270 
2271     if (!(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_PCIE) &&
2272         virtio_pci_modern(proxy)) {
2273         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2274     }
2275 
2276     vpciklass->parent_dc_realize(qdev, errp);
2277 }
2278 
2279 static void virtio_pci_class_init(ObjectClass *klass, void *data)
2280 {
2281     DeviceClass *dc = DEVICE_CLASS(klass);
2282     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2283     VirtioPCIClass *vpciklass = VIRTIO_PCI_CLASS(klass);
2284     ResettableClass *rc = RESETTABLE_CLASS(klass);
2285 
2286     device_class_set_props(dc, virtio_pci_properties);
2287     k->realize = virtio_pci_realize;
2288     k->exit = virtio_pci_exit;
2289     k->vendor_id = PCI_VENDOR_ID_REDHAT_QUMRANET;
2290     k->revision = VIRTIO_PCI_ABI_VERSION;
2291     k->class_id = PCI_CLASS_OTHERS;
2292     device_class_set_parent_realize(dc, virtio_pci_dc_realize,
2293                                     &vpciklass->parent_dc_realize);
2294     rc->phases.hold = virtio_pci_bus_reset_hold;
2295 }
2296 
2297 static const TypeInfo virtio_pci_info = {
2298     .name          = TYPE_VIRTIO_PCI,
2299     .parent        = TYPE_PCI_DEVICE,
2300     .instance_size = sizeof(VirtIOPCIProxy),
2301     .class_init    = virtio_pci_class_init,
2302     .class_size    = sizeof(VirtioPCIClass),
2303     .abstract      = true,
2304 };
2305 
2306 static Property virtio_pci_generic_properties[] = {
2307     DEFINE_PROP_ON_OFF_AUTO("disable-legacy", VirtIOPCIProxy, disable_legacy,
2308                             ON_OFF_AUTO_AUTO),
2309     DEFINE_PROP_BOOL("disable-modern", VirtIOPCIProxy, disable_modern, false),
2310     DEFINE_PROP_END_OF_LIST(),
2311 };
2312 
2313 static void virtio_pci_base_class_init(ObjectClass *klass, void *data)
2314 {
2315     const VirtioPCIDeviceTypeInfo *t = data;
2316     if (t->class_init) {
2317         t->class_init(klass, NULL);
2318     }
2319 }
2320 
2321 static void virtio_pci_generic_class_init(ObjectClass *klass, void *data)
2322 {
2323     DeviceClass *dc = DEVICE_CLASS(klass);
2324 
2325     device_class_set_props(dc, virtio_pci_generic_properties);
2326 }
2327 
2328 static void virtio_pci_transitional_instance_init(Object *obj)
2329 {
2330     VirtIOPCIProxy *proxy = VIRTIO_PCI(obj);
2331 
2332     proxy->disable_legacy = ON_OFF_AUTO_OFF;
2333     proxy->disable_modern = false;
2334 }
2335 
2336 static void virtio_pci_non_transitional_instance_init(Object *obj)
2337 {
2338     VirtIOPCIProxy *proxy = VIRTIO_PCI(obj);
2339 
2340     proxy->disable_legacy = ON_OFF_AUTO_ON;
2341     proxy->disable_modern = false;
2342 }
2343 
2344 void virtio_pci_types_register(const VirtioPCIDeviceTypeInfo *t)
2345 {
2346     char *base_name = NULL;
2347     TypeInfo base_type_info = {
2348         .name          = t->base_name,
2349         .parent        = t->parent ? t->parent : TYPE_VIRTIO_PCI,
2350         .instance_size = t->instance_size,
2351         .instance_init = t->instance_init,
2352         .class_size    = t->class_size,
2353         .abstract      = true,
2354         .interfaces    = t->interfaces,
2355     };
2356     TypeInfo generic_type_info = {
2357         .name = t->generic_name,
2358         .parent = base_type_info.name,
2359         .class_init = virtio_pci_generic_class_init,
2360         .interfaces = (InterfaceInfo[]) {
2361             { INTERFACE_PCIE_DEVICE },
2362             { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2363             { }
2364         },
2365     };
2366 
2367     if (!base_type_info.name) {
2368         /* No base type -> register a single generic device type */
2369         /* use intermediate %s-base-type to add generic device props */
2370         base_name = g_strdup_printf("%s-base-type", t->generic_name);
2371         base_type_info.name = base_name;
2372         base_type_info.class_init = virtio_pci_generic_class_init;
2373 
2374         generic_type_info.parent = base_name;
2375         generic_type_info.class_init = virtio_pci_base_class_init;
2376         generic_type_info.class_data = (void *)t;
2377 
2378         assert(!t->non_transitional_name);
2379         assert(!t->transitional_name);
2380     } else {
2381         base_type_info.class_init = virtio_pci_base_class_init;
2382         base_type_info.class_data = (void *)t;
2383     }
2384 
2385     type_register(&base_type_info);
2386     if (generic_type_info.name) {
2387         type_register(&generic_type_info);
2388     }
2389 
2390     if (t->non_transitional_name) {
2391         const TypeInfo non_transitional_type_info = {
2392             .name          = t->non_transitional_name,
2393             .parent        = base_type_info.name,
2394             .instance_init = virtio_pci_non_transitional_instance_init,
2395             .interfaces = (InterfaceInfo[]) {
2396                 { INTERFACE_PCIE_DEVICE },
2397                 { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2398                 { }
2399             },
2400         };
2401         type_register(&non_transitional_type_info);
2402     }
2403 
2404     if (t->transitional_name) {
2405         const TypeInfo transitional_type_info = {
2406             .name          = t->transitional_name,
2407             .parent        = base_type_info.name,
2408             .instance_init = virtio_pci_transitional_instance_init,
2409             .interfaces = (InterfaceInfo[]) {
2410                 /*
2411                  * Transitional virtio devices work only as Conventional PCI
2412                  * devices because they require PIO ports.
2413                  */
2414                 { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2415                 { }
2416             },
2417         };
2418         type_register(&transitional_type_info);
2419     }
2420     g_free(base_name);
2421 }
2422 
2423 unsigned virtio_pci_optimal_num_queues(unsigned fixed_queues)
2424 {
2425     /*
2426      * 1:1 vq to vCPU mapping is ideal because the same vCPU that submitted
2427      * virtqueue buffers can handle their completion. When a different vCPU
2428      * handles completion it may need to IPI the vCPU that submitted the
2429      * request and this adds overhead.
2430      *
2431      * Virtqueues consume guest RAM and MSI-X vectors. This is wasteful in
2432      * guests with very many vCPUs and a device that is only used by a few
2433      * vCPUs. Unfortunately optimizing that case requires manual pinning inside
2434      * the guest, so those users might as well manually set the number of
2435      * queues. There is no upper limit that can be applied automatically and
2436      * doing so arbitrarily would result in a sudden performance drop once the
2437      * threshold number of vCPUs is exceeded.
2438      */
2439     unsigned num_queues = current_machine->smp.cpus;
2440 
2441     /*
2442      * The maximum number of MSI-X vectors is PCI_MSIX_FLAGS_QSIZE + 1, but the
2443      * config change interrupt and the fixed virtqueues must be taken into
2444      * account too.
2445      */
2446     num_queues = MIN(num_queues, PCI_MSIX_FLAGS_QSIZE - fixed_queues);
2447 
2448     /*
2449      * There is a limit to how many virtqueues a device can have.
2450      */
2451     return MIN(num_queues, VIRTIO_QUEUE_MAX - fixed_queues);
2452 }
2453 
2454 /* virtio-pci-bus */
2455 
2456 static void virtio_pci_bus_new(VirtioBusState *bus, size_t bus_size,
2457                                VirtIOPCIProxy *dev)
2458 {
2459     DeviceState *qdev = DEVICE(dev);
2460     char virtio_bus_name[] = "virtio-bus";
2461 
2462     qbus_init(bus, bus_size, TYPE_VIRTIO_PCI_BUS, qdev, virtio_bus_name);
2463 }
2464 
2465 static void virtio_pci_bus_class_init(ObjectClass *klass, void *data)
2466 {
2467     BusClass *bus_class = BUS_CLASS(klass);
2468     VirtioBusClass *k = VIRTIO_BUS_CLASS(klass);
2469     bus_class->max_dev = 1;
2470     k->notify = virtio_pci_notify;
2471     k->save_config = virtio_pci_save_config;
2472     k->load_config = virtio_pci_load_config;
2473     k->save_queue = virtio_pci_save_queue;
2474     k->load_queue = virtio_pci_load_queue;
2475     k->save_extra_state = virtio_pci_save_extra_state;
2476     k->load_extra_state = virtio_pci_load_extra_state;
2477     k->has_extra_state = virtio_pci_has_extra_state;
2478     k->query_guest_notifiers = virtio_pci_query_guest_notifiers;
2479     k->set_guest_notifiers = virtio_pci_set_guest_notifiers;
2480     k->set_host_notifier_mr = virtio_pci_set_host_notifier_mr;
2481     k->vmstate_change = virtio_pci_vmstate_change;
2482     k->pre_plugged = virtio_pci_pre_plugged;
2483     k->device_plugged = virtio_pci_device_plugged;
2484     k->device_unplugged = virtio_pci_device_unplugged;
2485     k->query_nvectors = virtio_pci_query_nvectors;
2486     k->ioeventfd_enabled = virtio_pci_ioeventfd_enabled;
2487     k->ioeventfd_assign = virtio_pci_ioeventfd_assign;
2488     k->get_dma_as = virtio_pci_get_dma_as;
2489     k->iommu_enabled = virtio_pci_iommu_enabled;
2490     k->queue_enabled = virtio_pci_queue_enabled;
2491 }
2492 
2493 static const TypeInfo virtio_pci_bus_info = {
2494     .name          = TYPE_VIRTIO_PCI_BUS,
2495     .parent        = TYPE_VIRTIO_BUS,
2496     .instance_size = sizeof(VirtioPCIBusState),
2497     .class_size    = sizeof(VirtioPCIBusClass),
2498     .class_init    = virtio_pci_bus_class_init,
2499 };
2500 
2501 static void virtio_pci_register_types(void)
2502 {
2503     /* Base types: */
2504     type_register_static(&virtio_pci_bus_info);
2505     type_register_static(&virtio_pci_info);
2506 }
2507 
2508 type_init(virtio_pci_register_types)
2509 
2510