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