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