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