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