xref: /openbmc/qemu/hw/vfio/pci-quirks.c (revision 4cbb198e)
1 /*
2  * device quirks for PCI devices
3  *
4  * Copyright Red Hat, Inc. 2012-2015
5  *
6  * Authors:
7  *  Alex Williamson <alex.williamson@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  */
12 
13 #include "qemu/osdep.h"
14 #include "exec/memop.h"
15 #include "qemu/units.h"
16 #include "qemu/error-report.h"
17 #include "qemu/main-loop.h"
18 #include "qemu/module.h"
19 #include "qemu/range.h"
20 #include "qapi/error.h"
21 #include "qapi/visitor.h"
22 #include <sys/ioctl.h>
23 #include "hw/hw.h"
24 #include "hw/nvram/fw_cfg.h"
25 #include "hw/qdev-properties.h"
26 #include "pci.h"
27 #include "trace.h"
28 
29 /* Use uin32_t for vendor & device so PCI_ANY_ID expands and cannot match hw */
30 static bool vfio_pci_is(VFIOPCIDevice *vdev, uint32_t vendor, uint32_t device)
31 {
32     return (vendor == PCI_ANY_ID || vendor == vdev->vendor_id) &&
33            (device == PCI_ANY_ID || device == vdev->device_id);
34 }
35 
36 static bool vfio_is_vga(VFIOPCIDevice *vdev)
37 {
38     PCIDevice *pdev = &vdev->pdev;
39     uint16_t class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);
40 
41     return class == PCI_CLASS_DISPLAY_VGA;
42 }
43 
44 /*
45  * List of device ids/vendor ids for which to disable
46  * option rom loading. This avoids the guest hangs during rom
47  * execution as noticed with the BCM 57810 card for lack of a
48  * more better way to handle such issues.
49  * The  user can still override by specifying a romfile or
50  * rombar=1.
51  * Please see https://bugs.launchpad.net/qemu/+bug/1284874
52  * for an analysis of the 57810 card hang. When adding
53  * a new vendor id/device id combination below, please also add
54  * your card/environment details and information that could
55  * help in debugging to the bug tracking this issue
56  */
57 static const struct {
58     uint32_t vendor;
59     uint32_t device;
60 } romblacklist[] = {
61     { 0x14e4, 0x168e }, /* Broadcom BCM 57810 */
62 };
63 
64 bool vfio_blacklist_opt_rom(VFIOPCIDevice *vdev)
65 {
66     int i;
67 
68     for (i = 0 ; i < ARRAY_SIZE(romblacklist); i++) {
69         if (vfio_pci_is(vdev, romblacklist[i].vendor, romblacklist[i].device)) {
70             trace_vfio_quirk_rom_blacklisted(vdev->vbasedev.name,
71                                              romblacklist[i].vendor,
72                                              romblacklist[i].device);
73             return true;
74         }
75     }
76     return false;
77 }
78 
79 /*
80  * Device specific region quirks (mostly backdoors to PCI config space)
81  */
82 
83 /*
84  * The generic window quirks operate on an address and data register,
85  * vfio_generic_window_address_quirk handles the address register and
86  * vfio_generic_window_data_quirk handles the data register.  These ops
87  * pass reads and writes through to hardware until a value matching the
88  * stored address match/mask is written.  When this occurs, the data
89  * register access emulated PCI config space for the device rather than
90  * passing through accesses.  This enables devices where PCI config space
91  * is accessible behind a window register to maintain the virtualization
92  * provided through vfio.
93  */
94 typedef struct VFIOConfigWindowMatch {
95     uint32_t match;
96     uint32_t mask;
97 } VFIOConfigWindowMatch;
98 
99 typedef struct VFIOConfigWindowQuirk {
100     struct VFIOPCIDevice *vdev;
101 
102     uint32_t address_val;
103 
104     uint32_t address_offset;
105     uint32_t data_offset;
106 
107     bool window_enabled;
108     uint8_t bar;
109 
110     MemoryRegion *addr_mem;
111     MemoryRegion *data_mem;
112 
113     uint32_t nr_matches;
114     VFIOConfigWindowMatch matches[];
115 } VFIOConfigWindowQuirk;
116 
117 static uint64_t vfio_generic_window_quirk_address_read(void *opaque,
118                                                        hwaddr addr,
119                                                        unsigned size)
120 {
121     VFIOConfigWindowQuirk *window = opaque;
122     VFIOPCIDevice *vdev = window->vdev;
123 
124     return vfio_region_read(&vdev->bars[window->bar].region,
125                             addr + window->address_offset, size);
126 }
127 
128 static void vfio_generic_window_quirk_address_write(void *opaque, hwaddr addr,
129                                                     uint64_t data,
130                                                     unsigned size)
131 {
132     VFIOConfigWindowQuirk *window = opaque;
133     VFIOPCIDevice *vdev = window->vdev;
134     int i;
135 
136     window->window_enabled = false;
137 
138     vfio_region_write(&vdev->bars[window->bar].region,
139                       addr + window->address_offset, data, size);
140 
141     for (i = 0; i < window->nr_matches; i++) {
142         if ((data & ~window->matches[i].mask) == window->matches[i].match) {
143             window->window_enabled = true;
144             window->address_val = data & window->matches[i].mask;
145             trace_vfio_quirk_generic_window_address_write(vdev->vbasedev.name,
146                                     memory_region_name(window->addr_mem), data);
147             break;
148         }
149     }
150 }
151 
152 static const MemoryRegionOps vfio_generic_window_address_quirk = {
153     .read = vfio_generic_window_quirk_address_read,
154     .write = vfio_generic_window_quirk_address_write,
155     .endianness = DEVICE_LITTLE_ENDIAN,
156 };
157 
158 static uint64_t vfio_generic_window_quirk_data_read(void *opaque,
159                                                     hwaddr addr, unsigned size)
160 {
161     VFIOConfigWindowQuirk *window = opaque;
162     VFIOPCIDevice *vdev = window->vdev;
163     uint64_t data;
164 
165     /* Always read data reg, discard if window enabled */
166     data = vfio_region_read(&vdev->bars[window->bar].region,
167                             addr + window->data_offset, size);
168 
169     if (window->window_enabled) {
170         data = vfio_pci_read_config(&vdev->pdev, window->address_val, size);
171         trace_vfio_quirk_generic_window_data_read(vdev->vbasedev.name,
172                                     memory_region_name(window->data_mem), data);
173     }
174 
175     return data;
176 }
177 
178 static void vfio_generic_window_quirk_data_write(void *opaque, hwaddr addr,
179                                                  uint64_t data, unsigned size)
180 {
181     VFIOConfigWindowQuirk *window = opaque;
182     VFIOPCIDevice *vdev = window->vdev;
183 
184     if (window->window_enabled) {
185         vfio_pci_write_config(&vdev->pdev, window->address_val, data, size);
186         trace_vfio_quirk_generic_window_data_write(vdev->vbasedev.name,
187                                     memory_region_name(window->data_mem), data);
188         return;
189     }
190 
191     vfio_region_write(&vdev->bars[window->bar].region,
192                       addr + window->data_offset, data, size);
193 }
194 
195 static const MemoryRegionOps vfio_generic_window_data_quirk = {
196     .read = vfio_generic_window_quirk_data_read,
197     .write = vfio_generic_window_quirk_data_write,
198     .endianness = DEVICE_LITTLE_ENDIAN,
199 };
200 
201 /*
202  * The generic mirror quirk handles devices which expose PCI config space
203  * through a region within a BAR.  When enabled, reads and writes are
204  * redirected through to emulated PCI config space.  XXX if PCI config space
205  * used memory regions, this could just be an alias.
206  */
207 typedef struct VFIOConfigMirrorQuirk {
208     struct VFIOPCIDevice *vdev;
209     uint32_t offset;
210     uint8_t bar;
211     MemoryRegion *mem;
212     uint8_t data[];
213 } VFIOConfigMirrorQuirk;
214 
215 static uint64_t vfio_generic_quirk_mirror_read(void *opaque,
216                                                hwaddr addr, unsigned size)
217 {
218     VFIOConfigMirrorQuirk *mirror = opaque;
219     VFIOPCIDevice *vdev = mirror->vdev;
220     uint64_t data;
221 
222     /* Read and discard in case the hardware cares */
223     (void)vfio_region_read(&vdev->bars[mirror->bar].region,
224                            addr + mirror->offset, size);
225 
226     data = vfio_pci_read_config(&vdev->pdev, addr, size);
227     trace_vfio_quirk_generic_mirror_read(vdev->vbasedev.name,
228                                          memory_region_name(mirror->mem),
229                                          addr, data);
230     return data;
231 }
232 
233 static void vfio_generic_quirk_mirror_write(void *opaque, hwaddr addr,
234                                             uint64_t data, unsigned size)
235 {
236     VFIOConfigMirrorQuirk *mirror = opaque;
237     VFIOPCIDevice *vdev = mirror->vdev;
238 
239     vfio_pci_write_config(&vdev->pdev, addr, data, size);
240     trace_vfio_quirk_generic_mirror_write(vdev->vbasedev.name,
241                                           memory_region_name(mirror->mem),
242                                           addr, data);
243 }
244 
245 static const MemoryRegionOps vfio_generic_mirror_quirk = {
246     .read = vfio_generic_quirk_mirror_read,
247     .write = vfio_generic_quirk_mirror_write,
248     .endianness = DEVICE_LITTLE_ENDIAN,
249 };
250 
251 /* Is range1 fully contained within range2?  */
252 static bool vfio_range_contained(uint64_t first1, uint64_t len1,
253                                  uint64_t first2, uint64_t len2) {
254     return (first1 >= first2 && first1 + len1 <= first2 + len2);
255 }
256 
257 #define PCI_VENDOR_ID_ATI               0x1002
258 
259 /*
260  * Radeon HD cards (HD5450 & HD7850) report the upper byte of the I/O port BAR
261  * through VGA register 0x3c3.  On newer cards, the I/O port BAR is always
262  * BAR4 (older cards like the X550 used BAR1, but we don't care to support
263  * those).  Note that on bare metal, a read of 0x3c3 doesn't always return the
264  * I/O port BAR address.  Originally this was coded to return the virtual BAR
265  * address only if the physical register read returns the actual BAR address,
266  * but users have reported greater success if we return the virtual address
267  * unconditionally.
268  */
269 static uint64_t vfio_ati_3c3_quirk_read(void *opaque,
270                                         hwaddr addr, unsigned size)
271 {
272     VFIOPCIDevice *vdev = opaque;
273     uint64_t data = vfio_pci_read_config(&vdev->pdev,
274                                          PCI_BASE_ADDRESS_4 + 1, size);
275 
276     trace_vfio_quirk_ati_3c3_read(vdev->vbasedev.name, data);
277 
278     return data;
279 }
280 
281 static const MemoryRegionOps vfio_ati_3c3_quirk = {
282     .read = vfio_ati_3c3_quirk_read,
283     .endianness = DEVICE_LITTLE_ENDIAN,
284 };
285 
286 static VFIOQuirk *vfio_quirk_alloc(int nr_mem)
287 {
288     VFIOQuirk *quirk = g_new0(VFIOQuirk, 1);
289     QLIST_INIT(&quirk->ioeventfds);
290     quirk->mem = g_new0(MemoryRegion, nr_mem);
291     quirk->nr_mem = nr_mem;
292 
293     return quirk;
294 }
295 
296 static void vfio_ioeventfd_exit(VFIOPCIDevice *vdev, VFIOIOEventFD *ioeventfd)
297 {
298     QLIST_REMOVE(ioeventfd, next);
299     memory_region_del_eventfd(ioeventfd->mr, ioeventfd->addr, ioeventfd->size,
300                               true, ioeventfd->data, &ioeventfd->e);
301 
302     if (ioeventfd->vfio) {
303         struct vfio_device_ioeventfd vfio_ioeventfd;
304 
305         vfio_ioeventfd.argsz = sizeof(vfio_ioeventfd);
306         vfio_ioeventfd.flags = ioeventfd->size;
307         vfio_ioeventfd.data = ioeventfd->data;
308         vfio_ioeventfd.offset = ioeventfd->region->fd_offset +
309                                 ioeventfd->region_addr;
310         vfio_ioeventfd.fd = -1;
311 
312         if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_IOEVENTFD, &vfio_ioeventfd)) {
313             error_report("Failed to remove vfio ioeventfd for %s+0x%"
314                          HWADDR_PRIx"[%d]:0x%"PRIx64" (%m)",
315                          memory_region_name(ioeventfd->mr), ioeventfd->addr,
316                          ioeventfd->size, ioeventfd->data);
317         }
318     } else {
319         qemu_set_fd_handler(event_notifier_get_fd(&ioeventfd->e),
320                             NULL, NULL, NULL);
321     }
322 
323     event_notifier_cleanup(&ioeventfd->e);
324     trace_vfio_ioeventfd_exit(memory_region_name(ioeventfd->mr),
325                               (uint64_t)ioeventfd->addr, ioeventfd->size,
326                               ioeventfd->data);
327     g_free(ioeventfd);
328 }
329 
330 static void vfio_drop_dynamic_eventfds(VFIOPCIDevice *vdev, VFIOQuirk *quirk)
331 {
332     VFIOIOEventFD *ioeventfd, *tmp;
333 
334     QLIST_FOREACH_SAFE(ioeventfd, &quirk->ioeventfds, next, tmp) {
335         if (ioeventfd->dynamic) {
336             vfio_ioeventfd_exit(vdev, ioeventfd);
337         }
338     }
339 }
340 
341 static void vfio_ioeventfd_handler(void *opaque)
342 {
343     VFIOIOEventFD *ioeventfd = opaque;
344 
345     if (event_notifier_test_and_clear(&ioeventfd->e)) {
346         vfio_region_write(ioeventfd->region, ioeventfd->region_addr,
347                           ioeventfd->data, ioeventfd->size);
348         trace_vfio_ioeventfd_handler(memory_region_name(ioeventfd->mr),
349                                      (uint64_t)ioeventfd->addr, ioeventfd->size,
350                                      ioeventfd->data);
351     }
352 }
353 
354 static VFIOIOEventFD *vfio_ioeventfd_init(VFIOPCIDevice *vdev,
355                                           MemoryRegion *mr, hwaddr addr,
356                                           unsigned size, uint64_t data,
357                                           VFIORegion *region,
358                                           hwaddr region_addr, bool dynamic)
359 {
360     VFIOIOEventFD *ioeventfd;
361 
362     if (vdev->no_kvm_ioeventfd) {
363         return NULL;
364     }
365 
366     ioeventfd = g_malloc0(sizeof(*ioeventfd));
367 
368     if (event_notifier_init(&ioeventfd->e, 0)) {
369         g_free(ioeventfd);
370         return NULL;
371     }
372 
373     /*
374      * MemoryRegion and relative offset, plus additional ioeventfd setup
375      * parameters for configuring and later tearing down KVM ioeventfd.
376      */
377     ioeventfd->mr = mr;
378     ioeventfd->addr = addr;
379     ioeventfd->size = size;
380     ioeventfd->data = data;
381     ioeventfd->dynamic = dynamic;
382     /*
383      * VFIORegion and relative offset for implementing the userspace
384      * handler.  data & size fields shared for both uses.
385      */
386     ioeventfd->region = region;
387     ioeventfd->region_addr = region_addr;
388 
389     if (!vdev->no_vfio_ioeventfd) {
390         struct vfio_device_ioeventfd vfio_ioeventfd;
391 
392         vfio_ioeventfd.argsz = sizeof(vfio_ioeventfd);
393         vfio_ioeventfd.flags = ioeventfd->size;
394         vfio_ioeventfd.data = ioeventfd->data;
395         vfio_ioeventfd.offset = ioeventfd->region->fd_offset +
396                                 ioeventfd->region_addr;
397         vfio_ioeventfd.fd = event_notifier_get_fd(&ioeventfd->e);
398 
399         ioeventfd->vfio = !ioctl(vdev->vbasedev.fd,
400                                  VFIO_DEVICE_IOEVENTFD, &vfio_ioeventfd);
401     }
402 
403     if (!ioeventfd->vfio) {
404         qemu_set_fd_handler(event_notifier_get_fd(&ioeventfd->e),
405                             vfio_ioeventfd_handler, NULL, ioeventfd);
406     }
407 
408     memory_region_add_eventfd(ioeventfd->mr, ioeventfd->addr, ioeventfd->size,
409                               true, ioeventfd->data, &ioeventfd->e);
410     trace_vfio_ioeventfd_init(memory_region_name(mr), (uint64_t)addr,
411                               size, data, ioeventfd->vfio);
412 
413     return ioeventfd;
414 }
415 
416 static void vfio_vga_probe_ati_3c3_quirk(VFIOPCIDevice *vdev)
417 {
418     VFIOQuirk *quirk;
419 
420     /*
421      * As long as the BAR is >= 256 bytes it will be aligned such that the
422      * lower byte is always zero.  Filter out anything else, if it exists.
423      */
424     if (!vfio_pci_is(vdev, PCI_VENDOR_ID_ATI, PCI_ANY_ID) ||
425         !vdev->bars[4].ioport || vdev->bars[4].region.size < 256) {
426         return;
427     }
428 
429     quirk = vfio_quirk_alloc(1);
430 
431     memory_region_init_io(quirk->mem, OBJECT(vdev), &vfio_ati_3c3_quirk, vdev,
432                           "vfio-ati-3c3-quirk", 1);
433     memory_region_add_subregion(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
434                                 3 /* offset 3 bytes from 0x3c0 */, quirk->mem);
435 
436     QLIST_INSERT_HEAD(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks,
437                       quirk, next);
438 
439     trace_vfio_quirk_ati_3c3_probe(vdev->vbasedev.name);
440 }
441 
442 /*
443  * Newer ATI/AMD devices, including HD5450 and HD7850, have a mirror to PCI
444  * config space through MMIO BAR2 at offset 0x4000.  Nothing seems to access
445  * the MMIO space directly, but a window to this space is provided through
446  * I/O port BAR4.  Offset 0x0 is the address register and offset 0x4 is the
447  * data register.  When the address is programmed to a range of 0x4000-0x4fff
448  * PCI configuration space is available.  Experimentation seems to indicate
449  * that read-only may be provided by hardware.
450  */
451 static void vfio_probe_ati_bar4_quirk(VFIOPCIDevice *vdev, int nr)
452 {
453     VFIOQuirk *quirk;
454     VFIOConfigWindowQuirk *window;
455 
456     /* This windows doesn't seem to be used except by legacy VGA code */
457     if (!vfio_pci_is(vdev, PCI_VENDOR_ID_ATI, PCI_ANY_ID) ||
458         !vdev->vga || nr != 4) {
459         return;
460     }
461 
462     quirk = vfio_quirk_alloc(2);
463     window = quirk->data = g_malloc0(sizeof(*window) +
464                                      sizeof(VFIOConfigWindowMatch));
465     window->vdev = vdev;
466     window->address_offset = 0;
467     window->data_offset = 4;
468     window->nr_matches = 1;
469     window->matches[0].match = 0x4000;
470     window->matches[0].mask = vdev->config_size - 1;
471     window->bar = nr;
472     window->addr_mem = &quirk->mem[0];
473     window->data_mem = &quirk->mem[1];
474 
475     memory_region_init_io(window->addr_mem, OBJECT(vdev),
476                           &vfio_generic_window_address_quirk, window,
477                           "vfio-ati-bar4-window-address-quirk", 4);
478     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
479                                         window->address_offset,
480                                         window->addr_mem, 1);
481 
482     memory_region_init_io(window->data_mem, OBJECT(vdev),
483                           &vfio_generic_window_data_quirk, window,
484                           "vfio-ati-bar4-window-data-quirk", 4);
485     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
486                                         window->data_offset,
487                                         window->data_mem, 1);
488 
489     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
490 
491     trace_vfio_quirk_ati_bar4_probe(vdev->vbasedev.name);
492 }
493 
494 /*
495  * Trap the BAR2 MMIO mirror to config space as well.
496  */
497 static void vfio_probe_ati_bar2_quirk(VFIOPCIDevice *vdev, int nr)
498 {
499     VFIOQuirk *quirk;
500     VFIOConfigMirrorQuirk *mirror;
501 
502     /* Only enable on newer devices where BAR2 is 64bit */
503     if (!vfio_pci_is(vdev, PCI_VENDOR_ID_ATI, PCI_ANY_ID) ||
504         !vdev->vga || nr != 2 || !vdev->bars[2].mem64) {
505         return;
506     }
507 
508     quirk = vfio_quirk_alloc(1);
509     mirror = quirk->data = g_malloc0(sizeof(*mirror));
510     mirror->mem = quirk->mem;
511     mirror->vdev = vdev;
512     mirror->offset = 0x4000;
513     mirror->bar = nr;
514 
515     memory_region_init_io(mirror->mem, OBJECT(vdev),
516                           &vfio_generic_mirror_quirk, mirror,
517                           "vfio-ati-bar2-4000-quirk", PCI_CONFIG_SPACE_SIZE);
518     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
519                                         mirror->offset, mirror->mem, 1);
520 
521     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
522 
523     trace_vfio_quirk_ati_bar2_probe(vdev->vbasedev.name);
524 }
525 
526 /*
527  * Older ATI/AMD cards like the X550 have a similar window to that above.
528  * I/O port BAR1 provides a window to a mirror of PCI config space located
529  * in BAR2 at offset 0xf00.  We don't care to support such older cards, but
530  * note it for future reference.
531  */
532 
533 /*
534  * Nvidia has several different methods to get to config space, the
535  * nouveu project has several of these documented here:
536  * https://github.com/pathscale/envytools/tree/master/hwdocs
537  *
538  * The first quirk is actually not documented in envytools and is found
539  * on 10de:01d1 (NVIDIA Corporation G72 [GeForce 7300 LE]).  This is an
540  * NV46 chipset.  The backdoor uses the legacy VGA I/O ports to access
541  * the mirror of PCI config space found at BAR0 offset 0x1800.  The access
542  * sequence first writes 0x338 to I/O port 0x3d4.  The target offset is
543  * then written to 0x3d0.  Finally 0x538 is written for a read and 0x738
544  * is written for a write to 0x3d4.  The BAR0 offset is then accessible
545  * through 0x3d0.  This quirk doesn't seem to be necessary on newer cards
546  * that use the I/O port BAR5 window but it doesn't hurt to leave it.
547  */
548 typedef enum {NONE = 0, SELECT, WINDOW, READ, WRITE} VFIONvidia3d0State;
549 static const char *nv3d0_states[] = { "NONE", "SELECT",
550                                       "WINDOW", "READ", "WRITE" };
551 
552 typedef struct VFIONvidia3d0Quirk {
553     VFIOPCIDevice *vdev;
554     VFIONvidia3d0State state;
555     uint32_t offset;
556 } VFIONvidia3d0Quirk;
557 
558 static uint64_t vfio_nvidia_3d4_quirk_read(void *opaque,
559                                            hwaddr addr, unsigned size)
560 {
561     VFIONvidia3d0Quirk *quirk = opaque;
562     VFIOPCIDevice *vdev = quirk->vdev;
563 
564     quirk->state = NONE;
565 
566     return vfio_vga_read(&vdev->vga->region[QEMU_PCI_VGA_IO_HI],
567                          addr + 0x14, size);
568 }
569 
570 static void vfio_nvidia_3d4_quirk_write(void *opaque, hwaddr addr,
571                                         uint64_t data, unsigned size)
572 {
573     VFIONvidia3d0Quirk *quirk = opaque;
574     VFIOPCIDevice *vdev = quirk->vdev;
575     VFIONvidia3d0State old_state = quirk->state;
576 
577     quirk->state = NONE;
578 
579     switch (data) {
580     case 0x338:
581         if (old_state == NONE) {
582             quirk->state = SELECT;
583             trace_vfio_quirk_nvidia_3d0_state(vdev->vbasedev.name,
584                                               nv3d0_states[quirk->state]);
585         }
586         break;
587     case 0x538:
588         if (old_state == WINDOW) {
589             quirk->state = READ;
590             trace_vfio_quirk_nvidia_3d0_state(vdev->vbasedev.name,
591                                               nv3d0_states[quirk->state]);
592         }
593         break;
594     case 0x738:
595         if (old_state == WINDOW) {
596             quirk->state = WRITE;
597             trace_vfio_quirk_nvidia_3d0_state(vdev->vbasedev.name,
598                                               nv3d0_states[quirk->state]);
599         }
600         break;
601     }
602 
603     vfio_vga_write(&vdev->vga->region[QEMU_PCI_VGA_IO_HI],
604                    addr + 0x14, data, size);
605 }
606 
607 static const MemoryRegionOps vfio_nvidia_3d4_quirk = {
608     .read = vfio_nvidia_3d4_quirk_read,
609     .write = vfio_nvidia_3d4_quirk_write,
610     .endianness = DEVICE_LITTLE_ENDIAN,
611 };
612 
613 static uint64_t vfio_nvidia_3d0_quirk_read(void *opaque,
614                                            hwaddr addr, unsigned size)
615 {
616     VFIONvidia3d0Quirk *quirk = opaque;
617     VFIOPCIDevice *vdev = quirk->vdev;
618     VFIONvidia3d0State old_state = quirk->state;
619     uint64_t data = vfio_vga_read(&vdev->vga->region[QEMU_PCI_VGA_IO_HI],
620                                   addr + 0x10, size);
621 
622     quirk->state = NONE;
623 
624     if (old_state == READ &&
625         (quirk->offset & ~(PCI_CONFIG_SPACE_SIZE - 1)) == 0x1800) {
626         uint8_t offset = quirk->offset & (PCI_CONFIG_SPACE_SIZE - 1);
627 
628         data = vfio_pci_read_config(&vdev->pdev, offset, size);
629         trace_vfio_quirk_nvidia_3d0_read(vdev->vbasedev.name,
630                                          offset, size, data);
631     }
632 
633     return data;
634 }
635 
636 static void vfio_nvidia_3d0_quirk_write(void *opaque, hwaddr addr,
637                                         uint64_t data, unsigned size)
638 {
639     VFIONvidia3d0Quirk *quirk = opaque;
640     VFIOPCIDevice *vdev = quirk->vdev;
641     VFIONvidia3d0State old_state = quirk->state;
642 
643     quirk->state = NONE;
644 
645     if (old_state == SELECT) {
646         quirk->offset = (uint32_t)data;
647         quirk->state = WINDOW;
648         trace_vfio_quirk_nvidia_3d0_state(vdev->vbasedev.name,
649                                           nv3d0_states[quirk->state]);
650     } else if (old_state == WRITE) {
651         if ((quirk->offset & ~(PCI_CONFIG_SPACE_SIZE - 1)) == 0x1800) {
652             uint8_t offset = quirk->offset & (PCI_CONFIG_SPACE_SIZE - 1);
653 
654             vfio_pci_write_config(&vdev->pdev, offset, data, size);
655             trace_vfio_quirk_nvidia_3d0_write(vdev->vbasedev.name,
656                                               offset, data, size);
657             return;
658         }
659     }
660 
661     vfio_vga_write(&vdev->vga->region[QEMU_PCI_VGA_IO_HI],
662                    addr + 0x10, data, size);
663 }
664 
665 static const MemoryRegionOps vfio_nvidia_3d0_quirk = {
666     .read = vfio_nvidia_3d0_quirk_read,
667     .write = vfio_nvidia_3d0_quirk_write,
668     .endianness = DEVICE_LITTLE_ENDIAN,
669 };
670 
671 static void vfio_vga_probe_nvidia_3d0_quirk(VFIOPCIDevice *vdev)
672 {
673     VFIOQuirk *quirk;
674     VFIONvidia3d0Quirk *data;
675 
676     if (vdev->no_geforce_quirks ||
677         !vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||
678         !vdev->bars[1].region.size) {
679         return;
680     }
681 
682     quirk = vfio_quirk_alloc(2);
683     quirk->data = data = g_malloc0(sizeof(*data));
684     data->vdev = vdev;
685 
686     memory_region_init_io(&quirk->mem[0], OBJECT(vdev), &vfio_nvidia_3d4_quirk,
687                           data, "vfio-nvidia-3d4-quirk", 2);
688     memory_region_add_subregion(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
689                                 0x14 /* 0x3c0 + 0x14 */, &quirk->mem[0]);
690 
691     memory_region_init_io(&quirk->mem[1], OBJECT(vdev), &vfio_nvidia_3d0_quirk,
692                           data, "vfio-nvidia-3d0-quirk", 2);
693     memory_region_add_subregion(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].mem,
694                                 0x10 /* 0x3c0 + 0x10 */, &quirk->mem[1]);
695 
696     QLIST_INSERT_HEAD(&vdev->vga->region[QEMU_PCI_VGA_IO_HI].quirks,
697                       quirk, next);
698 
699     trace_vfio_quirk_nvidia_3d0_probe(vdev->vbasedev.name);
700 }
701 
702 /*
703  * The second quirk is documented in envytools.  The I/O port BAR5 is just
704  * a set of address/data ports to the MMIO BARs.  The BAR we care about is
705  * again BAR0.  This backdoor is apparently a bit newer than the one above
706  * so we need to not only trap 256 bytes @0x1800, but all of PCI config
707  * space, including extended space is available at the 4k @0x88000.
708  */
709 typedef struct VFIONvidiaBAR5Quirk {
710     uint32_t master;
711     uint32_t enable;
712     MemoryRegion *addr_mem;
713     MemoryRegion *data_mem;
714     bool enabled;
715     VFIOConfigWindowQuirk window; /* last for match data */
716 } VFIONvidiaBAR5Quirk;
717 
718 static void vfio_nvidia_bar5_enable(VFIONvidiaBAR5Quirk *bar5)
719 {
720     VFIOPCIDevice *vdev = bar5->window.vdev;
721 
722     if (((bar5->master & bar5->enable) & 0x1) == bar5->enabled) {
723         return;
724     }
725 
726     bar5->enabled = !bar5->enabled;
727     trace_vfio_quirk_nvidia_bar5_state(vdev->vbasedev.name,
728                                        bar5->enabled ?  "Enable" : "Disable");
729     memory_region_set_enabled(bar5->addr_mem, bar5->enabled);
730     memory_region_set_enabled(bar5->data_mem, bar5->enabled);
731 }
732 
733 static uint64_t vfio_nvidia_bar5_quirk_master_read(void *opaque,
734                                                    hwaddr addr, unsigned size)
735 {
736     VFIONvidiaBAR5Quirk *bar5 = opaque;
737     VFIOPCIDevice *vdev = bar5->window.vdev;
738 
739     return vfio_region_read(&vdev->bars[5].region, addr, size);
740 }
741 
742 static void vfio_nvidia_bar5_quirk_master_write(void *opaque, hwaddr addr,
743                                                 uint64_t data, unsigned size)
744 {
745     VFIONvidiaBAR5Quirk *bar5 = opaque;
746     VFIOPCIDevice *vdev = bar5->window.vdev;
747 
748     vfio_region_write(&vdev->bars[5].region, addr, data, size);
749 
750     bar5->master = data;
751     vfio_nvidia_bar5_enable(bar5);
752 }
753 
754 static const MemoryRegionOps vfio_nvidia_bar5_quirk_master = {
755     .read = vfio_nvidia_bar5_quirk_master_read,
756     .write = vfio_nvidia_bar5_quirk_master_write,
757     .endianness = DEVICE_LITTLE_ENDIAN,
758 };
759 
760 static uint64_t vfio_nvidia_bar5_quirk_enable_read(void *opaque,
761                                                    hwaddr addr, unsigned size)
762 {
763     VFIONvidiaBAR5Quirk *bar5 = opaque;
764     VFIOPCIDevice *vdev = bar5->window.vdev;
765 
766     return vfio_region_read(&vdev->bars[5].region, addr + 4, size);
767 }
768 
769 static void vfio_nvidia_bar5_quirk_enable_write(void *opaque, hwaddr addr,
770                                                 uint64_t data, unsigned size)
771 {
772     VFIONvidiaBAR5Quirk *bar5 = opaque;
773     VFIOPCIDevice *vdev = bar5->window.vdev;
774 
775     vfio_region_write(&vdev->bars[5].region, addr + 4, data, size);
776 
777     bar5->enable = data;
778     vfio_nvidia_bar5_enable(bar5);
779 }
780 
781 static const MemoryRegionOps vfio_nvidia_bar5_quirk_enable = {
782     .read = vfio_nvidia_bar5_quirk_enable_read,
783     .write = vfio_nvidia_bar5_quirk_enable_write,
784     .endianness = DEVICE_LITTLE_ENDIAN,
785 };
786 
787 static void vfio_probe_nvidia_bar5_quirk(VFIOPCIDevice *vdev, int nr)
788 {
789     VFIOQuirk *quirk;
790     VFIONvidiaBAR5Quirk *bar5;
791     VFIOConfigWindowQuirk *window;
792 
793     if (vdev->no_geforce_quirks ||
794         !vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||
795         !vdev->vga || nr != 5 || !vdev->bars[5].ioport) {
796         return;
797     }
798 
799     quirk = vfio_quirk_alloc(4);
800     bar5 = quirk->data = g_malloc0(sizeof(*bar5) +
801                                    (sizeof(VFIOConfigWindowMatch) * 2));
802     window = &bar5->window;
803 
804     window->vdev = vdev;
805     window->address_offset = 0x8;
806     window->data_offset = 0xc;
807     window->nr_matches = 2;
808     window->matches[0].match = 0x1800;
809     window->matches[0].mask = PCI_CONFIG_SPACE_SIZE - 1;
810     window->matches[1].match = 0x88000;
811     window->matches[1].mask = vdev->config_size - 1;
812     window->bar = nr;
813     window->addr_mem = bar5->addr_mem = &quirk->mem[0];
814     window->data_mem = bar5->data_mem = &quirk->mem[1];
815 
816     memory_region_init_io(window->addr_mem, OBJECT(vdev),
817                           &vfio_generic_window_address_quirk, window,
818                           "vfio-nvidia-bar5-window-address-quirk", 4);
819     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
820                                         window->address_offset,
821                                         window->addr_mem, 1);
822     memory_region_set_enabled(window->addr_mem, false);
823 
824     memory_region_init_io(window->data_mem, OBJECT(vdev),
825                           &vfio_generic_window_data_quirk, window,
826                           "vfio-nvidia-bar5-window-data-quirk", 4);
827     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
828                                         window->data_offset,
829                                         window->data_mem, 1);
830     memory_region_set_enabled(window->data_mem, false);
831 
832     memory_region_init_io(&quirk->mem[2], OBJECT(vdev),
833                           &vfio_nvidia_bar5_quirk_master, bar5,
834                           "vfio-nvidia-bar5-master-quirk", 4);
835     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
836                                         0, &quirk->mem[2], 1);
837 
838     memory_region_init_io(&quirk->mem[3], OBJECT(vdev),
839                           &vfio_nvidia_bar5_quirk_enable, bar5,
840                           "vfio-nvidia-bar5-enable-quirk", 4);
841     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
842                                         4, &quirk->mem[3], 1);
843 
844     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
845 
846     trace_vfio_quirk_nvidia_bar5_probe(vdev->vbasedev.name);
847 }
848 
849 typedef struct LastDataSet {
850     VFIOQuirk *quirk;
851     hwaddr addr;
852     uint64_t data;
853     unsigned size;
854     int hits;
855     int added;
856 } LastDataSet;
857 
858 #define MAX_DYN_IOEVENTFD 10
859 #define HITS_FOR_IOEVENTFD 10
860 
861 /*
862  * Finally, BAR0 itself.  We want to redirect any accesses to either
863  * 0x1800 or 0x88000 through the PCI config space access functions.
864  */
865 static void vfio_nvidia_quirk_mirror_write(void *opaque, hwaddr addr,
866                                            uint64_t data, unsigned size)
867 {
868     VFIOConfigMirrorQuirk *mirror = opaque;
869     VFIOPCIDevice *vdev = mirror->vdev;
870     PCIDevice *pdev = &vdev->pdev;
871     LastDataSet *last = (LastDataSet *)&mirror->data;
872 
873     vfio_generic_quirk_mirror_write(opaque, addr, data, size);
874 
875     /*
876      * Nvidia seems to acknowledge MSI interrupts by writing 0xff to the
877      * MSI capability ID register.  Both the ID and next register are
878      * read-only, so we allow writes covering either of those to real hw.
879      */
880     if ((pdev->cap_present & QEMU_PCI_CAP_MSI) &&
881         vfio_range_contained(addr, size, pdev->msi_cap, PCI_MSI_FLAGS)) {
882         vfio_region_write(&vdev->bars[mirror->bar].region,
883                           addr + mirror->offset, data, size);
884         trace_vfio_quirk_nvidia_bar0_msi_ack(vdev->vbasedev.name);
885     }
886 
887     /*
888      * Automatically add an ioeventfd to handle any repeated write with the
889      * same data and size above the standard PCI config space header.  This is
890      * primarily expected to accelerate the MSI-ACK behavior, such as noted
891      * above.  Current hardware/drivers should trigger an ioeventfd at config
892      * offset 0x704 (region offset 0x88704), with data 0x0, size 4.
893      *
894      * The criteria of 10 successive hits is arbitrary but reliably adds the
895      * MSI-ACK region.  Note that as some writes are bypassed via the ioeventfd,
896      * the remaining ones have a greater chance of being seen successively.
897      * To avoid the pathological case of burning up all of QEMU's open file
898      * handles, arbitrarily limit this algorithm from adding no more than 10
899      * ioeventfds, print an error if we would have added an 11th, and then
900      * stop counting.
901      */
902     if (!vdev->no_kvm_ioeventfd &&
903         addr >= PCI_STD_HEADER_SIZEOF && last->added <= MAX_DYN_IOEVENTFD) {
904         if (addr != last->addr || data != last->data || size != last->size) {
905             last->addr = addr;
906             last->data = data;
907             last->size = size;
908             last->hits = 1;
909         } else if (++last->hits >= HITS_FOR_IOEVENTFD) {
910             if (last->added < MAX_DYN_IOEVENTFD) {
911                 VFIOIOEventFD *ioeventfd;
912                 ioeventfd = vfio_ioeventfd_init(vdev, mirror->mem, addr, size,
913                                         data, &vdev->bars[mirror->bar].region,
914                                         mirror->offset + addr, true);
915                 if (ioeventfd) {
916                     VFIOQuirk *quirk = last->quirk;
917 
918                     QLIST_INSERT_HEAD(&quirk->ioeventfds, ioeventfd, next);
919                     last->added++;
920                 }
921             } else {
922                 last->added++;
923                 warn_report("NVIDIA ioeventfd queue full for %s, unable to "
924                             "accelerate 0x%"HWADDR_PRIx", data 0x%"PRIx64", "
925                             "size %u", vdev->vbasedev.name, addr, data, size);
926             }
927         }
928     }
929 }
930 
931 static const MemoryRegionOps vfio_nvidia_mirror_quirk = {
932     .read = vfio_generic_quirk_mirror_read,
933     .write = vfio_nvidia_quirk_mirror_write,
934     .endianness = DEVICE_LITTLE_ENDIAN,
935 };
936 
937 static void vfio_nvidia_bar0_quirk_reset(VFIOPCIDevice *vdev, VFIOQuirk *quirk)
938 {
939     VFIOConfigMirrorQuirk *mirror = quirk->data;
940     LastDataSet *last = (LastDataSet *)&mirror->data;
941 
942     last->addr = last->data = last->size = last->hits = last->added = 0;
943 
944     vfio_drop_dynamic_eventfds(vdev, quirk);
945 }
946 
947 static void vfio_probe_nvidia_bar0_quirk(VFIOPCIDevice *vdev, int nr)
948 {
949     VFIOQuirk *quirk;
950     VFIOConfigMirrorQuirk *mirror;
951     LastDataSet *last;
952 
953     if (vdev->no_geforce_quirks ||
954         !vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||
955         !vfio_is_vga(vdev) || nr != 0) {
956         return;
957     }
958 
959     quirk = vfio_quirk_alloc(1);
960     quirk->reset = vfio_nvidia_bar0_quirk_reset;
961     mirror = quirk->data = g_malloc0(sizeof(*mirror) + sizeof(LastDataSet));
962     mirror->mem = quirk->mem;
963     mirror->vdev = vdev;
964     mirror->offset = 0x88000;
965     mirror->bar = nr;
966     last = (LastDataSet *)&mirror->data;
967     last->quirk = quirk;
968 
969     memory_region_init_io(mirror->mem, OBJECT(vdev),
970                           &vfio_nvidia_mirror_quirk, mirror,
971                           "vfio-nvidia-bar0-88000-mirror-quirk",
972                           vdev->config_size);
973     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
974                                         mirror->offset, mirror->mem, 1);
975 
976     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
977 
978     /* The 0x1800 offset mirror only seems to get used by legacy VGA */
979     if (vdev->vga) {
980         quirk = vfio_quirk_alloc(1);
981         quirk->reset = vfio_nvidia_bar0_quirk_reset;
982         mirror = quirk->data = g_malloc0(sizeof(*mirror) + sizeof(LastDataSet));
983         mirror->mem = quirk->mem;
984         mirror->vdev = vdev;
985         mirror->offset = 0x1800;
986         mirror->bar = nr;
987         last = (LastDataSet *)&mirror->data;
988         last->quirk = quirk;
989 
990         memory_region_init_io(mirror->mem, OBJECT(vdev),
991                               &vfio_nvidia_mirror_quirk, mirror,
992                               "vfio-nvidia-bar0-1800-mirror-quirk",
993                               PCI_CONFIG_SPACE_SIZE);
994         memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
995                                             mirror->offset, mirror->mem, 1);
996 
997         QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
998     }
999 
1000     trace_vfio_quirk_nvidia_bar0_probe(vdev->vbasedev.name);
1001 }
1002 
1003 /*
1004  * TODO - Some Nvidia devices provide config access to their companion HDA
1005  * device and even to their parent bridge via these config space mirrors.
1006  * Add quirks for those regions.
1007  */
1008 
1009 #define PCI_VENDOR_ID_REALTEK 0x10ec
1010 
1011 /*
1012  * RTL8168 devices have a backdoor that can access the MSI-X table.  At BAR2
1013  * offset 0x70 there is a dword data register, offset 0x74 is a dword address
1014  * register.  According to the Linux r8169 driver, the MSI-X table is addressed
1015  * when the "type" portion of the address register is set to 0x1.  This appears
1016  * to be bits 16:30.  Bit 31 is both a write indicator and some sort of
1017  * "address latched" indicator.  Bits 12:15 are a mask field, which we can
1018  * ignore because the MSI-X table should always be accessed as a dword (full
1019  * mask).  Bits 0:11 is offset within the type.
1020  *
1021  * Example trace:
1022  *
1023  * Read from MSI-X table offset 0
1024  * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x74, 0x1f000, 4) // store read addr
1025  * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x74, 4) = 0x8001f000 // latch
1026  * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x70, 4) = 0xfee00398 // read data
1027  *
1028  * Write 0xfee00000 to MSI-X table offset 0
1029  * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x70, 0xfee00000, 4) // write data
1030  * vfio: vfio_bar_write(0000:05:00.0:BAR2+0x74, 0x8001f000, 4) // do write
1031  * vfio: vfio_bar_read(0000:05:00.0:BAR2+0x74, 4) = 0x1f000 // complete
1032  */
1033 typedef struct VFIOrtl8168Quirk {
1034     VFIOPCIDevice *vdev;
1035     uint32_t addr;
1036     uint32_t data;
1037     bool enabled;
1038 } VFIOrtl8168Quirk;
1039 
1040 static uint64_t vfio_rtl8168_quirk_address_read(void *opaque,
1041                                                 hwaddr addr, unsigned size)
1042 {
1043     VFIOrtl8168Quirk *rtl = opaque;
1044     VFIOPCIDevice *vdev = rtl->vdev;
1045     uint64_t data = vfio_region_read(&vdev->bars[2].region, addr + 0x74, size);
1046 
1047     if (rtl->enabled) {
1048         data = rtl->addr ^ 0x80000000U; /* latch/complete */
1049         trace_vfio_quirk_rtl8168_fake_latch(vdev->vbasedev.name, data);
1050     }
1051 
1052     return data;
1053 }
1054 
1055 static void vfio_rtl8168_quirk_address_write(void *opaque, hwaddr addr,
1056                                              uint64_t data, unsigned size)
1057 {
1058     VFIOrtl8168Quirk *rtl = opaque;
1059     VFIOPCIDevice *vdev = rtl->vdev;
1060 
1061     rtl->enabled = false;
1062 
1063     if ((data & 0x7fff0000) == 0x10000) { /* MSI-X table */
1064         rtl->enabled = true;
1065         rtl->addr = (uint32_t)data;
1066 
1067         if (data & 0x80000000U) { /* Do write */
1068             if (vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX) {
1069                 hwaddr offset = data & 0xfff;
1070                 uint64_t val = rtl->data;
1071 
1072                 trace_vfio_quirk_rtl8168_msix_write(vdev->vbasedev.name,
1073                                                     (uint16_t)offset, val);
1074 
1075                 /* Write to the proper guest MSI-X table instead */
1076                 memory_region_dispatch_write(&vdev->pdev.msix_table_mmio,
1077                                              offset, val, size_memop(size),
1078                                              MEMTXATTRS_UNSPECIFIED);
1079             }
1080             return; /* Do not write guest MSI-X data to hardware */
1081         }
1082     }
1083 
1084     vfio_region_write(&vdev->bars[2].region, addr + 0x74, data, size);
1085 }
1086 
1087 static const MemoryRegionOps vfio_rtl_address_quirk = {
1088     .read = vfio_rtl8168_quirk_address_read,
1089     .write = vfio_rtl8168_quirk_address_write,
1090     .valid = {
1091         .min_access_size = 4,
1092         .max_access_size = 4,
1093         .unaligned = false,
1094     },
1095     .endianness = DEVICE_LITTLE_ENDIAN,
1096 };
1097 
1098 static uint64_t vfio_rtl8168_quirk_data_read(void *opaque,
1099                                              hwaddr addr, unsigned size)
1100 {
1101     VFIOrtl8168Quirk *rtl = opaque;
1102     VFIOPCIDevice *vdev = rtl->vdev;
1103     uint64_t data = vfio_region_read(&vdev->bars[2].region, addr + 0x70, size);
1104 
1105     if (rtl->enabled && (vdev->pdev.cap_present & QEMU_PCI_CAP_MSIX)) {
1106         hwaddr offset = rtl->addr & 0xfff;
1107         memory_region_dispatch_read(&vdev->pdev.msix_table_mmio, offset,
1108                                     &data, size_memop(size),
1109                                     MEMTXATTRS_UNSPECIFIED);
1110         trace_vfio_quirk_rtl8168_msix_read(vdev->vbasedev.name, offset, data);
1111     }
1112 
1113     return data;
1114 }
1115 
1116 static void vfio_rtl8168_quirk_data_write(void *opaque, hwaddr addr,
1117                                           uint64_t data, unsigned size)
1118 {
1119     VFIOrtl8168Quirk *rtl = opaque;
1120     VFIOPCIDevice *vdev = rtl->vdev;
1121 
1122     rtl->data = (uint32_t)data;
1123 
1124     vfio_region_write(&vdev->bars[2].region, addr + 0x70, data, size);
1125 }
1126 
1127 static const MemoryRegionOps vfio_rtl_data_quirk = {
1128     .read = vfio_rtl8168_quirk_data_read,
1129     .write = vfio_rtl8168_quirk_data_write,
1130     .valid = {
1131         .min_access_size = 4,
1132         .max_access_size = 4,
1133         .unaligned = false,
1134     },
1135     .endianness = DEVICE_LITTLE_ENDIAN,
1136 };
1137 
1138 static void vfio_probe_rtl8168_bar2_quirk(VFIOPCIDevice *vdev, int nr)
1139 {
1140     VFIOQuirk *quirk;
1141     VFIOrtl8168Quirk *rtl;
1142 
1143     if (!vfio_pci_is(vdev, PCI_VENDOR_ID_REALTEK, 0x8168) || nr != 2) {
1144         return;
1145     }
1146 
1147     quirk = vfio_quirk_alloc(2);
1148     quirk->data = rtl = g_malloc0(sizeof(*rtl));
1149     rtl->vdev = vdev;
1150 
1151     memory_region_init_io(&quirk->mem[0], OBJECT(vdev),
1152                           &vfio_rtl_address_quirk, rtl,
1153                           "vfio-rtl8168-window-address-quirk", 4);
1154     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
1155                                         0x74, &quirk->mem[0], 1);
1156 
1157     memory_region_init_io(&quirk->mem[1], OBJECT(vdev),
1158                           &vfio_rtl_data_quirk, rtl,
1159                           "vfio-rtl8168-window-data-quirk", 4);
1160     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
1161                                         0x70, &quirk->mem[1], 1);
1162 
1163     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1164 
1165     trace_vfio_quirk_rtl8168_probe(vdev->vbasedev.name);
1166 }
1167 
1168 /*
1169  * Intel IGD support
1170  *
1171  * Obviously IGD is not a discrete device, this is evidenced not only by it
1172  * being integrated into the CPU, but by the various chipset and BIOS
1173  * dependencies that it brings along with it.  Intel is trying to move away
1174  * from this and Broadwell and newer devices can run in what Intel calls
1175  * "Universal Pass-Through" mode, or UPT.  Theoretically in UPT mode, nothing
1176  * more is required beyond assigning the IGD device to a VM.  There are
1177  * however support limitations to this mode.  It only supports IGD as a
1178  * secondary graphics device in the VM and it doesn't officially support any
1179  * physical outputs.
1180  *
1181  * The code here attempts to enable what we'll call legacy mode assignment,
1182  * IGD retains most of the capabilities we expect for it to have on bare
1183  * metal.  To enable this mode, the IGD device must be assigned to the VM
1184  * at PCI address 00:02.0, it must have a ROM, it very likely needs VGA
1185  * support, we must have VM BIOS support for reserving and populating some
1186  * of the required tables, and we need to tweak the chipset with revisions
1187  * and IDs and an LPC/ISA bridge device.  The intention is to make all of
1188  * this happen automatically by installing the device at the correct VM PCI
1189  * bus address.  If any of the conditions are not met, we cross our fingers
1190  * and hope the user knows better.
1191  *
1192  * NB - It is possible to enable physical outputs in UPT mode by supplying
1193  * an OpRegion table.  We don't do this by default because the guest driver
1194  * behaves differently if an OpRegion is provided and no monitor is attached
1195  * vs no OpRegion and a monitor being attached or not.  Effectively, if a
1196  * headless setup is desired, the OpRegion gets in the way of that.
1197  */
1198 
1199 /*
1200  * This presumes the device is already known to be an Intel VGA device, so we
1201  * take liberties in which device ID bits match which generation.  This should
1202  * not be taken as an indication that all the devices are supported, or even
1203  * supportable, some of them don't even support VT-d.
1204  * See linux:include/drm/i915_pciids.h for IDs.
1205  */
1206 static int igd_gen(VFIOPCIDevice *vdev)
1207 {
1208     if ((vdev->device_id & 0xfff) == 0xa84) {
1209         return 8; /* Broxton */
1210     }
1211 
1212     switch (vdev->device_id & 0xff00) {
1213     /* Old, untested, unavailable, unknown */
1214     case 0x0000:
1215     case 0x2500:
1216     case 0x2700:
1217     case 0x2900:
1218     case 0x2a00:
1219     case 0x2e00:
1220     case 0x3500:
1221     case 0xa000:
1222         return -1;
1223     /* SandyBridge, IvyBridge, ValleyView, Haswell */
1224     case 0x0100:
1225     case 0x0400:
1226     case 0x0a00:
1227     case 0x0c00:
1228     case 0x0d00:
1229     case 0x0f00:
1230         return 6;
1231     /* BroadWell, CherryView, SkyLake, KabyLake */
1232     case 0x1600:
1233     case 0x1900:
1234     case 0x2200:
1235     case 0x5900:
1236         return 8;
1237     }
1238 
1239     return 8; /* Assume newer is compatible */
1240 }
1241 
1242 typedef struct VFIOIGDQuirk {
1243     struct VFIOPCIDevice *vdev;
1244     uint32_t index;
1245     uint32_t bdsm;
1246 } VFIOIGDQuirk;
1247 
1248 #define IGD_GMCH 0x50 /* Graphics Control Register */
1249 #define IGD_BDSM 0x5c /* Base Data of Stolen Memory */
1250 #define IGD_ASLS 0xfc /* ASL Storage Register */
1251 
1252 /*
1253  * The OpRegion includes the Video BIOS Table, which seems important for
1254  * telling the driver what sort of outputs it has.  Without this, the device
1255  * may work in the guest, but we may not get output.  This also requires BIOS
1256  * support to reserve and populate a section of guest memory sufficient for
1257  * the table and to write the base address of that memory to the ASLS register
1258  * of the IGD device.
1259  */
1260 int vfio_pci_igd_opregion_init(VFIOPCIDevice *vdev,
1261                                struct vfio_region_info *info, Error **errp)
1262 {
1263     int ret;
1264 
1265     vdev->igd_opregion = g_malloc0(info->size);
1266     ret = pread(vdev->vbasedev.fd, vdev->igd_opregion,
1267                 info->size, info->offset);
1268     if (ret != info->size) {
1269         error_setg(errp, "failed to read IGD OpRegion");
1270         g_free(vdev->igd_opregion);
1271         vdev->igd_opregion = NULL;
1272         return -EINVAL;
1273     }
1274 
1275     /*
1276      * Provide fw_cfg with a copy of the OpRegion which the VM firmware is to
1277      * allocate 32bit reserved memory for, copy these contents into, and write
1278      * the reserved memory base address to the device ASLS register at 0xFC.
1279      * Alignment of this reserved region seems flexible, but using a 4k page
1280      * alignment seems to work well.  This interface assumes a single IGD
1281      * device, which may be at VM address 00:02.0 in legacy mode or another
1282      * address in UPT mode.
1283      *
1284      * NB, there may be future use cases discovered where the VM should have
1285      * direct interaction with the host OpRegion, in which case the write to
1286      * the ASLS register would trigger MemoryRegion setup to enable that.
1287      */
1288     fw_cfg_add_file(fw_cfg_find(), "etc/igd-opregion",
1289                     vdev->igd_opregion, info->size);
1290 
1291     trace_vfio_pci_igd_opregion_enabled(vdev->vbasedev.name);
1292 
1293     pci_set_long(vdev->pdev.config + IGD_ASLS, 0);
1294     pci_set_long(vdev->pdev.wmask + IGD_ASLS, ~0);
1295     pci_set_long(vdev->emulated_config_bits + IGD_ASLS, ~0);
1296 
1297     return 0;
1298 }
1299 
1300 /*
1301  * The rather short list of registers that we copy from the host devices.
1302  * The LPC/ISA bridge values are definitely needed to support the vBIOS, the
1303  * host bridge values may or may not be needed depending on the guest OS.
1304  * Since we're only munging revision and subsystem values on the host bridge,
1305  * we don't require our own device.  The LPC/ISA bridge needs to be our very
1306  * own though.
1307  */
1308 typedef struct {
1309     uint8_t offset;
1310     uint8_t len;
1311 } IGDHostInfo;
1312 
1313 static const IGDHostInfo igd_host_bridge_infos[] = {
1314     {PCI_REVISION_ID,         2},
1315     {PCI_SUBSYSTEM_VENDOR_ID, 2},
1316     {PCI_SUBSYSTEM_ID,        2},
1317 };
1318 
1319 static const IGDHostInfo igd_lpc_bridge_infos[] = {
1320     {PCI_VENDOR_ID,           2},
1321     {PCI_DEVICE_ID,           2},
1322     {PCI_REVISION_ID,         2},
1323     {PCI_SUBSYSTEM_VENDOR_ID, 2},
1324     {PCI_SUBSYSTEM_ID,        2},
1325 };
1326 
1327 static int vfio_pci_igd_copy(VFIOPCIDevice *vdev, PCIDevice *pdev,
1328                              struct vfio_region_info *info,
1329                              const IGDHostInfo *list, int len)
1330 {
1331     int i, ret;
1332 
1333     for (i = 0; i < len; i++) {
1334         ret = pread(vdev->vbasedev.fd, pdev->config + list[i].offset,
1335                     list[i].len, info->offset + list[i].offset);
1336         if (ret != list[i].len) {
1337             error_report("IGD copy failed: %m");
1338             return -errno;
1339         }
1340     }
1341 
1342     return 0;
1343 }
1344 
1345 /*
1346  * Stuff a few values into the host bridge.
1347  */
1348 static int vfio_pci_igd_host_init(VFIOPCIDevice *vdev,
1349                                   struct vfio_region_info *info)
1350 {
1351     PCIBus *bus;
1352     PCIDevice *host_bridge;
1353     int ret;
1354 
1355     bus = pci_device_root_bus(&vdev->pdev);
1356     host_bridge = pci_find_device(bus, 0, PCI_DEVFN(0, 0));
1357 
1358     if (!host_bridge) {
1359         error_report("Can't find host bridge");
1360         return -ENODEV;
1361     }
1362 
1363     ret = vfio_pci_igd_copy(vdev, host_bridge, info, igd_host_bridge_infos,
1364                             ARRAY_SIZE(igd_host_bridge_infos));
1365     if (!ret) {
1366         trace_vfio_pci_igd_host_bridge_enabled(vdev->vbasedev.name);
1367     }
1368 
1369     return ret;
1370 }
1371 
1372 /*
1373  * IGD LPC/ISA bridge support code.  The vBIOS needs this, but we can't write
1374  * arbitrary values into just any bridge, so we must create our own.  We try
1375  * to handle if the user has created it for us, which they might want to do
1376  * to enable multifunction so we don't occupy the whole PCI slot.
1377  */
1378 static void vfio_pci_igd_lpc_bridge_realize(PCIDevice *pdev, Error **errp)
1379 {
1380     if (pdev->devfn != PCI_DEVFN(0x1f, 0)) {
1381         error_setg(errp, "VFIO dummy ISA/LPC bridge must have address 1f.0");
1382     }
1383 }
1384 
1385 static void vfio_pci_igd_lpc_bridge_class_init(ObjectClass *klass, void *data)
1386 {
1387     DeviceClass *dc = DEVICE_CLASS(klass);
1388     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1389 
1390     set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
1391     dc->desc = "VFIO dummy ISA/LPC bridge for IGD assignment";
1392     dc->hotpluggable = false;
1393     k->realize = vfio_pci_igd_lpc_bridge_realize;
1394     k->class_id = PCI_CLASS_BRIDGE_ISA;
1395 }
1396 
1397 static TypeInfo vfio_pci_igd_lpc_bridge_info = {
1398     .name = "vfio-pci-igd-lpc-bridge",
1399     .parent = TYPE_PCI_DEVICE,
1400     .class_init = vfio_pci_igd_lpc_bridge_class_init,
1401     .interfaces = (InterfaceInfo[]) {
1402         { INTERFACE_CONVENTIONAL_PCI_DEVICE },
1403         { },
1404     },
1405 };
1406 
1407 static void vfio_pci_igd_register_types(void)
1408 {
1409     type_register_static(&vfio_pci_igd_lpc_bridge_info);
1410 }
1411 
1412 type_init(vfio_pci_igd_register_types)
1413 
1414 static int vfio_pci_igd_lpc_init(VFIOPCIDevice *vdev,
1415                                  struct vfio_region_info *info)
1416 {
1417     PCIDevice *lpc_bridge;
1418     int ret;
1419 
1420     lpc_bridge = pci_find_device(pci_device_root_bus(&vdev->pdev),
1421                                  0, PCI_DEVFN(0x1f, 0));
1422     if (!lpc_bridge) {
1423         lpc_bridge = pci_create_simple(pci_device_root_bus(&vdev->pdev),
1424                                  PCI_DEVFN(0x1f, 0), "vfio-pci-igd-lpc-bridge");
1425     }
1426 
1427     ret = vfio_pci_igd_copy(vdev, lpc_bridge, info, igd_lpc_bridge_infos,
1428                             ARRAY_SIZE(igd_lpc_bridge_infos));
1429     if (!ret) {
1430         trace_vfio_pci_igd_lpc_bridge_enabled(vdev->vbasedev.name);
1431     }
1432 
1433     return ret;
1434 }
1435 
1436 /*
1437  * IGD Gen8 and newer support up to 8MB for the GTT and use a 64bit PTE
1438  * entry, older IGDs use 2MB and 32bit.  Each PTE maps a 4k page.  Therefore
1439  * we either have 2M/4k * 4 = 2k or 8M/4k * 8 = 16k as the maximum iobar index
1440  * for programming the GTT.
1441  *
1442  * See linux:include/drm/i915_drm.h for shift and mask values.
1443  */
1444 static int vfio_igd_gtt_max(VFIOPCIDevice *vdev)
1445 {
1446     uint32_t gmch = vfio_pci_read_config(&vdev->pdev, IGD_GMCH, sizeof(gmch));
1447     int ggms, gen = igd_gen(vdev);
1448 
1449     gmch = vfio_pci_read_config(&vdev->pdev, IGD_GMCH, sizeof(gmch));
1450     ggms = (gmch >> (gen < 8 ? 8 : 6)) & 0x3;
1451     if (gen > 6) {
1452         ggms = 1 << ggms;
1453     }
1454 
1455     ggms *= MiB;
1456 
1457     return (ggms / (4 * KiB)) * (gen < 8 ? 4 : 8);
1458 }
1459 
1460 /*
1461  * The IGD ROM will make use of stolen memory (GGMS) for support of VESA modes.
1462  * Somehow the host stolen memory range is used for this, but how the ROM gets
1463  * it is a mystery, perhaps it's hardcoded into the ROM.  Thankfully though, it
1464  * reprograms the GTT through the IOBAR where we can trap it and transpose the
1465  * programming to the VM allocated buffer.  That buffer gets reserved by the VM
1466  * firmware via the fw_cfg entry added below.  Here we're just monitoring the
1467  * IOBAR address and data registers to detect a write sequence targeting the
1468  * GTTADR.  This code is developed by observed behavior and doesn't have a
1469  * direct spec reference, unfortunately.
1470  */
1471 static uint64_t vfio_igd_quirk_data_read(void *opaque,
1472                                          hwaddr addr, unsigned size)
1473 {
1474     VFIOIGDQuirk *igd = opaque;
1475     VFIOPCIDevice *vdev = igd->vdev;
1476 
1477     igd->index = ~0;
1478 
1479     return vfio_region_read(&vdev->bars[4].region, addr + 4, size);
1480 }
1481 
1482 static void vfio_igd_quirk_data_write(void *opaque, hwaddr addr,
1483                                       uint64_t data, unsigned size)
1484 {
1485     VFIOIGDQuirk *igd = opaque;
1486     VFIOPCIDevice *vdev = igd->vdev;
1487     uint64_t val = data;
1488     int gen = igd_gen(vdev);
1489 
1490     /*
1491      * Programming the GGMS starts at index 0x1 and uses every 4th index (ie.
1492      * 0x1, 0x5, 0x9, 0xd,...).  For pre-Gen8 each 4-byte write is a whole PTE
1493      * entry, with 0th bit enable set.  For Gen8 and up, PTEs are 64bit, so
1494      * entries 0x5 & 0xd are the high dword, in our case zero.  Each PTE points
1495      * to a 4k page, which we translate to a page from the VM allocated region,
1496      * pointed to by the BDSM register.  If this is not set, we fail.
1497      *
1498      * We trap writes to the full configured GTT size, but we typically only
1499      * see the vBIOS writing up to (nearly) the 1MB barrier.  In fact it often
1500      * seems to miss the last entry for an even 1MB GTT.  Doing a gratuitous
1501      * write of that last entry does work, but is hopefully unnecessary since
1502      * we clear the previous GTT on initialization.
1503      */
1504     if ((igd->index % 4 == 1) && igd->index < vfio_igd_gtt_max(vdev)) {
1505         if (gen < 8 || (igd->index % 8 == 1)) {
1506             uint32_t base;
1507 
1508             base = pci_get_long(vdev->pdev.config + IGD_BDSM);
1509             if (!base) {
1510                 hw_error("vfio-igd: Guest attempted to program IGD GTT before "
1511                          "BIOS reserved stolen memory.  Unsupported BIOS?");
1512             }
1513 
1514             val = data - igd->bdsm + base;
1515         } else {
1516             val = 0; /* upper 32bits of pte, we only enable below 4G PTEs */
1517         }
1518 
1519         trace_vfio_pci_igd_bar4_write(vdev->vbasedev.name,
1520                                       igd->index, data, val);
1521     }
1522 
1523     vfio_region_write(&vdev->bars[4].region, addr + 4, val, size);
1524 
1525     igd->index = ~0;
1526 }
1527 
1528 static const MemoryRegionOps vfio_igd_data_quirk = {
1529     .read = vfio_igd_quirk_data_read,
1530     .write = vfio_igd_quirk_data_write,
1531     .endianness = DEVICE_LITTLE_ENDIAN,
1532 };
1533 
1534 static uint64_t vfio_igd_quirk_index_read(void *opaque,
1535                                           hwaddr addr, unsigned size)
1536 {
1537     VFIOIGDQuirk *igd = opaque;
1538     VFIOPCIDevice *vdev = igd->vdev;
1539 
1540     igd->index = ~0;
1541 
1542     return vfio_region_read(&vdev->bars[4].region, addr, size);
1543 }
1544 
1545 static void vfio_igd_quirk_index_write(void *opaque, hwaddr addr,
1546                                        uint64_t data, unsigned size)
1547 {
1548     VFIOIGDQuirk *igd = opaque;
1549     VFIOPCIDevice *vdev = igd->vdev;
1550 
1551     igd->index = data;
1552 
1553     vfio_region_write(&vdev->bars[4].region, addr, data, size);
1554 }
1555 
1556 static const MemoryRegionOps vfio_igd_index_quirk = {
1557     .read = vfio_igd_quirk_index_read,
1558     .write = vfio_igd_quirk_index_write,
1559     .endianness = DEVICE_LITTLE_ENDIAN,
1560 };
1561 
1562 static void vfio_probe_igd_bar4_quirk(VFIOPCIDevice *vdev, int nr)
1563 {
1564     struct vfio_region_info *rom = NULL, *opregion = NULL,
1565                             *host = NULL, *lpc = NULL;
1566     VFIOQuirk *quirk;
1567     VFIOIGDQuirk *igd;
1568     PCIDevice *lpc_bridge;
1569     int i, ret, ggms_mb, gms_mb = 0, gen;
1570     uint64_t *bdsm_size;
1571     uint32_t gmch;
1572     uint16_t cmd_orig, cmd;
1573     Error *err = NULL;
1574 
1575     /*
1576      * This must be an Intel VGA device at address 00:02.0 for us to even
1577      * consider enabling legacy mode.  The vBIOS has dependencies on the
1578      * PCI bus address.
1579      */
1580     if (!vfio_pci_is(vdev, PCI_VENDOR_ID_INTEL, PCI_ANY_ID) ||
1581         !vfio_is_vga(vdev) || nr != 4 ||
1582         &vdev->pdev != pci_find_device(pci_device_root_bus(&vdev->pdev),
1583                                        0, PCI_DEVFN(0x2, 0))) {
1584         return;
1585     }
1586 
1587     /*
1588      * We need to create an LPC/ISA bridge at PCI bus address 00:1f.0 that we
1589      * can stuff host values into, so if there's already one there and it's not
1590      * one we can hack on, legacy mode is no-go.  Sorry Q35.
1591      */
1592     lpc_bridge = pci_find_device(pci_device_root_bus(&vdev->pdev),
1593                                  0, PCI_DEVFN(0x1f, 0));
1594     if (lpc_bridge && !object_dynamic_cast(OBJECT(lpc_bridge),
1595                                            "vfio-pci-igd-lpc-bridge")) {
1596         error_report("IGD device %s cannot support legacy mode due to existing "
1597                      "devices at address 1f.0", vdev->vbasedev.name);
1598         return;
1599     }
1600 
1601     /*
1602      * IGD is not a standard, they like to change their specs often.  We
1603      * only attempt to support back to SandBridge and we hope that newer
1604      * devices maintain compatibility with generation 8.
1605      */
1606     gen = igd_gen(vdev);
1607     if (gen != 6 && gen != 8) {
1608         error_report("IGD device %s is unsupported in legacy mode, "
1609                      "try SandyBridge or newer", vdev->vbasedev.name);
1610         return;
1611     }
1612 
1613     /*
1614      * Most of what we're doing here is to enable the ROM to run, so if
1615      * there's no ROM, there's no point in setting up this quirk.
1616      * NB. We only seem to get BIOS ROMs, so a UEFI VM would need CSM support.
1617      */
1618     ret = vfio_get_region_info(&vdev->vbasedev,
1619                                VFIO_PCI_ROM_REGION_INDEX, &rom);
1620     if ((ret || !rom->size) && !vdev->pdev.romfile) {
1621         error_report("IGD device %s has no ROM, legacy mode disabled",
1622                      vdev->vbasedev.name);
1623         goto out;
1624     }
1625 
1626     /*
1627      * Ignore the hotplug corner case, mark the ROM failed, we can't
1628      * create the devices we need for legacy mode in the hotplug scenario.
1629      */
1630     if (vdev->pdev.qdev.hotplugged) {
1631         error_report("IGD device %s hotplugged, ROM disabled, "
1632                      "legacy mode disabled", vdev->vbasedev.name);
1633         vdev->rom_read_failed = true;
1634         goto out;
1635     }
1636 
1637     /*
1638      * Check whether we have all the vfio device specific regions to
1639      * support legacy mode (added in Linux v4.6).  If not, bail.
1640      */
1641     ret = vfio_get_dev_region_info(&vdev->vbasedev,
1642                         VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
1643                         VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion);
1644     if (ret) {
1645         error_report("IGD device %s does not support OpRegion access,"
1646                      "legacy mode disabled", vdev->vbasedev.name);
1647         goto out;
1648     }
1649 
1650     ret = vfio_get_dev_region_info(&vdev->vbasedev,
1651                         VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
1652                         VFIO_REGION_SUBTYPE_INTEL_IGD_HOST_CFG, &host);
1653     if (ret) {
1654         error_report("IGD device %s does not support host bridge access,"
1655                      "legacy mode disabled", vdev->vbasedev.name);
1656         goto out;
1657     }
1658 
1659     ret = vfio_get_dev_region_info(&vdev->vbasedev,
1660                         VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,
1661                         VFIO_REGION_SUBTYPE_INTEL_IGD_LPC_CFG, &lpc);
1662     if (ret) {
1663         error_report("IGD device %s does not support LPC bridge access,"
1664                      "legacy mode disabled", vdev->vbasedev.name);
1665         goto out;
1666     }
1667 
1668     gmch = vfio_pci_read_config(&vdev->pdev, IGD_GMCH, 4);
1669 
1670     /*
1671      * If IGD VGA Disable is clear (expected) and VGA is not already enabled,
1672      * try to enable it.  Probably shouldn't be using legacy mode without VGA,
1673      * but also no point in us enabling VGA if disabled in hardware.
1674      */
1675     if (!(gmch & 0x2) && !vdev->vga && vfio_populate_vga(vdev, &err)) {
1676         error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
1677         error_report("IGD device %s failed to enable VGA access, "
1678                      "legacy mode disabled", vdev->vbasedev.name);
1679         goto out;
1680     }
1681 
1682     /* Create our LPC/ISA bridge */
1683     ret = vfio_pci_igd_lpc_init(vdev, lpc);
1684     if (ret) {
1685         error_report("IGD device %s failed to create LPC bridge, "
1686                      "legacy mode disabled", vdev->vbasedev.name);
1687         goto out;
1688     }
1689 
1690     /* Stuff some host values into the VM PCI host bridge */
1691     ret = vfio_pci_igd_host_init(vdev, host);
1692     if (ret) {
1693         error_report("IGD device %s failed to modify host bridge, "
1694                      "legacy mode disabled", vdev->vbasedev.name);
1695         goto out;
1696     }
1697 
1698     /* Setup OpRegion access */
1699     ret = vfio_pci_igd_opregion_init(vdev, opregion, &err);
1700     if (ret) {
1701         error_append_hint(&err, "IGD legacy mode disabled\n");
1702         error_reportf_err(err, VFIO_MSG_PREFIX, vdev->vbasedev.name);
1703         goto out;
1704     }
1705 
1706     /* Setup our quirk to munge GTT addresses to the VM allocated buffer */
1707     quirk = vfio_quirk_alloc(2);
1708     igd = quirk->data = g_malloc0(sizeof(*igd));
1709     igd->vdev = vdev;
1710     igd->index = ~0;
1711     igd->bdsm = vfio_pci_read_config(&vdev->pdev, IGD_BDSM, 4);
1712     igd->bdsm &= ~((1 * MiB) - 1); /* 1MB aligned */
1713 
1714     memory_region_init_io(&quirk->mem[0], OBJECT(vdev), &vfio_igd_index_quirk,
1715                           igd, "vfio-igd-index-quirk", 4);
1716     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
1717                                         0, &quirk->mem[0], 1);
1718 
1719     memory_region_init_io(&quirk->mem[1], OBJECT(vdev), &vfio_igd_data_quirk,
1720                           igd, "vfio-igd-data-quirk", 4);
1721     memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,
1722                                         4, &quirk->mem[1], 1);
1723 
1724     QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);
1725 
1726     /* Determine the size of stolen memory needed for GTT */
1727     ggms_mb = (gmch >> (gen < 8 ? 8 : 6)) & 0x3;
1728     if (gen > 6) {
1729         ggms_mb = 1 << ggms_mb;
1730     }
1731 
1732     /*
1733      * Assume we have no GMS memory, but allow it to be overrided by device
1734      * option (experimental).  The spec doesn't actually allow zero GMS when
1735      * when IVD (IGD VGA Disable) is clear, but the claim is that it's unused,
1736      * so let's not waste VM memory for it.
1737      */
1738     gmch &= ~((gen < 8 ? 0x1f : 0xff) << (gen < 8 ? 3 : 8));
1739 
1740     if (vdev->igd_gms) {
1741         if (vdev->igd_gms <= 0x10) {
1742             gms_mb = vdev->igd_gms * 32;
1743             gmch |= vdev->igd_gms << (gen < 8 ? 3 : 8);
1744         } else {
1745             error_report("Unsupported IGD GMS value 0x%x", vdev->igd_gms);
1746             vdev->igd_gms = 0;
1747         }
1748     }
1749 
1750     /*
1751      * Request reserved memory for stolen memory via fw_cfg.  VM firmware
1752      * must allocate a 1MB aligned reserved memory region below 4GB with
1753      * the requested size (in bytes) for use by the Intel PCI class VGA
1754      * device at VM address 00:02.0.  The base address of this reserved
1755      * memory region must be written to the device BDSM regsiter at PCI
1756      * config offset 0x5C.
1757      */
1758     bdsm_size = g_malloc(sizeof(*bdsm_size));
1759     *bdsm_size = cpu_to_le64((ggms_mb + gms_mb) * MiB);
1760     fw_cfg_add_file(fw_cfg_find(), "etc/igd-bdsm-size",
1761                     bdsm_size, sizeof(*bdsm_size));
1762 
1763     /* GMCH is read-only, emulated */
1764     pci_set_long(vdev->pdev.config + IGD_GMCH, gmch);
1765     pci_set_long(vdev->pdev.wmask + IGD_GMCH, 0);
1766     pci_set_long(vdev->emulated_config_bits + IGD_GMCH, ~0);
1767 
1768     /* BDSM is read-write, emulated.  The BIOS needs to be able to write it */
1769     pci_set_long(vdev->pdev.config + IGD_BDSM, 0);
1770     pci_set_long(vdev->pdev.wmask + IGD_BDSM, ~0);
1771     pci_set_long(vdev->emulated_config_bits + IGD_BDSM, ~0);
1772 
1773     /*
1774      * This IOBAR gives us access to GTTADR, which allows us to write to
1775      * the GTT itself.  So let's go ahead and write zero to all the GTT
1776      * entries to avoid spurious DMA faults.  Be sure I/O access is enabled
1777      * before talking to the device.
1778      */
1779     if (pread(vdev->vbasedev.fd, &cmd_orig, sizeof(cmd_orig),
1780               vdev->config_offset + PCI_COMMAND) != sizeof(cmd_orig)) {
1781         error_report("IGD device %s - failed to read PCI command register",
1782                      vdev->vbasedev.name);
1783     }
1784 
1785     cmd = cmd_orig | PCI_COMMAND_IO;
1786 
1787     if (pwrite(vdev->vbasedev.fd, &cmd, sizeof(cmd),
1788                vdev->config_offset + PCI_COMMAND) != sizeof(cmd)) {
1789         error_report("IGD device %s - failed to write PCI command register",
1790                      vdev->vbasedev.name);
1791     }
1792 
1793     for (i = 1; i < vfio_igd_gtt_max(vdev); i += 4) {
1794         vfio_region_write(&vdev->bars[4].region, 0, i, 4);
1795         vfio_region_write(&vdev->bars[4].region, 4, 0, 4);
1796     }
1797 
1798     if (pwrite(vdev->vbasedev.fd, &cmd_orig, sizeof(cmd_orig),
1799                vdev->config_offset + PCI_COMMAND) != sizeof(cmd_orig)) {
1800         error_report("IGD device %s - failed to restore PCI command register",
1801                      vdev->vbasedev.name);
1802     }
1803 
1804     trace_vfio_pci_igd_bdsm_enabled(vdev->vbasedev.name, ggms_mb + gms_mb);
1805 
1806 out:
1807     g_free(rom);
1808     g_free(opregion);
1809     g_free(host);
1810     g_free(lpc);
1811 }
1812 
1813 /*
1814  * Common quirk probe entry points.
1815  */
1816 void vfio_vga_quirk_setup(VFIOPCIDevice *vdev)
1817 {
1818     vfio_vga_probe_ati_3c3_quirk(vdev);
1819     vfio_vga_probe_nvidia_3d0_quirk(vdev);
1820 }
1821 
1822 void vfio_vga_quirk_exit(VFIOPCIDevice *vdev)
1823 {
1824     VFIOQuirk *quirk;
1825     int i, j;
1826 
1827     for (i = 0; i < ARRAY_SIZE(vdev->vga->region); i++) {
1828         QLIST_FOREACH(quirk, &vdev->vga->region[i].quirks, next) {
1829             for (j = 0; j < quirk->nr_mem; j++) {
1830                 memory_region_del_subregion(&vdev->vga->region[i].mem,
1831                                             &quirk->mem[j]);
1832             }
1833         }
1834     }
1835 }
1836 
1837 void vfio_vga_quirk_finalize(VFIOPCIDevice *vdev)
1838 {
1839     int i, j;
1840 
1841     for (i = 0; i < ARRAY_SIZE(vdev->vga->region); i++) {
1842         while (!QLIST_EMPTY(&vdev->vga->region[i].quirks)) {
1843             VFIOQuirk *quirk = QLIST_FIRST(&vdev->vga->region[i].quirks);
1844             QLIST_REMOVE(quirk, next);
1845             for (j = 0; j < quirk->nr_mem; j++) {
1846                 object_unparent(OBJECT(&quirk->mem[j]));
1847             }
1848             g_free(quirk->mem);
1849             g_free(quirk->data);
1850             g_free(quirk);
1851         }
1852     }
1853 }
1854 
1855 void vfio_bar_quirk_setup(VFIOPCIDevice *vdev, int nr)
1856 {
1857     vfio_probe_ati_bar4_quirk(vdev, nr);
1858     vfio_probe_ati_bar2_quirk(vdev, nr);
1859     vfio_probe_nvidia_bar5_quirk(vdev, nr);
1860     vfio_probe_nvidia_bar0_quirk(vdev, nr);
1861     vfio_probe_rtl8168_bar2_quirk(vdev, nr);
1862     vfio_probe_igd_bar4_quirk(vdev, nr);
1863 }
1864 
1865 void vfio_bar_quirk_exit(VFIOPCIDevice *vdev, int nr)
1866 {
1867     VFIOBAR *bar = &vdev->bars[nr];
1868     VFIOQuirk *quirk;
1869     int i;
1870 
1871     QLIST_FOREACH(quirk, &bar->quirks, next) {
1872         while (!QLIST_EMPTY(&quirk->ioeventfds)) {
1873             vfio_ioeventfd_exit(vdev, QLIST_FIRST(&quirk->ioeventfds));
1874         }
1875 
1876         for (i = 0; i < quirk->nr_mem; i++) {
1877             memory_region_del_subregion(bar->region.mem, &quirk->mem[i]);
1878         }
1879     }
1880 }
1881 
1882 void vfio_bar_quirk_finalize(VFIOPCIDevice *vdev, int nr)
1883 {
1884     VFIOBAR *bar = &vdev->bars[nr];
1885     int i;
1886 
1887     while (!QLIST_EMPTY(&bar->quirks)) {
1888         VFIOQuirk *quirk = QLIST_FIRST(&bar->quirks);
1889         QLIST_REMOVE(quirk, next);
1890         for (i = 0; i < quirk->nr_mem; i++) {
1891             object_unparent(OBJECT(&quirk->mem[i]));
1892         }
1893         g_free(quirk->mem);
1894         g_free(quirk->data);
1895         g_free(quirk);
1896     }
1897 }
1898 
1899 /*
1900  * Reset quirks
1901  */
1902 void vfio_quirk_reset(VFIOPCIDevice *vdev)
1903 {
1904     int i;
1905 
1906     for (i = 0; i < PCI_ROM_SLOT; i++) {
1907         VFIOQuirk *quirk;
1908         VFIOBAR *bar = &vdev->bars[i];
1909 
1910         QLIST_FOREACH(quirk, &bar->quirks, next) {
1911             if (quirk->reset) {
1912                 quirk->reset(vdev, quirk);
1913             }
1914         }
1915     }
1916 }
1917 
1918 /*
1919  * AMD Radeon PCI config reset, based on Linux:
1920  *   drivers/gpu/drm/radeon/ci_smc.c:ci_is_smc_running()
1921  *   drivers/gpu/drm/radeon/radeon_device.c:radeon_pci_config_reset
1922  *   drivers/gpu/drm/radeon/ci_smc.c:ci_reset_smc()
1923  *   drivers/gpu/drm/radeon/ci_smc.c:ci_stop_smc_clock()
1924  * IDs: include/drm/drm_pciids.h
1925  * Registers: http://cgit.freedesktop.org/~agd5f/linux/commit/?id=4e2aa447f6f0
1926  *
1927  * Bonaire and Hawaii GPUs do not respond to a bus reset.  This is a bug in the
1928  * hardware that should be fixed on future ASICs.  The symptom of this is that
1929  * once the accerlated driver loads, Windows guests will bsod on subsequent
1930  * attmpts to load the driver, such as after VM reset or shutdown/restart.  To
1931  * work around this, we do an AMD specific PCI config reset, followed by an SMC
1932  * reset.  The PCI config reset only works if SMC firmware is running, so we
1933  * have a dependency on the state of the device as to whether this reset will
1934  * be effective.  There are still cases where we won't be able to kick the
1935  * device into working, but this greatly improves the usability overall.  The
1936  * config reset magic is relatively common on AMD GPUs, but the setup and SMC
1937  * poking is largely ASIC specific.
1938  */
1939 static bool vfio_radeon_smc_is_running(VFIOPCIDevice *vdev)
1940 {
1941     uint32_t clk, pc_c;
1942 
1943     /*
1944      * Registers 200h and 204h are index and data registers for accessing
1945      * indirect configuration registers within the device.
1946      */
1947     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000004, 4);
1948     clk = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
1949     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000370, 4);
1950     pc_c = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
1951 
1952     return (!(clk & 1) && (0x20100 <= pc_c));
1953 }
1954 
1955 /*
1956  * The scope of a config reset is controlled by a mode bit in the misc register
1957  * and a fuse, exposed as a bit in another register.  The fuse is the default
1958  * (0 = GFX, 1 = whole GPU), the misc bit is a toggle, with the forumula
1959  * scope = !(misc ^ fuse), where the resulting scope is defined the same as
1960  * the fuse.  A truth table therefore tells us that if misc == fuse, we need
1961  * to flip the value of the bit in the misc register.
1962  */
1963 static void vfio_radeon_set_gfx_only_reset(VFIOPCIDevice *vdev)
1964 {
1965     uint32_t misc, fuse;
1966     bool a, b;
1967 
1968     vfio_region_write(&vdev->bars[5].region, 0x200, 0xc00c0000, 4);
1969     fuse = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
1970     b = fuse & 64;
1971 
1972     vfio_region_write(&vdev->bars[5].region, 0x200, 0xc0000010, 4);
1973     misc = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
1974     a = misc & 2;
1975 
1976     if (a == b) {
1977         vfio_region_write(&vdev->bars[5].region, 0x204, misc ^ 2, 4);
1978         vfio_region_read(&vdev->bars[5].region, 0x204, 4); /* flush */
1979     }
1980 }
1981 
1982 static int vfio_radeon_reset(VFIOPCIDevice *vdev)
1983 {
1984     PCIDevice *pdev = &vdev->pdev;
1985     int i, ret = 0;
1986     uint32_t data;
1987 
1988     /* Defer to a kernel implemented reset */
1989     if (vdev->vbasedev.reset_works) {
1990         trace_vfio_quirk_ati_bonaire_reset_skipped(vdev->vbasedev.name);
1991         return -ENODEV;
1992     }
1993 
1994     /* Enable only memory BAR access */
1995     vfio_pci_write_config(pdev, PCI_COMMAND, PCI_COMMAND_MEMORY, 2);
1996 
1997     /* Reset only works if SMC firmware is loaded and running */
1998     if (!vfio_radeon_smc_is_running(vdev)) {
1999         ret = -EINVAL;
2000         trace_vfio_quirk_ati_bonaire_reset_no_smc(vdev->vbasedev.name);
2001         goto out;
2002     }
2003 
2004     /* Make sure only the GFX function is reset */
2005     vfio_radeon_set_gfx_only_reset(vdev);
2006 
2007     /* AMD PCI config reset */
2008     vfio_pci_write_config(pdev, 0x7c, 0x39d5e86b, 4);
2009     usleep(100);
2010 
2011     /* Read back the memory size to make sure we're out of reset */
2012     for (i = 0; i < 100000; i++) {
2013         if (vfio_region_read(&vdev->bars[5].region, 0x5428, 4) != 0xffffffff) {
2014             goto reset_smc;
2015         }
2016         usleep(1);
2017     }
2018 
2019     trace_vfio_quirk_ati_bonaire_reset_timeout(vdev->vbasedev.name);
2020 
2021 reset_smc:
2022     /* Reset SMC */
2023     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000000, 4);
2024     data = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
2025     data |= 1;
2026     vfio_region_write(&vdev->bars[5].region, 0x204, data, 4);
2027 
2028     /* Disable SMC clock */
2029     vfio_region_write(&vdev->bars[5].region, 0x200, 0x80000004, 4);
2030     data = vfio_region_read(&vdev->bars[5].region, 0x204, 4);
2031     data |= 1;
2032     vfio_region_write(&vdev->bars[5].region, 0x204, data, 4);
2033 
2034     trace_vfio_quirk_ati_bonaire_reset_done(vdev->vbasedev.name);
2035 
2036 out:
2037     /* Restore PCI command register */
2038     vfio_pci_write_config(pdev, PCI_COMMAND, 0, 2);
2039 
2040     return ret;
2041 }
2042 
2043 void vfio_setup_resetfn_quirk(VFIOPCIDevice *vdev)
2044 {
2045     switch (vdev->vendor_id) {
2046     case 0x1002:
2047         switch (vdev->device_id) {
2048         /* Bonaire */
2049         case 0x6649: /* Bonaire [FirePro W5100] */
2050         case 0x6650:
2051         case 0x6651:
2052         case 0x6658: /* Bonaire XTX [Radeon R7 260X] */
2053         case 0x665c: /* Bonaire XT [Radeon HD 7790/8770 / R9 260 OEM] */
2054         case 0x665d: /* Bonaire [Radeon R7 200 Series] */
2055         /* Hawaii */
2056         case 0x67A0: /* Hawaii XT GL [FirePro W9100] */
2057         case 0x67A1: /* Hawaii PRO GL [FirePro W8100] */
2058         case 0x67A2:
2059         case 0x67A8:
2060         case 0x67A9:
2061         case 0x67AA:
2062         case 0x67B0: /* Hawaii XT [Radeon R9 290X] */
2063         case 0x67B1: /* Hawaii PRO [Radeon R9 290] */
2064         case 0x67B8:
2065         case 0x67B9:
2066         case 0x67BA:
2067         case 0x67BE:
2068             vdev->resetfn = vfio_radeon_reset;
2069             trace_vfio_quirk_ati_bonaire_reset(vdev->vbasedev.name);
2070             break;
2071         }
2072         break;
2073     }
2074 }
2075 
2076 /*
2077  * The NVIDIA GPUDirect P2P Vendor capability allows the user to specify
2078  * devices as a member of a clique.  Devices within the same clique ID
2079  * are capable of direct P2P.  It's the user's responsibility that this
2080  * is correct.  The spec says that this may reside at any unused config
2081  * offset, but reserves and recommends hypervisors place this at C8h.
2082  * The spec also states that the hypervisor should place this capability
2083  * at the end of the capability list, thus next is defined as 0h.
2084  *
2085  * +----------------+----------------+----------------+----------------+
2086  * | sig 7:0 ('P')  |  vndr len (8h) |    next (0h)   |   cap id (9h)  |
2087  * +----------------+----------------+----------------+----------------+
2088  * | rsvd 15:7(0h),id 6:3,ver 2:0(0h)|          sig 23:8 ('P2')        |
2089  * +---------------------------------+---------------------------------+
2090  *
2091  * https://lists.gnu.org/archive/html/qemu-devel/2017-08/pdfUda5iEpgOS.pdf
2092  */
2093 static void get_nv_gpudirect_clique_id(Object *obj, Visitor *v,
2094                                        const char *name, void *opaque,
2095                                        Error **errp)
2096 {
2097     DeviceState *dev = DEVICE(obj);
2098     Property *prop = opaque;
2099     uint8_t *ptr = qdev_get_prop_ptr(dev, prop);
2100 
2101     visit_type_uint8(v, name, ptr, errp);
2102 }
2103 
2104 static void set_nv_gpudirect_clique_id(Object *obj, Visitor *v,
2105                                        const char *name, void *opaque,
2106                                        Error **errp)
2107 {
2108     DeviceState *dev = DEVICE(obj);
2109     Property *prop = opaque;
2110     uint8_t value, *ptr = qdev_get_prop_ptr(dev, prop);
2111     Error *local_err = NULL;
2112 
2113     if (dev->realized) {
2114         qdev_prop_set_after_realize(dev, name, errp);
2115         return;
2116     }
2117 
2118     visit_type_uint8(v, name, &value, &local_err);
2119     if (local_err) {
2120         error_propagate(errp, local_err);
2121         return;
2122     }
2123 
2124     if (value & ~0xF) {
2125         error_setg(errp, "Property %s: valid range 0-15", name);
2126         return;
2127     }
2128 
2129     *ptr = value;
2130 }
2131 
2132 const PropertyInfo qdev_prop_nv_gpudirect_clique = {
2133     .name = "uint4",
2134     .description = "NVIDIA GPUDirect Clique ID (0 - 15)",
2135     .get = get_nv_gpudirect_clique_id,
2136     .set = set_nv_gpudirect_clique_id,
2137 };
2138 
2139 static int vfio_add_nv_gpudirect_cap(VFIOPCIDevice *vdev, Error **errp)
2140 {
2141     PCIDevice *pdev = &vdev->pdev;
2142     int ret, pos = 0xC8;
2143 
2144     if (vdev->nv_gpudirect_clique == 0xFF) {
2145         return 0;
2146     }
2147 
2148     if (!vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID)) {
2149         error_setg(errp, "NVIDIA GPUDirect Clique ID: invalid device vendor");
2150         return -EINVAL;
2151     }
2152 
2153     if (pci_get_byte(pdev->config + PCI_CLASS_DEVICE + 1) !=
2154         PCI_BASE_CLASS_DISPLAY) {
2155         error_setg(errp, "NVIDIA GPUDirect Clique ID: unsupported PCI class");
2156         return -EINVAL;
2157     }
2158 
2159     ret = pci_add_capability(pdev, PCI_CAP_ID_VNDR, pos, 8, errp);
2160     if (ret < 0) {
2161         error_prepend(errp, "Failed to add NVIDIA GPUDirect cap: ");
2162         return ret;
2163     }
2164 
2165     memset(vdev->emulated_config_bits + pos, 0xFF, 8);
2166     pos += PCI_CAP_FLAGS;
2167     pci_set_byte(pdev->config + pos++, 8);
2168     pci_set_byte(pdev->config + pos++, 'P');
2169     pci_set_byte(pdev->config + pos++, '2');
2170     pci_set_byte(pdev->config + pos++, 'P');
2171     pci_set_byte(pdev->config + pos++, vdev->nv_gpudirect_clique << 3);
2172     pci_set_byte(pdev->config + pos, 0);
2173 
2174     return 0;
2175 }
2176 
2177 int vfio_add_virt_caps(VFIOPCIDevice *vdev, Error **errp)
2178 {
2179     int ret;
2180 
2181     ret = vfio_add_nv_gpudirect_cap(vdev, errp);
2182     if (ret) {
2183         return ret;
2184     }
2185 
2186     return 0;
2187 }
2188 
2189 static void vfio_pci_nvlink2_get_tgt(Object *obj, Visitor *v,
2190                                      const char *name,
2191                                      void *opaque, Error **errp)
2192 {
2193     uint64_t tgt = (uintptr_t) opaque;
2194     visit_type_uint64(v, name, &tgt, errp);
2195 }
2196 
2197 static void vfio_pci_nvlink2_get_link_speed(Object *obj, Visitor *v,
2198                                                  const char *name,
2199                                                  void *opaque, Error **errp)
2200 {
2201     uint32_t link_speed = (uint32_t)(uintptr_t) opaque;
2202     visit_type_uint32(v, name, &link_speed, errp);
2203 }
2204 
2205 int vfio_pci_nvidia_v100_ram_init(VFIOPCIDevice *vdev, Error **errp)
2206 {
2207     int ret;
2208     void *p;
2209     struct vfio_region_info *nv2reg = NULL;
2210     struct vfio_info_cap_header *hdr;
2211     struct vfio_region_info_cap_nvlink2_ssatgt *cap;
2212     VFIOQuirk *quirk;
2213 
2214     ret = vfio_get_dev_region_info(&vdev->vbasedev,
2215                                    VFIO_REGION_TYPE_PCI_VENDOR_TYPE |
2216                                    PCI_VENDOR_ID_NVIDIA,
2217                                    VFIO_REGION_SUBTYPE_NVIDIA_NVLINK2_RAM,
2218                                    &nv2reg);
2219     if (ret) {
2220         return ret;
2221     }
2222 
2223     hdr = vfio_get_region_info_cap(nv2reg, VFIO_REGION_INFO_CAP_NVLINK2_SSATGT);
2224     if (!hdr) {
2225         ret = -ENODEV;
2226         goto free_exit;
2227     }
2228     cap = (void *) hdr;
2229 
2230     p = mmap(NULL, nv2reg->size, PROT_READ | PROT_WRITE | PROT_EXEC,
2231              MAP_SHARED, vdev->vbasedev.fd, nv2reg->offset);
2232     if (p == MAP_FAILED) {
2233         ret = -errno;
2234         goto free_exit;
2235     }
2236 
2237     quirk = vfio_quirk_alloc(1);
2238     memory_region_init_ram_ptr(&quirk->mem[0], OBJECT(vdev), "nvlink2-mr",
2239                                nv2reg->size, p);
2240     QLIST_INSERT_HEAD(&vdev->bars[0].quirks, quirk, next);
2241 
2242     object_property_add(OBJECT(vdev), "nvlink2-tgt", "uint64",
2243                         vfio_pci_nvlink2_get_tgt, NULL, NULL,
2244                         (void *) (uintptr_t) cap->tgt, NULL);
2245     trace_vfio_pci_nvidia_gpu_setup_quirk(vdev->vbasedev.name, cap->tgt,
2246                                           nv2reg->size);
2247 free_exit:
2248     g_free(nv2reg);
2249 
2250     return ret;
2251 }
2252 
2253 int vfio_pci_nvlink2_init(VFIOPCIDevice *vdev, Error **errp)
2254 {
2255     int ret;
2256     void *p;
2257     struct vfio_region_info *atsdreg = NULL;
2258     struct vfio_info_cap_header *hdr;
2259     struct vfio_region_info_cap_nvlink2_ssatgt *captgt;
2260     struct vfio_region_info_cap_nvlink2_lnkspd *capspeed;
2261     VFIOQuirk *quirk;
2262 
2263     ret = vfio_get_dev_region_info(&vdev->vbasedev,
2264                                    VFIO_REGION_TYPE_PCI_VENDOR_TYPE |
2265                                    PCI_VENDOR_ID_IBM,
2266                                    VFIO_REGION_SUBTYPE_IBM_NVLINK2_ATSD,
2267                                    &atsdreg);
2268     if (ret) {
2269         return ret;
2270     }
2271 
2272     hdr = vfio_get_region_info_cap(atsdreg,
2273                                    VFIO_REGION_INFO_CAP_NVLINK2_SSATGT);
2274     if (!hdr) {
2275         ret = -ENODEV;
2276         goto free_exit;
2277     }
2278     captgt = (void *) hdr;
2279 
2280     hdr = vfio_get_region_info_cap(atsdreg,
2281                                    VFIO_REGION_INFO_CAP_NVLINK2_LNKSPD);
2282     if (!hdr) {
2283         ret = -ENODEV;
2284         goto free_exit;
2285     }
2286     capspeed = (void *) hdr;
2287 
2288     /* Some NVLink bridges may not have assigned ATSD */
2289     if (atsdreg->size) {
2290         p = mmap(NULL, atsdreg->size, PROT_READ | PROT_WRITE | PROT_EXEC,
2291                  MAP_SHARED, vdev->vbasedev.fd, atsdreg->offset);
2292         if (p == MAP_FAILED) {
2293             ret = -errno;
2294             goto free_exit;
2295         }
2296 
2297         quirk = vfio_quirk_alloc(1);
2298         memory_region_init_ram_device_ptr(&quirk->mem[0], OBJECT(vdev),
2299                                           "nvlink2-atsd-mr", atsdreg->size, p);
2300         QLIST_INSERT_HEAD(&vdev->bars[0].quirks, quirk, next);
2301     }
2302 
2303     object_property_add(OBJECT(vdev), "nvlink2-tgt", "uint64",
2304                         vfio_pci_nvlink2_get_tgt, NULL, NULL,
2305                         (void *) (uintptr_t) captgt->tgt, NULL);
2306     trace_vfio_pci_nvlink2_setup_quirk_ssatgt(vdev->vbasedev.name, captgt->tgt,
2307                                               atsdreg->size);
2308 
2309     object_property_add(OBJECT(vdev), "nvlink2-link-speed", "uint32",
2310                         vfio_pci_nvlink2_get_link_speed, NULL, NULL,
2311                         (void *) (uintptr_t) capspeed->link_speed, NULL);
2312     trace_vfio_pci_nvlink2_setup_quirk_lnkspd(vdev->vbasedev.name,
2313                                               capspeed->link_speed);
2314 free_exit:
2315     g_free(atsdreg);
2316 
2317     return ret;
2318 }
2319