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