xref: /qemu/hw/virtio/virtio-pci.c (revision ca61e750)
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     /* When deassigning, pass a consistent nvqs value
1000      * to avoid leaking notifiers.
1001      */
1002     assert(assign || nvqs == proxy->nvqs_with_notifiers);
1003 
1004     proxy->nvqs_with_notifiers = nvqs;
1005 
1006     /* Must unset vector notifier while guest notifier is still assigned */
1007     if ((proxy->vector_irqfd || k->guest_notifier_mask) && !assign) {
1008         msix_unset_vector_notifiers(&proxy->pci_dev);
1009         if (proxy->vector_irqfd) {
1010             kvm_virtio_pci_vector_release(proxy, nvqs);
1011             g_free(proxy->vector_irqfd);
1012             proxy->vector_irqfd = NULL;
1013         }
1014     }
1015 
1016     for (n = 0; n < nvqs; n++) {
1017         if (!virtio_queue_get_num(vdev, n)) {
1018             break;
1019         }
1020 
1021         r = virtio_pci_set_guest_notifier(d, n, assign, with_irqfd);
1022         if (r < 0) {
1023             goto assign_error;
1024         }
1025     }
1026 
1027     /* Must set vector notifier after guest notifier has been assigned */
1028     if ((with_irqfd || k->guest_notifier_mask) && assign) {
1029         if (with_irqfd) {
1030             proxy->vector_irqfd =
1031                 g_malloc0(sizeof(*proxy->vector_irqfd) *
1032                           msix_nr_vectors_allocated(&proxy->pci_dev));
1033             r = kvm_virtio_pci_vector_use(proxy, nvqs);
1034             if (r < 0) {
1035                 goto assign_error;
1036             }
1037         }
1038         r = msix_set_vector_notifiers(&proxy->pci_dev,
1039                                       virtio_pci_vector_unmask,
1040                                       virtio_pci_vector_mask,
1041                                       virtio_pci_vector_poll);
1042         if (r < 0) {
1043             goto notifiers_error;
1044         }
1045     }
1046 
1047     return 0;
1048 
1049 notifiers_error:
1050     if (with_irqfd) {
1051         assert(assign);
1052         kvm_virtio_pci_vector_release(proxy, nvqs);
1053     }
1054 
1055 assign_error:
1056     /* We get here on assignment failure. Recover by undoing for VQs 0 .. n. */
1057     assert(assign);
1058     while (--n >= 0) {
1059         virtio_pci_set_guest_notifier(d, n, !assign, with_irqfd);
1060     }
1061     return r;
1062 }
1063 
1064 static int virtio_pci_set_host_notifier_mr(DeviceState *d, int n,
1065                                            MemoryRegion *mr, bool assign)
1066 {
1067     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
1068     int offset;
1069 
1070     if (n >= VIRTIO_QUEUE_MAX || !virtio_pci_modern(proxy) ||
1071         virtio_pci_queue_mem_mult(proxy) != memory_region_size(mr)) {
1072         return -1;
1073     }
1074 
1075     if (assign) {
1076         offset = virtio_pci_queue_mem_mult(proxy) * n;
1077         memory_region_add_subregion_overlap(&proxy->notify.mr, offset, mr, 1);
1078     } else {
1079         memory_region_del_subregion(&proxy->notify.mr, mr);
1080     }
1081 
1082     return 0;
1083 }
1084 
1085 static void virtio_pci_vmstate_change(DeviceState *d, bool running)
1086 {
1087     VirtIOPCIProxy *proxy = to_virtio_pci_proxy(d);
1088     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1089 
1090     if (running) {
1091         /* Old QEMU versions did not set bus master enable on status write.
1092          * Detect DRIVER set and enable it.
1093          */
1094         if ((proxy->flags & VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION) &&
1095             (vdev->status & VIRTIO_CONFIG_S_DRIVER) &&
1096             !(proxy->pci_dev.config[PCI_COMMAND] & PCI_COMMAND_MASTER)) {
1097             pci_default_write_config(&proxy->pci_dev, PCI_COMMAND,
1098                                      proxy->pci_dev.config[PCI_COMMAND] |
1099                                      PCI_COMMAND_MASTER, 1);
1100         }
1101         virtio_pci_start_ioeventfd(proxy);
1102     } else {
1103         virtio_pci_stop_ioeventfd(proxy);
1104     }
1105 }
1106 
1107 /*
1108  * virtio-pci: This is the PCIDevice which has a virtio-pci-bus.
1109  */
1110 
1111 static int virtio_pci_query_nvectors(DeviceState *d)
1112 {
1113     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1114 
1115     return proxy->nvectors;
1116 }
1117 
1118 static AddressSpace *virtio_pci_get_dma_as(DeviceState *d)
1119 {
1120     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1121     PCIDevice *dev = &proxy->pci_dev;
1122 
1123     return pci_get_address_space(dev);
1124 }
1125 
1126 static bool virtio_pci_iommu_enabled(DeviceState *d)
1127 {
1128     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1129     PCIDevice *dev = &proxy->pci_dev;
1130     AddressSpace *dma_as = pci_device_iommu_address_space(dev);
1131 
1132     if (dma_as == &address_space_memory) {
1133         return false;
1134     }
1135 
1136     return true;
1137 }
1138 
1139 static bool virtio_pci_queue_enabled(DeviceState *d, int n)
1140 {
1141     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1142     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1143 
1144     if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1145         return proxy->vqs[n].enabled;
1146     }
1147 
1148     return virtio_queue_enabled_legacy(vdev, n);
1149 }
1150 
1151 static int virtio_pci_add_mem_cap(VirtIOPCIProxy *proxy,
1152                                    struct virtio_pci_cap *cap)
1153 {
1154     PCIDevice *dev = &proxy->pci_dev;
1155     int offset;
1156 
1157     offset = pci_add_capability(dev, PCI_CAP_ID_VNDR, 0,
1158                                 cap->cap_len, &error_abort);
1159 
1160     assert(cap->cap_len >= sizeof *cap);
1161     memcpy(dev->config + offset + PCI_CAP_FLAGS, &cap->cap_len,
1162            cap->cap_len - PCI_CAP_FLAGS);
1163 
1164     return offset;
1165 }
1166 
1167 static uint64_t virtio_pci_common_read(void *opaque, hwaddr addr,
1168                                        unsigned size)
1169 {
1170     VirtIOPCIProxy *proxy = opaque;
1171     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1172     uint32_t val = 0;
1173     int i;
1174 
1175     if (vdev == NULL) {
1176         return UINT64_MAX;
1177     }
1178 
1179     switch (addr) {
1180     case VIRTIO_PCI_COMMON_DFSELECT:
1181         val = proxy->dfselect;
1182         break;
1183     case VIRTIO_PCI_COMMON_DF:
1184         if (proxy->dfselect <= 1) {
1185             VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1186 
1187             val = (vdev->host_features & ~vdc->legacy_features) >>
1188                 (32 * proxy->dfselect);
1189         }
1190         break;
1191     case VIRTIO_PCI_COMMON_GFSELECT:
1192         val = proxy->gfselect;
1193         break;
1194     case VIRTIO_PCI_COMMON_GF:
1195         if (proxy->gfselect < ARRAY_SIZE(proxy->guest_features)) {
1196             val = proxy->guest_features[proxy->gfselect];
1197         }
1198         break;
1199     case VIRTIO_PCI_COMMON_MSIX:
1200         val = vdev->config_vector;
1201         break;
1202     case VIRTIO_PCI_COMMON_NUMQ:
1203         for (i = 0; i < VIRTIO_QUEUE_MAX; ++i) {
1204             if (virtio_queue_get_num(vdev, i)) {
1205                 val = i + 1;
1206             }
1207         }
1208         break;
1209     case VIRTIO_PCI_COMMON_STATUS:
1210         val = vdev->status;
1211         break;
1212     case VIRTIO_PCI_COMMON_CFGGENERATION:
1213         val = vdev->generation;
1214         break;
1215     case VIRTIO_PCI_COMMON_Q_SELECT:
1216         val = vdev->queue_sel;
1217         break;
1218     case VIRTIO_PCI_COMMON_Q_SIZE:
1219         val = virtio_queue_get_num(vdev, vdev->queue_sel);
1220         break;
1221     case VIRTIO_PCI_COMMON_Q_MSIX:
1222         val = virtio_queue_vector(vdev, vdev->queue_sel);
1223         break;
1224     case VIRTIO_PCI_COMMON_Q_ENABLE:
1225         val = proxy->vqs[vdev->queue_sel].enabled;
1226         break;
1227     case VIRTIO_PCI_COMMON_Q_NOFF:
1228         /* Simply map queues in order */
1229         val = vdev->queue_sel;
1230         break;
1231     case VIRTIO_PCI_COMMON_Q_DESCLO:
1232         val = proxy->vqs[vdev->queue_sel].desc[0];
1233         break;
1234     case VIRTIO_PCI_COMMON_Q_DESCHI:
1235         val = proxy->vqs[vdev->queue_sel].desc[1];
1236         break;
1237     case VIRTIO_PCI_COMMON_Q_AVAILLO:
1238         val = proxy->vqs[vdev->queue_sel].avail[0];
1239         break;
1240     case VIRTIO_PCI_COMMON_Q_AVAILHI:
1241         val = proxy->vqs[vdev->queue_sel].avail[1];
1242         break;
1243     case VIRTIO_PCI_COMMON_Q_USEDLO:
1244         val = proxy->vqs[vdev->queue_sel].used[0];
1245         break;
1246     case VIRTIO_PCI_COMMON_Q_USEDHI:
1247         val = proxy->vqs[vdev->queue_sel].used[1];
1248         break;
1249     default:
1250         val = 0;
1251     }
1252 
1253     return val;
1254 }
1255 
1256 static void virtio_pci_common_write(void *opaque, hwaddr addr,
1257                                     uint64_t val, unsigned size)
1258 {
1259     VirtIOPCIProxy *proxy = opaque;
1260     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1261 
1262     if (vdev == NULL) {
1263         return;
1264     }
1265 
1266     switch (addr) {
1267     case VIRTIO_PCI_COMMON_DFSELECT:
1268         proxy->dfselect = val;
1269         break;
1270     case VIRTIO_PCI_COMMON_GFSELECT:
1271         proxy->gfselect = val;
1272         break;
1273     case VIRTIO_PCI_COMMON_GF:
1274         if (proxy->gfselect < ARRAY_SIZE(proxy->guest_features)) {
1275             proxy->guest_features[proxy->gfselect] = val;
1276             virtio_set_features(vdev,
1277                                 (((uint64_t)proxy->guest_features[1]) << 32) |
1278                                 proxy->guest_features[0]);
1279         }
1280         break;
1281     case VIRTIO_PCI_COMMON_MSIX:
1282         msix_vector_unuse(&proxy->pci_dev, vdev->config_vector);
1283         /* Make it possible for guest to discover an error took place. */
1284         if (msix_vector_use(&proxy->pci_dev, val) < 0) {
1285             val = VIRTIO_NO_VECTOR;
1286         }
1287         vdev->config_vector = val;
1288         break;
1289     case VIRTIO_PCI_COMMON_STATUS:
1290         if (!(val & VIRTIO_CONFIG_S_DRIVER_OK)) {
1291             virtio_pci_stop_ioeventfd(proxy);
1292         }
1293 
1294         virtio_set_status(vdev, val & 0xFF);
1295 
1296         if (val & VIRTIO_CONFIG_S_DRIVER_OK) {
1297             virtio_pci_start_ioeventfd(proxy);
1298         }
1299 
1300         if (vdev->status == 0) {
1301             virtio_pci_reset(DEVICE(proxy));
1302         }
1303 
1304         break;
1305     case VIRTIO_PCI_COMMON_Q_SELECT:
1306         if (val < VIRTIO_QUEUE_MAX) {
1307             vdev->queue_sel = val;
1308         }
1309         break;
1310     case VIRTIO_PCI_COMMON_Q_SIZE:
1311         proxy->vqs[vdev->queue_sel].num = val;
1312         virtio_queue_set_num(vdev, vdev->queue_sel,
1313                              proxy->vqs[vdev->queue_sel].num);
1314         break;
1315     case VIRTIO_PCI_COMMON_Q_MSIX:
1316         msix_vector_unuse(&proxy->pci_dev,
1317                           virtio_queue_vector(vdev, vdev->queue_sel));
1318         /* Make it possible for guest to discover an error took place. */
1319         if (msix_vector_use(&proxy->pci_dev, val) < 0) {
1320             val = VIRTIO_NO_VECTOR;
1321         }
1322         virtio_queue_set_vector(vdev, vdev->queue_sel, val);
1323         break;
1324     case VIRTIO_PCI_COMMON_Q_ENABLE:
1325         if (val == 1) {
1326             virtio_queue_set_num(vdev, vdev->queue_sel,
1327                                  proxy->vqs[vdev->queue_sel].num);
1328             virtio_queue_set_rings(vdev, vdev->queue_sel,
1329                        ((uint64_t)proxy->vqs[vdev->queue_sel].desc[1]) << 32 |
1330                        proxy->vqs[vdev->queue_sel].desc[0],
1331                        ((uint64_t)proxy->vqs[vdev->queue_sel].avail[1]) << 32 |
1332                        proxy->vqs[vdev->queue_sel].avail[0],
1333                        ((uint64_t)proxy->vqs[vdev->queue_sel].used[1]) << 32 |
1334                        proxy->vqs[vdev->queue_sel].used[0]);
1335             proxy->vqs[vdev->queue_sel].enabled = 1;
1336         } else {
1337             virtio_error(vdev, "wrong value for queue_enable %"PRIx64, val);
1338         }
1339         break;
1340     case VIRTIO_PCI_COMMON_Q_DESCLO:
1341         proxy->vqs[vdev->queue_sel].desc[0] = val;
1342         break;
1343     case VIRTIO_PCI_COMMON_Q_DESCHI:
1344         proxy->vqs[vdev->queue_sel].desc[1] = val;
1345         break;
1346     case VIRTIO_PCI_COMMON_Q_AVAILLO:
1347         proxy->vqs[vdev->queue_sel].avail[0] = val;
1348         break;
1349     case VIRTIO_PCI_COMMON_Q_AVAILHI:
1350         proxy->vqs[vdev->queue_sel].avail[1] = val;
1351         break;
1352     case VIRTIO_PCI_COMMON_Q_USEDLO:
1353         proxy->vqs[vdev->queue_sel].used[0] = val;
1354         break;
1355     case VIRTIO_PCI_COMMON_Q_USEDHI:
1356         proxy->vqs[vdev->queue_sel].used[1] = val;
1357         break;
1358     default:
1359         break;
1360     }
1361 }
1362 
1363 
1364 static uint64_t virtio_pci_notify_read(void *opaque, hwaddr addr,
1365                                        unsigned size)
1366 {
1367     VirtIOPCIProxy *proxy = opaque;
1368     if (virtio_bus_get_device(&proxy->bus) == NULL) {
1369         return UINT64_MAX;
1370     }
1371 
1372     return 0;
1373 }
1374 
1375 static void virtio_pci_notify_write(void *opaque, hwaddr addr,
1376                                     uint64_t val, unsigned size)
1377 {
1378     VirtIOPCIProxy *proxy = opaque;
1379     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1380 
1381     unsigned queue = addr / virtio_pci_queue_mem_mult(proxy);
1382 
1383     if (vdev != NULL && queue < VIRTIO_QUEUE_MAX) {
1384         trace_virtio_pci_notify_write(addr, val, size);
1385         virtio_queue_notify(vdev, queue);
1386     }
1387 }
1388 
1389 static void virtio_pci_notify_write_pio(void *opaque, hwaddr addr,
1390                                         uint64_t val, unsigned size)
1391 {
1392     VirtIOPCIProxy *proxy = opaque;
1393     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1394 
1395     unsigned queue = val;
1396 
1397     if (vdev != NULL && queue < VIRTIO_QUEUE_MAX) {
1398         trace_virtio_pci_notify_write_pio(addr, val, size);
1399         virtio_queue_notify(vdev, queue);
1400     }
1401 }
1402 
1403 static uint64_t virtio_pci_isr_read(void *opaque, hwaddr addr,
1404                                     unsigned size)
1405 {
1406     VirtIOPCIProxy *proxy = opaque;
1407     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1408     uint64_t val;
1409 
1410     if (vdev == NULL) {
1411         return UINT64_MAX;
1412     }
1413 
1414     val = qatomic_xchg(&vdev->isr, 0);
1415     pci_irq_deassert(&proxy->pci_dev);
1416     return val;
1417 }
1418 
1419 static void virtio_pci_isr_write(void *opaque, hwaddr addr,
1420                                  uint64_t val, unsigned size)
1421 {
1422 }
1423 
1424 static uint64_t virtio_pci_device_read(void *opaque, hwaddr addr,
1425                                        unsigned size)
1426 {
1427     VirtIOPCIProxy *proxy = opaque;
1428     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1429     uint64_t val;
1430 
1431     if (vdev == NULL) {
1432         return UINT64_MAX;
1433     }
1434 
1435     switch (size) {
1436     case 1:
1437         val = virtio_config_modern_readb(vdev, addr);
1438         break;
1439     case 2:
1440         val = virtio_config_modern_readw(vdev, addr);
1441         break;
1442     case 4:
1443         val = virtio_config_modern_readl(vdev, addr);
1444         break;
1445     default:
1446         val = 0;
1447         break;
1448     }
1449     return val;
1450 }
1451 
1452 static void virtio_pci_device_write(void *opaque, hwaddr addr,
1453                                     uint64_t val, unsigned size)
1454 {
1455     VirtIOPCIProxy *proxy = opaque;
1456     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1457 
1458     if (vdev == NULL) {
1459         return;
1460     }
1461 
1462     switch (size) {
1463     case 1:
1464         virtio_config_modern_writeb(vdev, addr, val);
1465         break;
1466     case 2:
1467         virtio_config_modern_writew(vdev, addr, val);
1468         break;
1469     case 4:
1470         virtio_config_modern_writel(vdev, addr, val);
1471         break;
1472     }
1473 }
1474 
1475 static void virtio_pci_modern_regions_init(VirtIOPCIProxy *proxy,
1476                                            const char *vdev_name)
1477 {
1478     static const MemoryRegionOps common_ops = {
1479         .read = virtio_pci_common_read,
1480         .write = virtio_pci_common_write,
1481         .impl = {
1482             .min_access_size = 1,
1483             .max_access_size = 4,
1484         },
1485         .endianness = DEVICE_LITTLE_ENDIAN,
1486     };
1487     static const MemoryRegionOps isr_ops = {
1488         .read = virtio_pci_isr_read,
1489         .write = virtio_pci_isr_write,
1490         .impl = {
1491             .min_access_size = 1,
1492             .max_access_size = 4,
1493         },
1494         .endianness = DEVICE_LITTLE_ENDIAN,
1495     };
1496     static const MemoryRegionOps device_ops = {
1497         .read = virtio_pci_device_read,
1498         .write = virtio_pci_device_write,
1499         .impl = {
1500             .min_access_size = 1,
1501             .max_access_size = 4,
1502         },
1503         .endianness = DEVICE_LITTLE_ENDIAN,
1504     };
1505     static const MemoryRegionOps notify_ops = {
1506         .read = virtio_pci_notify_read,
1507         .write = virtio_pci_notify_write,
1508         .impl = {
1509             .min_access_size = 1,
1510             .max_access_size = 4,
1511         },
1512         .endianness = DEVICE_LITTLE_ENDIAN,
1513     };
1514     static const MemoryRegionOps notify_pio_ops = {
1515         .read = virtio_pci_notify_read,
1516         .write = virtio_pci_notify_write_pio,
1517         .impl = {
1518             .min_access_size = 1,
1519             .max_access_size = 4,
1520         },
1521         .endianness = DEVICE_LITTLE_ENDIAN,
1522     };
1523     g_autoptr(GString) name = g_string_new(NULL);
1524 
1525     g_string_printf(name, "virtio-pci-common-%s", vdev_name);
1526     memory_region_init_io(&proxy->common.mr, OBJECT(proxy),
1527                           &common_ops,
1528                           proxy,
1529                           name->str,
1530                           proxy->common.size);
1531 
1532     g_string_printf(name, "virtio-pci-isr-%s", vdev_name);
1533     memory_region_init_io(&proxy->isr.mr, OBJECT(proxy),
1534                           &isr_ops,
1535                           proxy,
1536                           name->str,
1537                           proxy->isr.size);
1538 
1539     g_string_printf(name, "virtio-pci-device-%s", vdev_name);
1540     memory_region_init_io(&proxy->device.mr, OBJECT(proxy),
1541                           &device_ops,
1542                           proxy,
1543                           name->str,
1544                           proxy->device.size);
1545 
1546     g_string_printf(name, "virtio-pci-notify-%s", vdev_name);
1547     memory_region_init_io(&proxy->notify.mr, OBJECT(proxy),
1548                           &notify_ops,
1549                           proxy,
1550                           name->str,
1551                           proxy->notify.size);
1552 
1553     g_string_printf(name, "virtio-pci-notify-pio-%s", vdev_name);
1554     memory_region_init_io(&proxy->notify_pio.mr, OBJECT(proxy),
1555                           &notify_pio_ops,
1556                           proxy,
1557                           name->str,
1558                           proxy->notify_pio.size);
1559 }
1560 
1561 static void virtio_pci_modern_region_map(VirtIOPCIProxy *proxy,
1562                                          VirtIOPCIRegion *region,
1563                                          struct virtio_pci_cap *cap,
1564                                          MemoryRegion *mr,
1565                                          uint8_t bar)
1566 {
1567     memory_region_add_subregion(mr, region->offset, &region->mr);
1568 
1569     cap->cfg_type = region->type;
1570     cap->bar = bar;
1571     cap->offset = cpu_to_le32(region->offset);
1572     cap->length = cpu_to_le32(region->size);
1573     virtio_pci_add_mem_cap(proxy, cap);
1574 
1575 }
1576 
1577 static void virtio_pci_modern_mem_region_map(VirtIOPCIProxy *proxy,
1578                                              VirtIOPCIRegion *region,
1579                                              struct virtio_pci_cap *cap)
1580 {
1581     virtio_pci_modern_region_map(proxy, region, cap,
1582                                  &proxy->modern_bar, proxy->modern_mem_bar_idx);
1583 }
1584 
1585 static void virtio_pci_modern_io_region_map(VirtIOPCIProxy *proxy,
1586                                             VirtIOPCIRegion *region,
1587                                             struct virtio_pci_cap *cap)
1588 {
1589     virtio_pci_modern_region_map(proxy, region, cap,
1590                                  &proxy->io_bar, proxy->modern_io_bar_idx);
1591 }
1592 
1593 static void virtio_pci_modern_mem_region_unmap(VirtIOPCIProxy *proxy,
1594                                                VirtIOPCIRegion *region)
1595 {
1596     memory_region_del_subregion(&proxy->modern_bar,
1597                                 &region->mr);
1598 }
1599 
1600 static void virtio_pci_modern_io_region_unmap(VirtIOPCIProxy *proxy,
1601                                               VirtIOPCIRegion *region)
1602 {
1603     memory_region_del_subregion(&proxy->io_bar,
1604                                 &region->mr);
1605 }
1606 
1607 static void virtio_pci_pre_plugged(DeviceState *d, Error **errp)
1608 {
1609     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1610     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1611 
1612     if (virtio_pci_modern(proxy)) {
1613         virtio_add_feature(&vdev->host_features, VIRTIO_F_VERSION_1);
1614     }
1615 
1616     virtio_add_feature(&vdev->host_features, VIRTIO_F_BAD_FEATURE);
1617 }
1618 
1619 /* This is called by virtio-bus just after the device is plugged. */
1620 static void virtio_pci_device_plugged(DeviceState *d, Error **errp)
1621 {
1622     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1623     VirtioBusState *bus = &proxy->bus;
1624     bool legacy = virtio_pci_legacy(proxy);
1625     bool modern;
1626     bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;
1627     uint8_t *config;
1628     uint32_t size;
1629     VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);
1630 
1631     /*
1632      * Virtio capabilities present without
1633      * VIRTIO_F_VERSION_1 confuses guests
1634      */
1635     if (!proxy->ignore_backend_features &&
1636             !virtio_has_feature(vdev->host_features, VIRTIO_F_VERSION_1)) {
1637         virtio_pci_disable_modern(proxy);
1638 
1639         if (!legacy) {
1640             error_setg(errp, "Device doesn't support modern mode, and legacy"
1641                              " mode is disabled");
1642             error_append_hint(errp, "Set disable-legacy to off\n");
1643 
1644             return;
1645         }
1646     }
1647 
1648     modern = virtio_pci_modern(proxy);
1649 
1650     config = proxy->pci_dev.config;
1651     if (proxy->class_code) {
1652         pci_config_set_class(config, proxy->class_code);
1653     }
1654 
1655     if (legacy) {
1656         if (!virtio_legacy_allowed(vdev)) {
1657             /*
1658              * To avoid migration issues, we allow legacy mode when legacy
1659              * check is disabled in the old machine types (< 5.1).
1660              */
1661             if (virtio_legacy_check_disabled(vdev)) {
1662                 warn_report("device is modern-only, but for backward "
1663                             "compatibility legacy is allowed");
1664             } else {
1665                 error_setg(errp,
1666                            "device is modern-only, use disable-legacy=on");
1667                 return;
1668             }
1669         }
1670         if (virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM)) {
1671             error_setg(errp, "VIRTIO_F_IOMMU_PLATFORM was supported by"
1672                        " neither legacy nor transitional device");
1673             return ;
1674         }
1675         /*
1676          * Legacy and transitional devices use specific subsystem IDs.
1677          * Note that the subsystem vendor ID (config + PCI_SUBSYSTEM_VENDOR_ID)
1678          * is set to PCI_SUBVENDOR_ID_REDHAT_QUMRANET by default.
1679          */
1680         pci_set_word(config + PCI_SUBSYSTEM_ID, virtio_bus_get_vdev_id(bus));
1681     } else {
1682         /* pure virtio-1.0 */
1683         pci_set_word(config + PCI_VENDOR_ID,
1684                      PCI_VENDOR_ID_REDHAT_QUMRANET);
1685         pci_set_word(config + PCI_DEVICE_ID,
1686                      0x1040 + virtio_bus_get_vdev_id(bus));
1687         pci_config_set_revision(config, 1);
1688     }
1689     config[PCI_INTERRUPT_PIN] = 1;
1690 
1691 
1692     if (modern) {
1693         struct virtio_pci_cap cap = {
1694             .cap_len = sizeof cap,
1695         };
1696         struct virtio_pci_notify_cap notify = {
1697             .cap.cap_len = sizeof notify,
1698             .notify_off_multiplier =
1699                 cpu_to_le32(virtio_pci_queue_mem_mult(proxy)),
1700         };
1701         struct virtio_pci_cfg_cap cfg = {
1702             .cap.cap_len = sizeof cfg,
1703             .cap.cfg_type = VIRTIO_PCI_CAP_PCI_CFG,
1704         };
1705         struct virtio_pci_notify_cap notify_pio = {
1706             .cap.cap_len = sizeof notify,
1707             .notify_off_multiplier = cpu_to_le32(0x0),
1708         };
1709 
1710         struct virtio_pci_cfg_cap *cfg_mask;
1711 
1712         virtio_pci_modern_regions_init(proxy, vdev->name);
1713 
1714         virtio_pci_modern_mem_region_map(proxy, &proxy->common, &cap);
1715         virtio_pci_modern_mem_region_map(proxy, &proxy->isr, &cap);
1716         virtio_pci_modern_mem_region_map(proxy, &proxy->device, &cap);
1717         virtio_pci_modern_mem_region_map(proxy, &proxy->notify, &notify.cap);
1718 
1719         if (modern_pio) {
1720             memory_region_init(&proxy->io_bar, OBJECT(proxy),
1721                                "virtio-pci-io", 0x4);
1722 
1723             pci_register_bar(&proxy->pci_dev, proxy->modern_io_bar_idx,
1724                              PCI_BASE_ADDRESS_SPACE_IO, &proxy->io_bar);
1725 
1726             virtio_pci_modern_io_region_map(proxy, &proxy->notify_pio,
1727                                             &notify_pio.cap);
1728         }
1729 
1730         pci_register_bar(&proxy->pci_dev, proxy->modern_mem_bar_idx,
1731                          PCI_BASE_ADDRESS_SPACE_MEMORY |
1732                          PCI_BASE_ADDRESS_MEM_PREFETCH |
1733                          PCI_BASE_ADDRESS_MEM_TYPE_64,
1734                          &proxy->modern_bar);
1735 
1736         proxy->config_cap = virtio_pci_add_mem_cap(proxy, &cfg.cap);
1737         cfg_mask = (void *)(proxy->pci_dev.wmask + proxy->config_cap);
1738         pci_set_byte(&cfg_mask->cap.bar, ~0x0);
1739         pci_set_long((uint8_t *)&cfg_mask->cap.offset, ~0x0);
1740         pci_set_long((uint8_t *)&cfg_mask->cap.length, ~0x0);
1741         pci_set_long(cfg_mask->pci_cfg_data, ~0x0);
1742     }
1743 
1744     if (proxy->nvectors) {
1745         int err = msix_init_exclusive_bar(&proxy->pci_dev, proxy->nvectors,
1746                                           proxy->msix_bar_idx, NULL);
1747         if (err) {
1748             /* Notice when a system that supports MSIx can't initialize it */
1749             if (err != -ENOTSUP) {
1750                 warn_report("unable to init msix vectors to %" PRIu32,
1751                             proxy->nvectors);
1752             }
1753             proxy->nvectors = 0;
1754         }
1755     }
1756 
1757     proxy->pci_dev.config_write = virtio_write_config;
1758     proxy->pci_dev.config_read = virtio_read_config;
1759 
1760     if (legacy) {
1761         size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev)
1762             + virtio_bus_get_vdev_config_len(bus);
1763         size = pow2ceil(size);
1764 
1765         memory_region_init_io(&proxy->bar, OBJECT(proxy),
1766                               &virtio_pci_config_ops,
1767                               proxy, "virtio-pci", size);
1768 
1769         pci_register_bar(&proxy->pci_dev, proxy->legacy_io_bar_idx,
1770                          PCI_BASE_ADDRESS_SPACE_IO, &proxy->bar);
1771     }
1772 }
1773 
1774 static void virtio_pci_device_unplugged(DeviceState *d)
1775 {
1776     VirtIOPCIProxy *proxy = VIRTIO_PCI(d);
1777     bool modern = virtio_pci_modern(proxy);
1778     bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;
1779 
1780     virtio_pci_stop_ioeventfd(proxy);
1781 
1782     if (modern) {
1783         virtio_pci_modern_mem_region_unmap(proxy, &proxy->common);
1784         virtio_pci_modern_mem_region_unmap(proxy, &proxy->isr);
1785         virtio_pci_modern_mem_region_unmap(proxy, &proxy->device);
1786         virtio_pci_modern_mem_region_unmap(proxy, &proxy->notify);
1787         if (modern_pio) {
1788             virtio_pci_modern_io_region_unmap(proxy, &proxy->notify_pio);
1789         }
1790     }
1791 }
1792 
1793 static void virtio_pci_realize(PCIDevice *pci_dev, Error **errp)
1794 {
1795     VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev);
1796     VirtioPCIClass *k = VIRTIO_PCI_GET_CLASS(pci_dev);
1797     bool pcie_port = pci_bus_is_express(pci_get_bus(pci_dev)) &&
1798                      !pci_bus_is_root(pci_get_bus(pci_dev));
1799 
1800     if (kvm_enabled() && !kvm_has_many_ioeventfds()) {
1801         proxy->flags &= ~VIRTIO_PCI_FLAG_USE_IOEVENTFD;
1802     }
1803 
1804     /* fd-based ioevents can't be synchronized in record/replay */
1805     if (replay_mode != REPLAY_MODE_NONE) {
1806         proxy->flags &= ~VIRTIO_PCI_FLAG_USE_IOEVENTFD;
1807     }
1808 
1809     /*
1810      * virtio pci bar layout used by default.
1811      * subclasses can re-arrange things if needed.
1812      *
1813      *   region 0   --  virtio legacy io bar
1814      *   region 1   --  msi-x bar
1815      *   region 2   --  virtio modern io bar (off by default)
1816      *   region 4+5 --  virtio modern memory (64bit) bar
1817      *
1818      */
1819     proxy->legacy_io_bar_idx  = 0;
1820     proxy->msix_bar_idx       = 1;
1821     proxy->modern_io_bar_idx  = 2;
1822     proxy->modern_mem_bar_idx = 4;
1823 
1824     proxy->common.offset = 0x0;
1825     proxy->common.size = 0x1000;
1826     proxy->common.type = VIRTIO_PCI_CAP_COMMON_CFG;
1827 
1828     proxy->isr.offset = 0x1000;
1829     proxy->isr.size = 0x1000;
1830     proxy->isr.type = VIRTIO_PCI_CAP_ISR_CFG;
1831 
1832     proxy->device.offset = 0x2000;
1833     proxy->device.size = 0x1000;
1834     proxy->device.type = VIRTIO_PCI_CAP_DEVICE_CFG;
1835 
1836     proxy->notify.offset = 0x3000;
1837     proxy->notify.size = virtio_pci_queue_mem_mult(proxy) * VIRTIO_QUEUE_MAX;
1838     proxy->notify.type = VIRTIO_PCI_CAP_NOTIFY_CFG;
1839 
1840     proxy->notify_pio.offset = 0x0;
1841     proxy->notify_pio.size = 0x4;
1842     proxy->notify_pio.type = VIRTIO_PCI_CAP_NOTIFY_CFG;
1843 
1844     /* subclasses can enforce modern, so do this unconditionally */
1845     memory_region_init(&proxy->modern_bar, OBJECT(proxy), "virtio-pci",
1846                        /* PCI BAR regions must be powers of 2 */
1847                        pow2ceil(proxy->notify.offset + proxy->notify.size));
1848 
1849     if (proxy->disable_legacy == ON_OFF_AUTO_AUTO) {
1850         proxy->disable_legacy = pcie_port ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
1851     }
1852 
1853     if (!virtio_pci_modern(proxy) && !virtio_pci_legacy(proxy)) {
1854         error_setg(errp, "device cannot work as neither modern nor legacy mode"
1855                    " is enabled");
1856         error_append_hint(errp, "Set either disable-modern or disable-legacy"
1857                           " to off\n");
1858         return;
1859     }
1860 
1861     if (pcie_port && pci_is_express(pci_dev)) {
1862         int pos;
1863         uint16_t last_pcie_cap_offset = PCI_CONFIG_SPACE_SIZE;
1864 
1865         pos = pcie_endpoint_cap_init(pci_dev, 0);
1866         assert(pos > 0);
1867 
1868         pos = pci_add_capability(pci_dev, PCI_CAP_ID_PM, 0,
1869                                  PCI_PM_SIZEOF, errp);
1870         if (pos < 0) {
1871             return;
1872         }
1873 
1874         pci_dev->exp.pm_cap = pos;
1875 
1876         /*
1877          * Indicates that this function complies with revision 1.2 of the
1878          * PCI Power Management Interface Specification.
1879          */
1880         pci_set_word(pci_dev->config + pos + PCI_PM_PMC, 0x3);
1881 
1882         if (proxy->flags & VIRTIO_PCI_FLAG_AER) {
1883             pcie_aer_init(pci_dev, PCI_ERR_VER, last_pcie_cap_offset,
1884                           PCI_ERR_SIZEOF, NULL);
1885             last_pcie_cap_offset += PCI_ERR_SIZEOF;
1886         }
1887 
1888         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_DEVERR) {
1889             /* Init error enabling flags */
1890             pcie_cap_deverr_init(pci_dev);
1891         }
1892 
1893         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_LNKCTL) {
1894             /* Init Link Control Register */
1895             pcie_cap_lnkctl_init(pci_dev);
1896         }
1897 
1898         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_PM) {
1899             /* Init Power Management Control Register */
1900             pci_set_word(pci_dev->wmask + pos + PCI_PM_CTRL,
1901                          PCI_PM_CTRL_STATE_MASK);
1902         }
1903 
1904         if (proxy->flags & VIRTIO_PCI_FLAG_ATS) {
1905             pcie_ats_init(pci_dev, last_pcie_cap_offset,
1906                           proxy->flags & VIRTIO_PCI_FLAG_ATS_PAGE_ALIGNED);
1907             last_pcie_cap_offset += PCI_EXT_CAP_ATS_SIZEOF;
1908         }
1909 
1910         if (proxy->flags & VIRTIO_PCI_FLAG_INIT_FLR) {
1911             /* Set Function Level Reset capability bit */
1912             pcie_cap_flr_init(pci_dev);
1913         }
1914     } else {
1915         /*
1916          * make future invocations of pci_is_express() return false
1917          * and pci_config_size() return PCI_CONFIG_SPACE_SIZE.
1918          */
1919         pci_dev->cap_present &= ~QEMU_PCI_CAP_EXPRESS;
1920     }
1921 
1922     virtio_pci_bus_new(&proxy->bus, sizeof(proxy->bus), proxy);
1923     if (k->realize) {
1924         k->realize(proxy, errp);
1925     }
1926 }
1927 
1928 static void virtio_pci_exit(PCIDevice *pci_dev)
1929 {
1930     VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev);
1931     bool pcie_port = pci_bus_is_express(pci_get_bus(pci_dev)) &&
1932                      !pci_bus_is_root(pci_get_bus(pci_dev));
1933 
1934     msix_uninit_exclusive_bar(pci_dev);
1935     if (proxy->flags & VIRTIO_PCI_FLAG_AER && pcie_port &&
1936         pci_is_express(pci_dev)) {
1937         pcie_aer_exit(pci_dev);
1938     }
1939 }
1940 
1941 static void virtio_pci_reset(DeviceState *qdev)
1942 {
1943     VirtIOPCIProxy *proxy = VIRTIO_PCI(qdev);
1944     VirtioBusState *bus = VIRTIO_BUS(&proxy->bus);
1945     PCIDevice *dev = PCI_DEVICE(qdev);
1946     int i;
1947 
1948     virtio_pci_stop_ioeventfd(proxy);
1949     virtio_bus_reset(bus);
1950     msix_unuse_all_vectors(&proxy->pci_dev);
1951 
1952     for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1953         proxy->vqs[i].enabled = 0;
1954         proxy->vqs[i].num = 0;
1955         proxy->vqs[i].desc[0] = proxy->vqs[i].desc[1] = 0;
1956         proxy->vqs[i].avail[0] = proxy->vqs[i].avail[1] = 0;
1957         proxy->vqs[i].used[0] = proxy->vqs[i].used[1] = 0;
1958     }
1959 
1960     if (pci_is_express(dev)) {
1961         pcie_cap_deverr_reset(dev);
1962         pcie_cap_lnkctl_reset(dev);
1963 
1964         pci_set_word(dev->config + dev->exp.pm_cap + PCI_PM_CTRL, 0);
1965     }
1966 }
1967 
1968 static Property virtio_pci_properties[] = {
1969     DEFINE_PROP_BIT("virtio-pci-bus-master-bug-migration", VirtIOPCIProxy, flags,
1970                     VIRTIO_PCI_FLAG_BUS_MASTER_BUG_MIGRATION_BIT, false),
1971     DEFINE_PROP_BIT("migrate-extra", VirtIOPCIProxy, flags,
1972                     VIRTIO_PCI_FLAG_MIGRATE_EXTRA_BIT, true),
1973     DEFINE_PROP_BIT("modern-pio-notify", VirtIOPCIProxy, flags,
1974                     VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY_BIT, false),
1975     DEFINE_PROP_BIT("x-disable-pcie", VirtIOPCIProxy, flags,
1976                     VIRTIO_PCI_FLAG_DISABLE_PCIE_BIT, false),
1977     DEFINE_PROP_BIT("page-per-vq", VirtIOPCIProxy, flags,
1978                     VIRTIO_PCI_FLAG_PAGE_PER_VQ_BIT, false),
1979     DEFINE_PROP_BOOL("x-ignore-backend-features", VirtIOPCIProxy,
1980                      ignore_backend_features, false),
1981     DEFINE_PROP_BIT("ats", VirtIOPCIProxy, flags,
1982                     VIRTIO_PCI_FLAG_ATS_BIT, false),
1983     DEFINE_PROP_BIT("x-ats-page-aligned", VirtIOPCIProxy, flags,
1984                     VIRTIO_PCI_FLAG_ATS_PAGE_ALIGNED_BIT, true),
1985     DEFINE_PROP_BIT("x-pcie-deverr-init", VirtIOPCIProxy, flags,
1986                     VIRTIO_PCI_FLAG_INIT_DEVERR_BIT, true),
1987     DEFINE_PROP_BIT("x-pcie-lnkctl-init", VirtIOPCIProxy, flags,
1988                     VIRTIO_PCI_FLAG_INIT_LNKCTL_BIT, true),
1989     DEFINE_PROP_BIT("x-pcie-pm-init", VirtIOPCIProxy, flags,
1990                     VIRTIO_PCI_FLAG_INIT_PM_BIT, true),
1991     DEFINE_PROP_BIT("x-pcie-flr-init", VirtIOPCIProxy, flags,
1992                     VIRTIO_PCI_FLAG_INIT_FLR_BIT, true),
1993     DEFINE_PROP_BIT("aer", VirtIOPCIProxy, flags,
1994                     VIRTIO_PCI_FLAG_AER_BIT, false),
1995     DEFINE_PROP_END_OF_LIST(),
1996 };
1997 
1998 static void virtio_pci_dc_realize(DeviceState *qdev, Error **errp)
1999 {
2000     VirtioPCIClass *vpciklass = VIRTIO_PCI_GET_CLASS(qdev);
2001     VirtIOPCIProxy *proxy = VIRTIO_PCI(qdev);
2002     PCIDevice *pci_dev = &proxy->pci_dev;
2003 
2004     if (!(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_PCIE) &&
2005         virtio_pci_modern(proxy)) {
2006         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2007     }
2008 
2009     vpciklass->parent_dc_realize(qdev, errp);
2010 }
2011 
2012 static void virtio_pci_class_init(ObjectClass *klass, void *data)
2013 {
2014     DeviceClass *dc = DEVICE_CLASS(klass);
2015     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2016     VirtioPCIClass *vpciklass = VIRTIO_PCI_CLASS(klass);
2017 
2018     device_class_set_props(dc, virtio_pci_properties);
2019     k->realize = virtio_pci_realize;
2020     k->exit = virtio_pci_exit;
2021     k->vendor_id = PCI_VENDOR_ID_REDHAT_QUMRANET;
2022     k->revision = VIRTIO_PCI_ABI_VERSION;
2023     k->class_id = PCI_CLASS_OTHERS;
2024     device_class_set_parent_realize(dc, virtio_pci_dc_realize,
2025                                     &vpciklass->parent_dc_realize);
2026     dc->reset = virtio_pci_reset;
2027 }
2028 
2029 static const TypeInfo virtio_pci_info = {
2030     .name          = TYPE_VIRTIO_PCI,
2031     .parent        = TYPE_PCI_DEVICE,
2032     .instance_size = sizeof(VirtIOPCIProxy),
2033     .class_init    = virtio_pci_class_init,
2034     .class_size    = sizeof(VirtioPCIClass),
2035     .abstract      = true,
2036 };
2037 
2038 static Property virtio_pci_generic_properties[] = {
2039     DEFINE_PROP_ON_OFF_AUTO("disable-legacy", VirtIOPCIProxy, disable_legacy,
2040                             ON_OFF_AUTO_AUTO),
2041     DEFINE_PROP_BOOL("disable-modern", VirtIOPCIProxy, disable_modern, false),
2042     DEFINE_PROP_END_OF_LIST(),
2043 };
2044 
2045 static void virtio_pci_base_class_init(ObjectClass *klass, void *data)
2046 {
2047     const VirtioPCIDeviceTypeInfo *t = data;
2048     if (t->class_init) {
2049         t->class_init(klass, NULL);
2050     }
2051 }
2052 
2053 static void virtio_pci_generic_class_init(ObjectClass *klass, void *data)
2054 {
2055     DeviceClass *dc = DEVICE_CLASS(klass);
2056 
2057     device_class_set_props(dc, virtio_pci_generic_properties);
2058 }
2059 
2060 static void virtio_pci_transitional_instance_init(Object *obj)
2061 {
2062     VirtIOPCIProxy *proxy = VIRTIO_PCI(obj);
2063 
2064     proxy->disable_legacy = ON_OFF_AUTO_OFF;
2065     proxy->disable_modern = false;
2066 }
2067 
2068 static void virtio_pci_non_transitional_instance_init(Object *obj)
2069 {
2070     VirtIOPCIProxy *proxy = VIRTIO_PCI(obj);
2071 
2072     proxy->disable_legacy = ON_OFF_AUTO_ON;
2073     proxy->disable_modern = false;
2074 }
2075 
2076 void virtio_pci_types_register(const VirtioPCIDeviceTypeInfo *t)
2077 {
2078     char *base_name = NULL;
2079     TypeInfo base_type_info = {
2080         .name          = t->base_name,
2081         .parent        = t->parent ? t->parent : TYPE_VIRTIO_PCI,
2082         .instance_size = t->instance_size,
2083         .instance_init = t->instance_init,
2084         .class_size    = t->class_size,
2085         .abstract      = true,
2086         .interfaces    = t->interfaces,
2087     };
2088     TypeInfo generic_type_info = {
2089         .name = t->generic_name,
2090         .parent = base_type_info.name,
2091         .class_init = virtio_pci_generic_class_init,
2092         .interfaces = (InterfaceInfo[]) {
2093             { INTERFACE_PCIE_DEVICE },
2094             { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2095             { }
2096         },
2097     };
2098 
2099     if (!base_type_info.name) {
2100         /* No base type -> register a single generic device type */
2101         /* use intermediate %s-base-type to add generic device props */
2102         base_name = g_strdup_printf("%s-base-type", t->generic_name);
2103         base_type_info.name = base_name;
2104         base_type_info.class_init = virtio_pci_generic_class_init;
2105 
2106         generic_type_info.parent = base_name;
2107         generic_type_info.class_init = virtio_pci_base_class_init;
2108         generic_type_info.class_data = (void *)t;
2109 
2110         assert(!t->non_transitional_name);
2111         assert(!t->transitional_name);
2112     } else {
2113         base_type_info.class_init = virtio_pci_base_class_init;
2114         base_type_info.class_data = (void *)t;
2115     }
2116 
2117     type_register(&base_type_info);
2118     if (generic_type_info.name) {
2119         type_register(&generic_type_info);
2120     }
2121 
2122     if (t->non_transitional_name) {
2123         const TypeInfo non_transitional_type_info = {
2124             .name          = t->non_transitional_name,
2125             .parent        = base_type_info.name,
2126             .instance_init = virtio_pci_non_transitional_instance_init,
2127             .interfaces = (InterfaceInfo[]) {
2128                 { INTERFACE_PCIE_DEVICE },
2129                 { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2130                 { }
2131             },
2132         };
2133         type_register(&non_transitional_type_info);
2134     }
2135 
2136     if (t->transitional_name) {
2137         const TypeInfo transitional_type_info = {
2138             .name          = t->transitional_name,
2139             .parent        = base_type_info.name,
2140             .instance_init = virtio_pci_transitional_instance_init,
2141             .interfaces = (InterfaceInfo[]) {
2142                 /*
2143                  * Transitional virtio devices work only as Conventional PCI
2144                  * devices because they require PIO ports.
2145                  */
2146                 { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2147                 { }
2148             },
2149         };
2150         type_register(&transitional_type_info);
2151     }
2152     g_free(base_name);
2153 }
2154 
2155 unsigned virtio_pci_optimal_num_queues(unsigned fixed_queues)
2156 {
2157     /*
2158      * 1:1 vq to vCPU mapping is ideal because the same vCPU that submitted
2159      * virtqueue buffers can handle their completion. When a different vCPU
2160      * handles completion it may need to IPI the vCPU that submitted the
2161      * request and this adds overhead.
2162      *
2163      * Virtqueues consume guest RAM and MSI-X vectors. This is wasteful in
2164      * guests with very many vCPUs and a device that is only used by a few
2165      * vCPUs. Unfortunately optimizing that case requires manual pinning inside
2166      * the guest, so those users might as well manually set the number of
2167      * queues. There is no upper limit that can be applied automatically and
2168      * doing so arbitrarily would result in a sudden performance drop once the
2169      * threshold number of vCPUs is exceeded.
2170      */
2171     unsigned num_queues = current_machine->smp.cpus;
2172 
2173     /*
2174      * The maximum number of MSI-X vectors is PCI_MSIX_FLAGS_QSIZE + 1, but the
2175      * config change interrupt and the fixed virtqueues must be taken into
2176      * account too.
2177      */
2178     num_queues = MIN(num_queues, PCI_MSIX_FLAGS_QSIZE - fixed_queues);
2179 
2180     /*
2181      * There is a limit to how many virtqueues a device can have.
2182      */
2183     return MIN(num_queues, VIRTIO_QUEUE_MAX - fixed_queues);
2184 }
2185 
2186 /* virtio-pci-bus */
2187 
2188 static void virtio_pci_bus_new(VirtioBusState *bus, size_t bus_size,
2189                                VirtIOPCIProxy *dev)
2190 {
2191     DeviceState *qdev = DEVICE(dev);
2192     char virtio_bus_name[] = "virtio-bus";
2193 
2194     qbus_init(bus, bus_size, TYPE_VIRTIO_PCI_BUS, qdev, virtio_bus_name);
2195 }
2196 
2197 static void virtio_pci_bus_class_init(ObjectClass *klass, void *data)
2198 {
2199     BusClass *bus_class = BUS_CLASS(klass);
2200     VirtioBusClass *k = VIRTIO_BUS_CLASS(klass);
2201     bus_class->max_dev = 1;
2202     k->notify = virtio_pci_notify;
2203     k->save_config = virtio_pci_save_config;
2204     k->load_config = virtio_pci_load_config;
2205     k->save_queue = virtio_pci_save_queue;
2206     k->load_queue = virtio_pci_load_queue;
2207     k->save_extra_state = virtio_pci_save_extra_state;
2208     k->load_extra_state = virtio_pci_load_extra_state;
2209     k->has_extra_state = virtio_pci_has_extra_state;
2210     k->query_guest_notifiers = virtio_pci_query_guest_notifiers;
2211     k->set_guest_notifiers = virtio_pci_set_guest_notifiers;
2212     k->set_host_notifier_mr = virtio_pci_set_host_notifier_mr;
2213     k->vmstate_change = virtio_pci_vmstate_change;
2214     k->pre_plugged = virtio_pci_pre_plugged;
2215     k->device_plugged = virtio_pci_device_plugged;
2216     k->device_unplugged = virtio_pci_device_unplugged;
2217     k->query_nvectors = virtio_pci_query_nvectors;
2218     k->ioeventfd_enabled = virtio_pci_ioeventfd_enabled;
2219     k->ioeventfd_assign = virtio_pci_ioeventfd_assign;
2220     k->get_dma_as = virtio_pci_get_dma_as;
2221     k->iommu_enabled = virtio_pci_iommu_enabled;
2222     k->queue_enabled = virtio_pci_queue_enabled;
2223 }
2224 
2225 static const TypeInfo virtio_pci_bus_info = {
2226     .name          = TYPE_VIRTIO_PCI_BUS,
2227     .parent        = TYPE_VIRTIO_BUS,
2228     .instance_size = sizeof(VirtioPCIBusState),
2229     .class_size    = sizeof(VirtioPCIBusClass),
2230     .class_init    = virtio_pci_bus_class_init,
2231 };
2232 
2233 static void virtio_pci_register_types(void)
2234 {
2235     /* Base types: */
2236     type_register_static(&virtio_pci_bus_info);
2237     type_register_static(&virtio_pci_info);
2238 }
2239 
2240 type_init(virtio_pci_register_types)
2241 
2242