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