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