xref: /qemu/hw/display/qxl.c (revision b30d1886)
1 /*
2  * Copyright (C) 2010 Red Hat, Inc.
3  *
4  * written by Yaniv Kamay, Izik Eidus, Gerd Hoffmann
5  * maintained by Gerd Hoffmann <kraxel@redhat.com>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License as
9  * published by the Free Software Foundation; either version 2 or
10  * (at your option) version 3 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #include "qemu/osdep.h"
22 #include <zlib.h>
23 
24 #include "qemu-common.h"
25 #include "qemu/timer.h"
26 #include "qemu/queue.h"
27 #include "qemu/atomic.h"
28 #include "sysemu/sysemu.h"
29 #include "trace.h"
30 
31 #include "qxl.h"
32 
33 /*
34  * NOTE: SPICE_RING_PROD_ITEM accesses memory on the pci bar and as
35  * such can be changed by the guest, so to avoid a guest trigerrable
36  * abort we just qxl_set_guest_bug and set the return to NULL. Still
37  * it may happen as a result of emulator bug as well.
38  */
39 #undef SPICE_RING_PROD_ITEM
40 #define SPICE_RING_PROD_ITEM(qxl, r, ret) {                             \
41         uint32_t prod = (r)->prod & SPICE_RING_INDEX_MASK(r);           \
42         if (prod >= ARRAY_SIZE((r)->items)) {                           \
43             qxl_set_guest_bug(qxl, "SPICE_RING_PROD_ITEM indices mismatch " \
44                           "%u >= %zu", prod, ARRAY_SIZE((r)->items));   \
45             ret = NULL;                                                 \
46         } else {                                                        \
47             ret = &(r)->items[prod].el;                                 \
48         }                                                               \
49     }
50 
51 #undef SPICE_RING_CONS_ITEM
52 #define SPICE_RING_CONS_ITEM(qxl, r, ret) {                             \
53         uint32_t cons = (r)->cons & SPICE_RING_INDEX_MASK(r);           \
54         if (cons >= ARRAY_SIZE((r)->items)) {                           \
55             qxl_set_guest_bug(qxl, "SPICE_RING_CONS_ITEM indices mismatch " \
56                           "%u >= %zu", cons, ARRAY_SIZE((r)->items));   \
57             ret = NULL;                                                 \
58         } else {                                                        \
59             ret = &(r)->items[cons].el;                                 \
60         }                                                               \
61     }
62 
63 #undef ALIGN
64 #define ALIGN(a, b) (((a) + ((b) - 1)) & ~((b) - 1))
65 
66 #define PIXEL_SIZE 0.2936875 //1280x1024 is 14.8" x 11.9"
67 
68 #define QXL_MODE(_x, _y, _b, _o)                  \
69     {   .x_res = _x,                              \
70         .y_res = _y,                              \
71         .bits  = _b,                              \
72         .stride = (_x) * (_b) / 8,                \
73         .x_mili = PIXEL_SIZE * (_x),              \
74         .y_mili = PIXEL_SIZE * (_y),              \
75         .orientation = _o,                        \
76     }
77 
78 #define QXL_MODE_16_32(x_res, y_res, orientation) \
79     QXL_MODE(x_res, y_res, 16, orientation),      \
80     QXL_MODE(x_res, y_res, 32, orientation)
81 
82 #define QXL_MODE_EX(x_res, y_res)                 \
83     QXL_MODE_16_32(x_res, y_res, 0),              \
84     QXL_MODE_16_32(x_res, y_res, 1)
85 
86 static QXLMode qxl_modes[] = {
87     QXL_MODE_EX(640, 480),
88     QXL_MODE_EX(800, 480),
89     QXL_MODE_EX(800, 600),
90     QXL_MODE_EX(832, 624),
91     QXL_MODE_EX(960, 640),
92     QXL_MODE_EX(1024, 600),
93     QXL_MODE_EX(1024, 768),
94     QXL_MODE_EX(1152, 864),
95     QXL_MODE_EX(1152, 870),
96     QXL_MODE_EX(1280, 720),
97     QXL_MODE_EX(1280, 760),
98     QXL_MODE_EX(1280, 768),
99     QXL_MODE_EX(1280, 800),
100     QXL_MODE_EX(1280, 960),
101     QXL_MODE_EX(1280, 1024),
102     QXL_MODE_EX(1360, 768),
103     QXL_MODE_EX(1366, 768),
104     QXL_MODE_EX(1400, 1050),
105     QXL_MODE_EX(1440, 900),
106     QXL_MODE_EX(1600, 900),
107     QXL_MODE_EX(1600, 1200),
108     QXL_MODE_EX(1680, 1050),
109     QXL_MODE_EX(1920, 1080),
110     /* these modes need more than 8 MB video memory */
111     QXL_MODE_EX(1920, 1200),
112     QXL_MODE_EX(1920, 1440),
113     QXL_MODE_EX(2000, 2000),
114     QXL_MODE_EX(2048, 1536),
115     QXL_MODE_EX(2048, 2048),
116     QXL_MODE_EX(2560, 1440),
117     QXL_MODE_EX(2560, 1600),
118     /* these modes need more than 16 MB video memory */
119     QXL_MODE_EX(2560, 2048),
120     QXL_MODE_EX(2800, 2100),
121     QXL_MODE_EX(3200, 2400),
122     /* these modes need more than 32 MB video memory */
123     QXL_MODE_EX(3840, 2160), /* 4k mainstream */
124     QXL_MODE_EX(4096, 2160), /* 4k            */
125     /* these modes need more than 64 MB video memory */
126     QXL_MODE_EX(7680, 4320), /* 8k mainstream */
127     /* these modes need more than 128 MB video memory */
128     QXL_MODE_EX(8192, 4320), /* 8k            */
129 };
130 
131 static void qxl_send_events(PCIQXLDevice *d, uint32_t events);
132 static int qxl_destroy_primary(PCIQXLDevice *d, qxl_async_io async);
133 static void qxl_reset_memslots(PCIQXLDevice *d);
134 static void qxl_reset_surfaces(PCIQXLDevice *d);
135 static void qxl_ring_set_dirty(PCIQXLDevice *qxl);
136 
137 static void qxl_hw_update(void *opaque);
138 
139 void qxl_set_guest_bug(PCIQXLDevice *qxl, const char *msg, ...)
140 {
141     trace_qxl_set_guest_bug(qxl->id);
142     qxl_send_events(qxl, QXL_INTERRUPT_ERROR);
143     qxl->guest_bug = 1;
144     if (qxl->guestdebug) {
145         va_list ap;
146         va_start(ap, msg);
147         fprintf(stderr, "qxl-%d: guest bug: ", qxl->id);
148         vfprintf(stderr, msg, ap);
149         fprintf(stderr, "\n");
150         va_end(ap);
151     }
152 }
153 
154 static void qxl_clear_guest_bug(PCIQXLDevice *qxl)
155 {
156     qxl->guest_bug = 0;
157 }
158 
159 void qxl_spice_update_area(PCIQXLDevice *qxl, uint32_t surface_id,
160                            struct QXLRect *area, struct QXLRect *dirty_rects,
161                            uint32_t num_dirty_rects,
162                            uint32_t clear_dirty_region,
163                            qxl_async_io async, struct QXLCookie *cookie)
164 {
165     trace_qxl_spice_update_area(qxl->id, surface_id, area->left, area->right,
166                                 area->top, area->bottom);
167     trace_qxl_spice_update_area_rest(qxl->id, num_dirty_rects,
168                                      clear_dirty_region);
169     if (async == QXL_SYNC) {
170         spice_qxl_update_area(&qxl->ssd.qxl, surface_id, area,
171                         dirty_rects, num_dirty_rects, clear_dirty_region);
172     } else {
173         assert(cookie != NULL);
174         spice_qxl_update_area_async(&qxl->ssd.qxl, surface_id, area,
175                                     clear_dirty_region, (uintptr_t)cookie);
176     }
177 }
178 
179 static void qxl_spice_destroy_surface_wait_complete(PCIQXLDevice *qxl,
180                                                     uint32_t id)
181 {
182     trace_qxl_spice_destroy_surface_wait_complete(qxl->id, id);
183     qemu_mutex_lock(&qxl->track_lock);
184     qxl->guest_surfaces.cmds[id] = 0;
185     qxl->guest_surfaces.count--;
186     qemu_mutex_unlock(&qxl->track_lock);
187 }
188 
189 static void qxl_spice_destroy_surface_wait(PCIQXLDevice *qxl, uint32_t id,
190                                            qxl_async_io async)
191 {
192     QXLCookie *cookie;
193 
194     trace_qxl_spice_destroy_surface_wait(qxl->id, id, async);
195     if (async) {
196         cookie = qxl_cookie_new(QXL_COOKIE_TYPE_IO,
197                                 QXL_IO_DESTROY_SURFACE_ASYNC);
198         cookie->u.surface_id = id;
199         spice_qxl_destroy_surface_async(&qxl->ssd.qxl, id, (uintptr_t)cookie);
200     } else {
201         spice_qxl_destroy_surface_wait(&qxl->ssd.qxl, id);
202         qxl_spice_destroy_surface_wait_complete(qxl, id);
203     }
204 }
205 
206 static void qxl_spice_flush_surfaces_async(PCIQXLDevice *qxl)
207 {
208     trace_qxl_spice_flush_surfaces_async(qxl->id, qxl->guest_surfaces.count,
209                                          qxl->num_free_res);
210     spice_qxl_flush_surfaces_async(&qxl->ssd.qxl,
211         (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_IO,
212                                   QXL_IO_FLUSH_SURFACES_ASYNC));
213 }
214 
215 void qxl_spice_loadvm_commands(PCIQXLDevice *qxl, struct QXLCommandExt *ext,
216                                uint32_t count)
217 {
218     trace_qxl_spice_loadvm_commands(qxl->id, ext, count);
219     spice_qxl_loadvm_commands(&qxl->ssd.qxl, ext, count);
220 }
221 
222 void qxl_spice_oom(PCIQXLDevice *qxl)
223 {
224     trace_qxl_spice_oom(qxl->id);
225     spice_qxl_oom(&qxl->ssd.qxl);
226 }
227 
228 void qxl_spice_reset_memslots(PCIQXLDevice *qxl)
229 {
230     trace_qxl_spice_reset_memslots(qxl->id);
231     spice_qxl_reset_memslots(&qxl->ssd.qxl);
232 }
233 
234 static void qxl_spice_destroy_surfaces_complete(PCIQXLDevice *qxl)
235 {
236     trace_qxl_spice_destroy_surfaces_complete(qxl->id);
237     qemu_mutex_lock(&qxl->track_lock);
238     memset(qxl->guest_surfaces.cmds, 0,
239            sizeof(qxl->guest_surfaces.cmds[0]) * qxl->ssd.num_surfaces);
240     qxl->guest_surfaces.count = 0;
241     qemu_mutex_unlock(&qxl->track_lock);
242 }
243 
244 static void qxl_spice_destroy_surfaces(PCIQXLDevice *qxl, qxl_async_io async)
245 {
246     trace_qxl_spice_destroy_surfaces(qxl->id, async);
247     if (async) {
248         spice_qxl_destroy_surfaces_async(&qxl->ssd.qxl,
249                 (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_IO,
250                                           QXL_IO_DESTROY_ALL_SURFACES_ASYNC));
251     } else {
252         spice_qxl_destroy_surfaces(&qxl->ssd.qxl);
253         qxl_spice_destroy_surfaces_complete(qxl);
254     }
255 }
256 
257 static void qxl_spice_monitors_config_async(PCIQXLDevice *qxl, int replay)
258 {
259     trace_qxl_spice_monitors_config(qxl->id);
260     if (replay) {
261         /*
262          * don't use QXL_COOKIE_TYPE_IO:
263          *  - we are not running yet (post_load), we will assert
264          *    in send_events
265          *  - this is not a guest io, but a reply, so async_io isn't set.
266          */
267         spice_qxl_monitors_config_async(&qxl->ssd.qxl,
268                 qxl->guest_monitors_config,
269                 MEMSLOT_GROUP_GUEST,
270                 (uintptr_t)qxl_cookie_new(
271                     QXL_COOKIE_TYPE_POST_LOAD_MONITORS_CONFIG,
272                     0));
273     } else {
274 #if SPICE_SERVER_VERSION >= 0x000c06 /* release 0.12.6 */
275         if (qxl->max_outputs) {
276             spice_qxl_set_max_monitors(&qxl->ssd.qxl, qxl->max_outputs);
277         }
278 #endif
279         qxl->guest_monitors_config = qxl->ram->monitors_config;
280         spice_qxl_monitors_config_async(&qxl->ssd.qxl,
281                 qxl->ram->monitors_config,
282                 MEMSLOT_GROUP_GUEST,
283                 (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_IO,
284                                           QXL_IO_MONITORS_CONFIG_ASYNC));
285     }
286 }
287 
288 void qxl_spice_reset_image_cache(PCIQXLDevice *qxl)
289 {
290     trace_qxl_spice_reset_image_cache(qxl->id);
291     spice_qxl_reset_image_cache(&qxl->ssd.qxl);
292 }
293 
294 void qxl_spice_reset_cursor(PCIQXLDevice *qxl)
295 {
296     trace_qxl_spice_reset_cursor(qxl->id);
297     spice_qxl_reset_cursor(&qxl->ssd.qxl);
298     qemu_mutex_lock(&qxl->track_lock);
299     qxl->guest_cursor = 0;
300     qemu_mutex_unlock(&qxl->track_lock);
301     if (qxl->ssd.cursor) {
302         cursor_put(qxl->ssd.cursor);
303     }
304     qxl->ssd.cursor = cursor_builtin_hidden();
305 }
306 
307 static ram_addr_t qxl_rom_size(void)
308 {
309 #define QXL_REQUIRED_SZ (sizeof(QXLRom) + sizeof(QXLModes) + sizeof(qxl_modes))
310 #define QXL_ROM_SZ 8192
311 
312     QEMU_BUILD_BUG_ON(QXL_REQUIRED_SZ > QXL_ROM_SZ);
313     return QXL_ROM_SZ;
314 }
315 
316 static void init_qxl_rom(PCIQXLDevice *d)
317 {
318     QXLRom *rom = memory_region_get_ram_ptr(&d->rom_bar);
319     QXLModes *modes = (QXLModes *)(rom + 1);
320     uint32_t ram_header_size;
321     uint32_t surface0_area_size;
322     uint32_t num_pages;
323     uint32_t fb;
324     int i, n;
325 
326     memset(rom, 0, d->rom_size);
327 
328     rom->magic         = cpu_to_le32(QXL_ROM_MAGIC);
329     rom->id            = cpu_to_le32(d->id);
330     rom->log_level     = cpu_to_le32(d->guestdebug);
331     rom->modes_offset  = cpu_to_le32(sizeof(QXLRom));
332 
333     rom->slot_gen_bits = MEMSLOT_GENERATION_BITS;
334     rom->slot_id_bits  = MEMSLOT_SLOT_BITS;
335     rom->slots_start   = 1;
336     rom->slots_end     = NUM_MEMSLOTS - 1;
337     rom->n_surfaces    = cpu_to_le32(d->ssd.num_surfaces);
338 
339     for (i = 0, n = 0; i < ARRAY_SIZE(qxl_modes); i++) {
340         fb = qxl_modes[i].y_res * qxl_modes[i].stride;
341         if (fb > d->vgamem_size) {
342             continue;
343         }
344         modes->modes[n].id          = cpu_to_le32(i);
345         modes->modes[n].x_res       = cpu_to_le32(qxl_modes[i].x_res);
346         modes->modes[n].y_res       = cpu_to_le32(qxl_modes[i].y_res);
347         modes->modes[n].bits        = cpu_to_le32(qxl_modes[i].bits);
348         modes->modes[n].stride      = cpu_to_le32(qxl_modes[i].stride);
349         modes->modes[n].x_mili      = cpu_to_le32(qxl_modes[i].x_mili);
350         modes->modes[n].y_mili      = cpu_to_le32(qxl_modes[i].y_mili);
351         modes->modes[n].orientation = cpu_to_le32(qxl_modes[i].orientation);
352         n++;
353     }
354     modes->n_modes     = cpu_to_le32(n);
355 
356     ram_header_size    = ALIGN(sizeof(QXLRam), 4096);
357     surface0_area_size = ALIGN(d->vgamem_size, 4096);
358     num_pages          = d->vga.vram_size;
359     num_pages         -= ram_header_size;
360     num_pages         -= surface0_area_size;
361     num_pages          = num_pages / QXL_PAGE_SIZE;
362 
363     assert(ram_header_size + surface0_area_size <= d->vga.vram_size);
364 
365     rom->draw_area_offset   = cpu_to_le32(0);
366     rom->surface0_area_size = cpu_to_le32(surface0_area_size);
367     rom->pages_offset       = cpu_to_le32(surface0_area_size);
368     rom->num_pages          = cpu_to_le32(num_pages);
369     rom->ram_header_offset  = cpu_to_le32(d->vga.vram_size - ram_header_size);
370 
371     d->shadow_rom = *rom;
372     d->rom        = rom;
373     d->modes      = modes;
374 }
375 
376 static void init_qxl_ram(PCIQXLDevice *d)
377 {
378     uint8_t *buf;
379     uint64_t *item;
380 
381     buf = d->vga.vram_ptr;
382     d->ram = (QXLRam *)(buf + le32_to_cpu(d->shadow_rom.ram_header_offset));
383     d->ram->magic       = cpu_to_le32(QXL_RAM_MAGIC);
384     d->ram->int_pending = cpu_to_le32(0);
385     d->ram->int_mask    = cpu_to_le32(0);
386     d->ram->update_surface = 0;
387     d->ram->monitors_config = 0;
388     SPICE_RING_INIT(&d->ram->cmd_ring);
389     SPICE_RING_INIT(&d->ram->cursor_ring);
390     SPICE_RING_INIT(&d->ram->release_ring);
391     SPICE_RING_PROD_ITEM(d, &d->ram->release_ring, item);
392     assert(item);
393     *item = 0;
394     qxl_ring_set_dirty(d);
395 }
396 
397 /* can be called from spice server thread context */
398 static void qxl_set_dirty(MemoryRegion *mr, ram_addr_t addr, ram_addr_t end)
399 {
400     memory_region_set_dirty(mr, addr, end - addr);
401 }
402 
403 static void qxl_rom_set_dirty(PCIQXLDevice *qxl)
404 {
405     qxl_set_dirty(&qxl->rom_bar, 0, qxl->rom_size);
406 }
407 
408 /* called from spice server thread context only */
409 static void qxl_ram_set_dirty(PCIQXLDevice *qxl, void *ptr)
410 {
411     void *base = qxl->vga.vram_ptr;
412     intptr_t offset;
413 
414     offset = ptr - base;
415     assert(offset < qxl->vga.vram_size);
416     qxl_set_dirty(&qxl->vga.vram, offset, offset + 3);
417 }
418 
419 /* can be called from spice server thread context */
420 static void qxl_ring_set_dirty(PCIQXLDevice *qxl)
421 {
422     ram_addr_t addr = qxl->shadow_rom.ram_header_offset;
423     ram_addr_t end  = qxl->vga.vram_size;
424     qxl_set_dirty(&qxl->vga.vram, addr, end);
425 }
426 
427 /*
428  * keep track of some command state, for savevm/loadvm.
429  * called from spice server thread context only
430  */
431 static int qxl_track_command(PCIQXLDevice *qxl, struct QXLCommandExt *ext)
432 {
433     switch (le32_to_cpu(ext->cmd.type)) {
434     case QXL_CMD_SURFACE:
435     {
436         QXLSurfaceCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);
437 
438         if (!cmd) {
439             return 1;
440         }
441         uint32_t id = le32_to_cpu(cmd->surface_id);
442 
443         if (id >= qxl->ssd.num_surfaces) {
444             qxl_set_guest_bug(qxl, "QXL_CMD_SURFACE id %d >= %d", id,
445                               qxl->ssd.num_surfaces);
446             return 1;
447         }
448         if (cmd->type == QXL_SURFACE_CMD_CREATE &&
449             (cmd->u.surface_create.stride & 0x03) != 0) {
450             qxl_set_guest_bug(qxl, "QXL_CMD_SURFACE stride = %d %% 4 != 0\n",
451                               cmd->u.surface_create.stride);
452             return 1;
453         }
454         qemu_mutex_lock(&qxl->track_lock);
455         if (cmd->type == QXL_SURFACE_CMD_CREATE) {
456             qxl->guest_surfaces.cmds[id] = ext->cmd.data;
457             qxl->guest_surfaces.count++;
458             if (qxl->guest_surfaces.max < qxl->guest_surfaces.count)
459                 qxl->guest_surfaces.max = qxl->guest_surfaces.count;
460         }
461         if (cmd->type == QXL_SURFACE_CMD_DESTROY) {
462             qxl->guest_surfaces.cmds[id] = 0;
463             qxl->guest_surfaces.count--;
464         }
465         qemu_mutex_unlock(&qxl->track_lock);
466         break;
467     }
468     case QXL_CMD_CURSOR:
469     {
470         QXLCursorCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);
471 
472         if (!cmd) {
473             return 1;
474         }
475         if (cmd->type == QXL_CURSOR_SET) {
476             qemu_mutex_lock(&qxl->track_lock);
477             qxl->guest_cursor = ext->cmd.data;
478             qemu_mutex_unlock(&qxl->track_lock);
479         }
480         break;
481     }
482     }
483     return 0;
484 }
485 
486 /* spice display interface callbacks */
487 
488 static void interface_attach_worker(QXLInstance *sin, QXLWorker *qxl_worker)
489 {
490     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
491 
492     trace_qxl_interface_attach_worker(qxl->id);
493     qxl->ssd.worker = qxl_worker;
494 }
495 
496 static void interface_set_compression_level(QXLInstance *sin, int level)
497 {
498     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
499 
500     trace_qxl_interface_set_compression_level(qxl->id, level);
501     qxl->shadow_rom.compression_level = cpu_to_le32(level);
502     qxl->rom->compression_level = cpu_to_le32(level);
503     qxl_rom_set_dirty(qxl);
504 }
505 
506 #if SPICE_NEEDS_SET_MM_TIME
507 static void interface_set_mm_time(QXLInstance *sin, uint32_t mm_time)
508 {
509     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
510 
511     if (!qemu_spice_display_is_running(&qxl->ssd)) {
512         return;
513     }
514 
515     trace_qxl_interface_set_mm_time(qxl->id, mm_time);
516     qxl->shadow_rom.mm_clock = cpu_to_le32(mm_time);
517     qxl->rom->mm_clock = cpu_to_le32(mm_time);
518     qxl_rom_set_dirty(qxl);
519 }
520 #endif
521 
522 static void interface_get_init_info(QXLInstance *sin, QXLDevInitInfo *info)
523 {
524     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
525 
526     trace_qxl_interface_get_init_info(qxl->id);
527     info->memslot_gen_bits = MEMSLOT_GENERATION_BITS;
528     info->memslot_id_bits = MEMSLOT_SLOT_BITS;
529     info->num_memslots = NUM_MEMSLOTS;
530     info->num_memslots_groups = NUM_MEMSLOTS_GROUPS;
531     info->internal_groupslot_id = 0;
532     info->qxl_ram_size =
533         le32_to_cpu(qxl->shadow_rom.num_pages) << QXL_PAGE_BITS;
534     info->n_surfaces = qxl->ssd.num_surfaces;
535 }
536 
537 static const char *qxl_mode_to_string(int mode)
538 {
539     switch (mode) {
540     case QXL_MODE_COMPAT:
541         return "compat";
542     case QXL_MODE_NATIVE:
543         return "native";
544     case QXL_MODE_UNDEFINED:
545         return "undefined";
546     case QXL_MODE_VGA:
547         return "vga";
548     }
549     return "INVALID";
550 }
551 
552 static const char *io_port_to_string(uint32_t io_port)
553 {
554     if (io_port >= QXL_IO_RANGE_SIZE) {
555         return "out of range";
556     }
557     static const char *io_port_to_string[QXL_IO_RANGE_SIZE + 1] = {
558         [QXL_IO_NOTIFY_CMD]             = "QXL_IO_NOTIFY_CMD",
559         [QXL_IO_NOTIFY_CURSOR]          = "QXL_IO_NOTIFY_CURSOR",
560         [QXL_IO_UPDATE_AREA]            = "QXL_IO_UPDATE_AREA",
561         [QXL_IO_UPDATE_IRQ]             = "QXL_IO_UPDATE_IRQ",
562         [QXL_IO_NOTIFY_OOM]             = "QXL_IO_NOTIFY_OOM",
563         [QXL_IO_RESET]                  = "QXL_IO_RESET",
564         [QXL_IO_SET_MODE]               = "QXL_IO_SET_MODE",
565         [QXL_IO_LOG]                    = "QXL_IO_LOG",
566         [QXL_IO_MEMSLOT_ADD]            = "QXL_IO_MEMSLOT_ADD",
567         [QXL_IO_MEMSLOT_DEL]            = "QXL_IO_MEMSLOT_DEL",
568         [QXL_IO_DETACH_PRIMARY]         = "QXL_IO_DETACH_PRIMARY",
569         [QXL_IO_ATTACH_PRIMARY]         = "QXL_IO_ATTACH_PRIMARY",
570         [QXL_IO_CREATE_PRIMARY]         = "QXL_IO_CREATE_PRIMARY",
571         [QXL_IO_DESTROY_PRIMARY]        = "QXL_IO_DESTROY_PRIMARY",
572         [QXL_IO_DESTROY_SURFACE_WAIT]   = "QXL_IO_DESTROY_SURFACE_WAIT",
573         [QXL_IO_DESTROY_ALL_SURFACES]   = "QXL_IO_DESTROY_ALL_SURFACES",
574         [QXL_IO_UPDATE_AREA_ASYNC]      = "QXL_IO_UPDATE_AREA_ASYNC",
575         [QXL_IO_MEMSLOT_ADD_ASYNC]      = "QXL_IO_MEMSLOT_ADD_ASYNC",
576         [QXL_IO_CREATE_PRIMARY_ASYNC]   = "QXL_IO_CREATE_PRIMARY_ASYNC",
577         [QXL_IO_DESTROY_PRIMARY_ASYNC]  = "QXL_IO_DESTROY_PRIMARY_ASYNC",
578         [QXL_IO_DESTROY_SURFACE_ASYNC]  = "QXL_IO_DESTROY_SURFACE_ASYNC",
579         [QXL_IO_DESTROY_ALL_SURFACES_ASYNC]
580                                         = "QXL_IO_DESTROY_ALL_SURFACES_ASYNC",
581         [QXL_IO_FLUSH_SURFACES_ASYNC]   = "QXL_IO_FLUSH_SURFACES_ASYNC",
582         [QXL_IO_FLUSH_RELEASE]          = "QXL_IO_FLUSH_RELEASE",
583         [QXL_IO_MONITORS_CONFIG_ASYNC]  = "QXL_IO_MONITORS_CONFIG_ASYNC",
584     };
585     return io_port_to_string[io_port];
586 }
587 
588 /* called from spice server thread context only */
589 static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext)
590 {
591     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
592     SimpleSpiceUpdate *update;
593     QXLCommandRing *ring;
594     QXLCommand *cmd;
595     int notify, ret;
596 
597     trace_qxl_ring_command_check(qxl->id, qxl_mode_to_string(qxl->mode));
598 
599     switch (qxl->mode) {
600     case QXL_MODE_VGA:
601         ret = false;
602         qemu_mutex_lock(&qxl->ssd.lock);
603         update = QTAILQ_FIRST(&qxl->ssd.updates);
604         if (update != NULL) {
605             QTAILQ_REMOVE(&qxl->ssd.updates, update, next);
606             *ext = update->ext;
607             ret = true;
608         }
609         qemu_mutex_unlock(&qxl->ssd.lock);
610         if (ret) {
611             trace_qxl_ring_command_get(qxl->id, qxl_mode_to_string(qxl->mode));
612             qxl_log_command(qxl, "vga", ext);
613         }
614         return ret;
615     case QXL_MODE_COMPAT:
616     case QXL_MODE_NATIVE:
617     case QXL_MODE_UNDEFINED:
618         ring = &qxl->ram->cmd_ring;
619         if (qxl->guest_bug || SPICE_RING_IS_EMPTY(ring)) {
620             return false;
621         }
622         SPICE_RING_CONS_ITEM(qxl, ring, cmd);
623         if (!cmd) {
624             return false;
625         }
626         ext->cmd      = *cmd;
627         ext->group_id = MEMSLOT_GROUP_GUEST;
628         ext->flags    = qxl->cmdflags;
629         SPICE_RING_POP(ring, notify);
630         qxl_ring_set_dirty(qxl);
631         if (notify) {
632             qxl_send_events(qxl, QXL_INTERRUPT_DISPLAY);
633         }
634         qxl->guest_primary.commands++;
635         qxl_track_command(qxl, ext);
636         qxl_log_command(qxl, "cmd", ext);
637         trace_qxl_ring_command_get(qxl->id, qxl_mode_to_string(qxl->mode));
638         return true;
639     default:
640         return false;
641     }
642 }
643 
644 /* called from spice server thread context only */
645 static int interface_req_cmd_notification(QXLInstance *sin)
646 {
647     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
648     int wait = 1;
649 
650     trace_qxl_ring_command_req_notification(qxl->id);
651     switch (qxl->mode) {
652     case QXL_MODE_COMPAT:
653     case QXL_MODE_NATIVE:
654     case QXL_MODE_UNDEFINED:
655         SPICE_RING_CONS_WAIT(&qxl->ram->cmd_ring, wait);
656         qxl_ring_set_dirty(qxl);
657         break;
658     default:
659         /* nothing */
660         break;
661     }
662     return wait;
663 }
664 
665 /* called from spice server thread context only */
666 static inline void qxl_push_free_res(PCIQXLDevice *d, int flush)
667 {
668     QXLReleaseRing *ring = &d->ram->release_ring;
669     uint64_t *item;
670     int notify;
671 
672 #define QXL_FREE_BUNCH_SIZE 32
673 
674     if (ring->prod - ring->cons + 1 == ring->num_items) {
675         /* ring full -- can't push */
676         return;
677     }
678     if (!flush && d->oom_running) {
679         /* collect everything from oom handler before pushing */
680         return;
681     }
682     if (!flush && d->num_free_res < QXL_FREE_BUNCH_SIZE) {
683         /* collect a bit more before pushing */
684         return;
685     }
686 
687     SPICE_RING_PUSH(ring, notify);
688     trace_qxl_ring_res_push(d->id, qxl_mode_to_string(d->mode),
689            d->guest_surfaces.count, d->num_free_res,
690            d->last_release, notify ? "yes" : "no");
691     trace_qxl_ring_res_push_rest(d->id, ring->prod - ring->cons,
692            ring->num_items, ring->prod, ring->cons);
693     if (notify) {
694         qxl_send_events(d, QXL_INTERRUPT_DISPLAY);
695     }
696     SPICE_RING_PROD_ITEM(d, ring, item);
697     if (!item) {
698         return;
699     }
700     *item = 0;
701     d->num_free_res = 0;
702     d->last_release = NULL;
703     qxl_ring_set_dirty(d);
704 }
705 
706 /* called from spice server thread context only */
707 static void interface_release_resource(QXLInstance *sin,
708                                        QXLReleaseInfoExt ext)
709 {
710     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
711     QXLReleaseRing *ring;
712     uint64_t *item, id;
713 
714     if (ext.group_id == MEMSLOT_GROUP_HOST) {
715         /* host group -> vga mode update request */
716         QXLCommandExt *cmdext = (void *)(intptr_t)(ext.info->id);
717         SimpleSpiceUpdate *update;
718         g_assert(cmdext->cmd.type == QXL_CMD_DRAW);
719         update = container_of(cmdext, SimpleSpiceUpdate, ext);
720         qemu_spice_destroy_update(&qxl->ssd, update);
721         return;
722     }
723 
724     /*
725      * ext->info points into guest-visible memory
726      * pci bar 0, $command.release_info
727      */
728     ring = &qxl->ram->release_ring;
729     SPICE_RING_PROD_ITEM(qxl, ring, item);
730     if (!item) {
731         return;
732     }
733     if (*item == 0) {
734         /* stick head into the ring */
735         id = ext.info->id;
736         ext.info->next = 0;
737         qxl_ram_set_dirty(qxl, &ext.info->next);
738         *item = id;
739         qxl_ring_set_dirty(qxl);
740     } else {
741         /* append item to the list */
742         qxl->last_release->next = ext.info->id;
743         qxl_ram_set_dirty(qxl, &qxl->last_release->next);
744         ext.info->next = 0;
745         qxl_ram_set_dirty(qxl, &ext.info->next);
746     }
747     qxl->last_release = ext.info;
748     qxl->num_free_res++;
749     trace_qxl_ring_res_put(qxl->id, qxl->num_free_res);
750     qxl_push_free_res(qxl, 0);
751 }
752 
753 /* called from spice server thread context only */
754 static int interface_get_cursor_command(QXLInstance *sin, struct QXLCommandExt *ext)
755 {
756     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
757     QXLCursorRing *ring;
758     QXLCommand *cmd;
759     int notify;
760 
761     trace_qxl_ring_cursor_check(qxl->id, qxl_mode_to_string(qxl->mode));
762 
763     switch (qxl->mode) {
764     case QXL_MODE_COMPAT:
765     case QXL_MODE_NATIVE:
766     case QXL_MODE_UNDEFINED:
767         ring = &qxl->ram->cursor_ring;
768         if (SPICE_RING_IS_EMPTY(ring)) {
769             return false;
770         }
771         SPICE_RING_CONS_ITEM(qxl, ring, cmd);
772         if (!cmd) {
773             return false;
774         }
775         ext->cmd      = *cmd;
776         ext->group_id = MEMSLOT_GROUP_GUEST;
777         ext->flags    = qxl->cmdflags;
778         SPICE_RING_POP(ring, notify);
779         qxl_ring_set_dirty(qxl);
780         if (notify) {
781             qxl_send_events(qxl, QXL_INTERRUPT_CURSOR);
782         }
783         qxl->guest_primary.commands++;
784         qxl_track_command(qxl, ext);
785         qxl_log_command(qxl, "csr", ext);
786         if (qxl->id == 0) {
787             qxl_render_cursor(qxl, ext);
788         }
789         trace_qxl_ring_cursor_get(qxl->id, qxl_mode_to_string(qxl->mode));
790         return true;
791     default:
792         return false;
793     }
794 }
795 
796 /* called from spice server thread context only */
797 static int interface_req_cursor_notification(QXLInstance *sin)
798 {
799     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
800     int wait = 1;
801 
802     trace_qxl_ring_cursor_req_notification(qxl->id);
803     switch (qxl->mode) {
804     case QXL_MODE_COMPAT:
805     case QXL_MODE_NATIVE:
806     case QXL_MODE_UNDEFINED:
807         SPICE_RING_CONS_WAIT(&qxl->ram->cursor_ring, wait);
808         qxl_ring_set_dirty(qxl);
809         break;
810     default:
811         /* nothing */
812         break;
813     }
814     return wait;
815 }
816 
817 /* called from spice server thread context */
818 static void interface_notify_update(QXLInstance *sin, uint32_t update_id)
819 {
820     /*
821      * Called by spice-server as a result of a QXL_CMD_UPDATE which is not in
822      * use by xf86-video-qxl and is defined out in the qxl windows driver.
823      * Probably was at some earlier version that is prior to git start (2009),
824      * and is still guest trigerrable.
825      */
826     fprintf(stderr, "%s: deprecated\n", __func__);
827 }
828 
829 /* called from spice server thread context only */
830 static int interface_flush_resources(QXLInstance *sin)
831 {
832     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
833     int ret;
834 
835     ret = qxl->num_free_res;
836     if (ret) {
837         qxl_push_free_res(qxl, 1);
838     }
839     return ret;
840 }
841 
842 static void qxl_create_guest_primary_complete(PCIQXLDevice *d);
843 
844 /* called from spice server thread context only */
845 static void interface_async_complete_io(PCIQXLDevice *qxl, QXLCookie *cookie)
846 {
847     uint32_t current_async;
848 
849     qemu_mutex_lock(&qxl->async_lock);
850     current_async = qxl->current_async;
851     qxl->current_async = QXL_UNDEFINED_IO;
852     qemu_mutex_unlock(&qxl->async_lock);
853 
854     trace_qxl_interface_async_complete_io(qxl->id, current_async, cookie);
855     if (!cookie) {
856         fprintf(stderr, "qxl: %s: error, cookie is NULL\n", __func__);
857         return;
858     }
859     if (cookie && current_async != cookie->io) {
860         fprintf(stderr,
861                 "qxl: %s: error: current_async = %d != %"
862                 PRId64 " = cookie->io\n", __func__, current_async, cookie->io);
863     }
864     switch (current_async) {
865     case QXL_IO_MEMSLOT_ADD_ASYNC:
866     case QXL_IO_DESTROY_PRIMARY_ASYNC:
867     case QXL_IO_UPDATE_AREA_ASYNC:
868     case QXL_IO_FLUSH_SURFACES_ASYNC:
869     case QXL_IO_MONITORS_CONFIG_ASYNC:
870         break;
871     case QXL_IO_CREATE_PRIMARY_ASYNC:
872         qxl_create_guest_primary_complete(qxl);
873         break;
874     case QXL_IO_DESTROY_ALL_SURFACES_ASYNC:
875         qxl_spice_destroy_surfaces_complete(qxl);
876         break;
877     case QXL_IO_DESTROY_SURFACE_ASYNC:
878         qxl_spice_destroy_surface_wait_complete(qxl, cookie->u.surface_id);
879         break;
880     default:
881         fprintf(stderr, "qxl: %s: unexpected current_async %d\n", __func__,
882                 current_async);
883     }
884     qxl_send_events(qxl, QXL_INTERRUPT_IO_CMD);
885 }
886 
887 /* called from spice server thread context only */
888 static void interface_update_area_complete(QXLInstance *sin,
889         uint32_t surface_id,
890         QXLRect *dirty, uint32_t num_updated_rects)
891 {
892     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
893     int i;
894     int qxl_i;
895 
896     qemu_mutex_lock(&qxl->ssd.lock);
897     if (surface_id != 0 || !num_updated_rects ||
898         !qxl->render_update_cookie_num) {
899         qemu_mutex_unlock(&qxl->ssd.lock);
900         return;
901     }
902     trace_qxl_interface_update_area_complete(qxl->id, surface_id, dirty->left,
903             dirty->right, dirty->top, dirty->bottom);
904     trace_qxl_interface_update_area_complete_rest(qxl->id, num_updated_rects);
905     if (qxl->num_dirty_rects + num_updated_rects > QXL_NUM_DIRTY_RECTS) {
906         /*
907          * overflow - treat this as a full update. Not expected to be common.
908          */
909         trace_qxl_interface_update_area_complete_overflow(qxl->id,
910                                                           QXL_NUM_DIRTY_RECTS);
911         qxl->guest_primary.resized = 1;
912     }
913     if (qxl->guest_primary.resized) {
914         /*
915          * Don't bother copying or scheduling the bh since we will flip
916          * the whole area anyway on completion of the update_area async call
917          */
918         qemu_mutex_unlock(&qxl->ssd.lock);
919         return;
920     }
921     qxl_i = qxl->num_dirty_rects;
922     for (i = 0; i < num_updated_rects; i++) {
923         qxl->dirty[qxl_i++] = dirty[i];
924     }
925     qxl->num_dirty_rects += num_updated_rects;
926     trace_qxl_interface_update_area_complete_schedule_bh(qxl->id,
927                                                          qxl->num_dirty_rects);
928     qemu_bh_schedule(qxl->update_area_bh);
929     qemu_mutex_unlock(&qxl->ssd.lock);
930 }
931 
932 /* called from spice server thread context only */
933 static void interface_async_complete(QXLInstance *sin, uint64_t cookie_token)
934 {
935     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
936     QXLCookie *cookie = (QXLCookie *)(uintptr_t)cookie_token;
937 
938     switch (cookie->type) {
939     case QXL_COOKIE_TYPE_IO:
940         interface_async_complete_io(qxl, cookie);
941         g_free(cookie);
942         break;
943     case QXL_COOKIE_TYPE_RENDER_UPDATE_AREA:
944         qxl_render_update_area_done(qxl, cookie);
945         break;
946     case QXL_COOKIE_TYPE_POST_LOAD_MONITORS_CONFIG:
947         break;
948     default:
949         fprintf(stderr, "qxl: %s: unexpected cookie type %d\n",
950                 __func__, cookie->type);
951         g_free(cookie);
952     }
953 }
954 
955 /* called from spice server thread context only */
956 static void interface_set_client_capabilities(QXLInstance *sin,
957                                               uint8_t client_present,
958                                               uint8_t caps[58])
959 {
960     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
961 
962     if (qxl->revision < 4) {
963         trace_qxl_set_client_capabilities_unsupported_by_revision(qxl->id,
964                                                               qxl->revision);
965         return;
966     }
967 
968     if (runstate_check(RUN_STATE_INMIGRATE) ||
969         runstate_check(RUN_STATE_POSTMIGRATE)) {
970         return;
971     }
972 
973     qxl->shadow_rom.client_present = client_present;
974     memcpy(qxl->shadow_rom.client_capabilities, caps,
975            sizeof(qxl->shadow_rom.client_capabilities));
976     qxl->rom->client_present = client_present;
977     memcpy(qxl->rom->client_capabilities, caps,
978            sizeof(qxl->rom->client_capabilities));
979     qxl_rom_set_dirty(qxl);
980 
981     qxl_send_events(qxl, QXL_INTERRUPT_CLIENT);
982 }
983 
984 static uint32_t qxl_crc32(const uint8_t *p, unsigned len)
985 {
986     /*
987      * zlib xors the seed with 0xffffffff, and xors the result
988      * again with 0xffffffff; Both are not done with linux's crc32,
989      * which we want to be compatible with, so undo that.
990      */
991     return crc32(0xffffffff, p, len) ^ 0xffffffff;
992 }
993 
994 static bool qxl_rom_monitors_config_changed(QXLRom *rom,
995         VDAgentMonitorsConfig *monitors_config,
996         unsigned int max_outputs)
997 {
998     int i;
999     unsigned int monitors_count;
1000 
1001     monitors_count = MIN(monitors_config->num_of_monitors, max_outputs);
1002 
1003     if (rom->client_monitors_config.count != monitors_count) {
1004         return true;
1005     }
1006 
1007     for (i = 0 ; i < rom->client_monitors_config.count ; ++i) {
1008         VDAgentMonConfig *monitor = &monitors_config->monitors[i];
1009         QXLURect *rect = &rom->client_monitors_config.heads[i];
1010         /* monitor->depth ignored */
1011         if ((rect->left != monitor->x) ||
1012             (rect->top != monitor->y)  ||
1013             (rect->right != monitor->x + monitor->width) ||
1014             (rect->bottom != monitor->y + monitor->height)) {
1015             return true;
1016         }
1017     }
1018 
1019     return false;
1020 }
1021 
1022 /* called from main context only */
1023 static int interface_client_monitors_config(QXLInstance *sin,
1024                                         VDAgentMonitorsConfig *monitors_config)
1025 {
1026     PCIQXLDevice *qxl = container_of(sin, PCIQXLDevice, ssd.qxl);
1027     QXLRom *rom = memory_region_get_ram_ptr(&qxl->rom_bar);
1028     int i;
1029     unsigned max_outputs = ARRAY_SIZE(rom->client_monitors_config.heads);
1030     bool config_changed = false;
1031 
1032     if (qxl->revision < 4) {
1033         trace_qxl_client_monitors_config_unsupported_by_device(qxl->id,
1034                                                                qxl->revision);
1035         return 0;
1036     }
1037     /*
1038      * Older windows drivers set int_mask to 0 when their ISR is called,
1039      * then later set it to ~0. So it doesn't relate to the actual interrupts
1040      * handled. However, they are old, so clearly they don't support this
1041      * interrupt
1042      */
1043     if (qxl->ram->int_mask == 0 || qxl->ram->int_mask == ~0 ||
1044         !(qxl->ram->int_mask & QXL_INTERRUPT_CLIENT_MONITORS_CONFIG)) {
1045         trace_qxl_client_monitors_config_unsupported_by_guest(qxl->id,
1046                                                             qxl->ram->int_mask,
1047                                                             monitors_config);
1048         return 0;
1049     }
1050     if (!monitors_config) {
1051         return 1;
1052     }
1053 
1054 #if SPICE_SERVER_VERSION >= 0x000c06 /* release 0.12.6 */
1055     /* limit number of outputs based on setting limit */
1056     if (qxl->max_outputs && qxl->max_outputs <= max_outputs) {
1057         max_outputs = qxl->max_outputs;
1058     }
1059 #endif
1060 
1061     config_changed = qxl_rom_monitors_config_changed(rom,
1062                                                      monitors_config,
1063                                                      max_outputs);
1064 
1065     memset(&rom->client_monitors_config, 0,
1066            sizeof(rom->client_monitors_config));
1067     rom->client_monitors_config.count = monitors_config->num_of_monitors;
1068     /* monitors_config->flags ignored */
1069     if (rom->client_monitors_config.count >= max_outputs) {
1070         trace_qxl_client_monitors_config_capped(qxl->id,
1071                                 monitors_config->num_of_monitors,
1072                                 max_outputs);
1073         rom->client_monitors_config.count = max_outputs;
1074     }
1075     for (i = 0 ; i < rom->client_monitors_config.count ; ++i) {
1076         VDAgentMonConfig *monitor = &monitors_config->monitors[i];
1077         QXLURect *rect = &rom->client_monitors_config.heads[i];
1078         /* monitor->depth ignored */
1079         rect->left = monitor->x;
1080         rect->top = monitor->y;
1081         rect->right = monitor->x + monitor->width;
1082         rect->bottom = monitor->y + monitor->height;
1083     }
1084     rom->client_monitors_config_crc = qxl_crc32(
1085             (const uint8_t *)&rom->client_monitors_config,
1086             sizeof(rom->client_monitors_config));
1087     trace_qxl_client_monitors_config_crc(qxl->id,
1088             sizeof(rom->client_monitors_config),
1089             rom->client_monitors_config_crc);
1090 
1091     trace_qxl_interrupt_client_monitors_config(qxl->id,
1092                         rom->client_monitors_config.count,
1093                         rom->client_monitors_config.heads);
1094     if (config_changed) {
1095         qxl_send_events(qxl, QXL_INTERRUPT_CLIENT_MONITORS_CONFIG);
1096     }
1097     return 1;
1098 }
1099 
1100 static const QXLInterface qxl_interface = {
1101     .base.type               = SPICE_INTERFACE_QXL,
1102     .base.description        = "qxl gpu",
1103     .base.major_version      = SPICE_INTERFACE_QXL_MAJOR,
1104     .base.minor_version      = SPICE_INTERFACE_QXL_MINOR,
1105 
1106     .attache_worker          = interface_attach_worker,
1107     .set_compression_level   = interface_set_compression_level,
1108 #if SPICE_NEEDS_SET_MM_TIME
1109     .set_mm_time             = interface_set_mm_time,
1110 #endif
1111     .get_init_info           = interface_get_init_info,
1112 
1113     /* the callbacks below are called from spice server thread context */
1114     .get_command             = interface_get_command,
1115     .req_cmd_notification    = interface_req_cmd_notification,
1116     .release_resource        = interface_release_resource,
1117     .get_cursor_command      = interface_get_cursor_command,
1118     .req_cursor_notification = interface_req_cursor_notification,
1119     .notify_update           = interface_notify_update,
1120     .flush_resources         = interface_flush_resources,
1121     .async_complete          = interface_async_complete,
1122     .update_area_complete    = interface_update_area_complete,
1123     .set_client_capabilities = interface_set_client_capabilities,
1124     .client_monitors_config = interface_client_monitors_config,
1125 };
1126 
1127 static const GraphicHwOps qxl_ops = {
1128     .gfx_update  = qxl_hw_update,
1129 };
1130 
1131 static void qxl_enter_vga_mode(PCIQXLDevice *d)
1132 {
1133     if (d->mode == QXL_MODE_VGA) {
1134         return;
1135     }
1136     trace_qxl_enter_vga_mode(d->id);
1137 #if SPICE_SERVER_VERSION >= 0x000c03 /* release 0.12.3 */
1138     spice_qxl_driver_unload(&d->ssd.qxl);
1139 #endif
1140     graphic_console_set_hwops(d->ssd.dcl.con, d->vga.hw_ops, &d->vga);
1141     update_displaychangelistener(&d->ssd.dcl, GUI_REFRESH_INTERVAL_DEFAULT);
1142     qemu_spice_create_host_primary(&d->ssd);
1143     d->mode = QXL_MODE_VGA;
1144     vga_dirty_log_start(&d->vga);
1145     graphic_hw_update(d->vga.con);
1146 }
1147 
1148 static void qxl_exit_vga_mode(PCIQXLDevice *d)
1149 {
1150     if (d->mode != QXL_MODE_VGA) {
1151         return;
1152     }
1153     trace_qxl_exit_vga_mode(d->id);
1154     graphic_console_set_hwops(d->ssd.dcl.con, &qxl_ops, d);
1155     update_displaychangelistener(&d->ssd.dcl, GUI_REFRESH_INTERVAL_IDLE);
1156     vga_dirty_log_stop(&d->vga);
1157     qxl_destroy_primary(d, QXL_SYNC);
1158 }
1159 
1160 static void qxl_update_irq(PCIQXLDevice *d)
1161 {
1162     uint32_t pending = le32_to_cpu(d->ram->int_pending);
1163     uint32_t mask    = le32_to_cpu(d->ram->int_mask);
1164     int level = !!(pending & mask);
1165     pci_set_irq(&d->pci, level);
1166     qxl_ring_set_dirty(d);
1167 }
1168 
1169 static void qxl_check_state(PCIQXLDevice *d)
1170 {
1171     QXLRam *ram = d->ram;
1172     int spice_display_running = qemu_spice_display_is_running(&d->ssd);
1173 
1174     assert(!spice_display_running || SPICE_RING_IS_EMPTY(&ram->cmd_ring));
1175     assert(!spice_display_running || SPICE_RING_IS_EMPTY(&ram->cursor_ring));
1176 }
1177 
1178 static void qxl_reset_state(PCIQXLDevice *d)
1179 {
1180     QXLRom *rom = d->rom;
1181 
1182     qxl_check_state(d);
1183     d->shadow_rom.update_id = cpu_to_le32(0);
1184     *rom = d->shadow_rom;
1185     qxl_rom_set_dirty(d);
1186     init_qxl_ram(d);
1187     d->num_free_res = 0;
1188     d->last_release = NULL;
1189     memset(&d->ssd.dirty, 0, sizeof(d->ssd.dirty));
1190     qxl_update_irq(d);
1191 }
1192 
1193 static void qxl_soft_reset(PCIQXLDevice *d)
1194 {
1195     trace_qxl_soft_reset(d->id);
1196     qxl_check_state(d);
1197     qxl_clear_guest_bug(d);
1198     qemu_mutex_lock(&d->async_lock);
1199     d->current_async = QXL_UNDEFINED_IO;
1200     qemu_mutex_unlock(&d->async_lock);
1201 
1202     if (d->id == 0) {
1203         qxl_enter_vga_mode(d);
1204     } else {
1205         d->mode = QXL_MODE_UNDEFINED;
1206     }
1207 }
1208 
1209 static void qxl_hard_reset(PCIQXLDevice *d, int loadvm)
1210 {
1211     bool startstop = qemu_spice_display_is_running(&d->ssd);
1212 
1213     trace_qxl_hard_reset(d->id, loadvm);
1214 
1215     if (startstop) {
1216         qemu_spice_display_stop();
1217     }
1218 
1219     qxl_spice_reset_cursor(d);
1220     qxl_spice_reset_image_cache(d);
1221     qxl_reset_surfaces(d);
1222     qxl_reset_memslots(d);
1223 
1224     /* pre loadvm reset must not touch QXLRam.  This lives in
1225      * device memory, is migrated together with RAM and thus
1226      * already loaded at this point */
1227     if (!loadvm) {
1228         qxl_reset_state(d);
1229     }
1230     qemu_spice_create_host_memslot(&d->ssd);
1231     qxl_soft_reset(d);
1232 
1233     if (startstop) {
1234         qemu_spice_display_start();
1235     }
1236 }
1237 
1238 static void qxl_reset_handler(DeviceState *dev)
1239 {
1240     PCIQXLDevice *d = PCI_QXL(PCI_DEVICE(dev));
1241 
1242     qxl_hard_reset(d, 0);
1243 }
1244 
1245 static void qxl_vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)
1246 {
1247     VGACommonState *vga = opaque;
1248     PCIQXLDevice *qxl = container_of(vga, PCIQXLDevice, vga);
1249 
1250     trace_qxl_io_write_vga(qxl->id, qxl_mode_to_string(qxl->mode), addr, val);
1251     if (qxl->mode != QXL_MODE_VGA) {
1252         qxl_destroy_primary(qxl, QXL_SYNC);
1253         qxl_soft_reset(qxl);
1254     }
1255     vga_ioport_write(opaque, addr, val);
1256 }
1257 
1258 static const MemoryRegionPortio qxl_vga_portio_list[] = {
1259     { 0x04,  2, 1, .read  = vga_ioport_read,
1260                    .write = qxl_vga_ioport_write }, /* 3b4 */
1261     { 0x0a,  1, 1, .read  = vga_ioport_read,
1262                    .write = qxl_vga_ioport_write }, /* 3ba */
1263     { 0x10, 16, 1, .read  = vga_ioport_read,
1264                    .write = qxl_vga_ioport_write }, /* 3c0 */
1265     { 0x24,  2, 1, .read  = vga_ioport_read,
1266                    .write = qxl_vga_ioport_write }, /* 3d4 */
1267     { 0x2a,  1, 1, .read  = vga_ioport_read,
1268                    .write = qxl_vga_ioport_write }, /* 3da */
1269     PORTIO_END_OF_LIST(),
1270 };
1271 
1272 static int qxl_add_memslot(PCIQXLDevice *d, uint32_t slot_id, uint64_t delta,
1273                            qxl_async_io async)
1274 {
1275     static const int regions[] = {
1276         QXL_RAM_RANGE_INDEX,
1277         QXL_VRAM_RANGE_INDEX,
1278         QXL_VRAM64_RANGE_INDEX,
1279     };
1280     uint64_t guest_start;
1281     uint64_t guest_end;
1282     int pci_region;
1283     pcibus_t pci_start;
1284     pcibus_t pci_end;
1285     MemoryRegion *mr;
1286     intptr_t virt_start;
1287     QXLDevMemSlot memslot;
1288     int i;
1289 
1290     guest_start = le64_to_cpu(d->guest_slots[slot_id].slot.mem_start);
1291     guest_end   = le64_to_cpu(d->guest_slots[slot_id].slot.mem_end);
1292 
1293     trace_qxl_memslot_add_guest(d->id, slot_id, guest_start, guest_end);
1294 
1295     if (slot_id >= NUM_MEMSLOTS) {
1296         qxl_set_guest_bug(d, "%s: slot_id >= NUM_MEMSLOTS %d >= %d", __func__,
1297                       slot_id, NUM_MEMSLOTS);
1298         return 1;
1299     }
1300     if (guest_start > guest_end) {
1301         qxl_set_guest_bug(d, "%s: guest_start > guest_end 0x%" PRIx64
1302                          " > 0x%" PRIx64, __func__, guest_start, guest_end);
1303         return 1;
1304     }
1305 
1306     for (i = 0; i < ARRAY_SIZE(regions); i++) {
1307         pci_region = regions[i];
1308         pci_start = d->pci.io_regions[pci_region].addr;
1309         pci_end = pci_start + d->pci.io_regions[pci_region].size;
1310         /* mapped? */
1311         if (pci_start == -1) {
1312             continue;
1313         }
1314         /* start address in range ? */
1315         if (guest_start < pci_start || guest_start > pci_end) {
1316             continue;
1317         }
1318         /* end address in range ? */
1319         if (guest_end > pci_end) {
1320             continue;
1321         }
1322         /* passed */
1323         break;
1324     }
1325     if (i == ARRAY_SIZE(regions)) {
1326         qxl_set_guest_bug(d, "%s: finished loop without match", __func__);
1327         return 1;
1328     }
1329 
1330     switch (pci_region) {
1331     case QXL_RAM_RANGE_INDEX:
1332         mr = &d->vga.vram;
1333         break;
1334     case QXL_VRAM_RANGE_INDEX:
1335     case 4 /* vram 64bit */:
1336         mr = &d->vram_bar;
1337         break;
1338     default:
1339         /* should not happen */
1340         qxl_set_guest_bug(d, "%s: pci_region = %d", __func__, pci_region);
1341         return 1;
1342     }
1343 
1344     virt_start = (intptr_t)memory_region_get_ram_ptr(mr);
1345     memslot.slot_id = slot_id;
1346     memslot.slot_group_id = MEMSLOT_GROUP_GUEST; /* guest group */
1347     memslot.virt_start = virt_start + (guest_start - pci_start);
1348     memslot.virt_end   = virt_start + (guest_end   - pci_start);
1349     memslot.addr_delta = memslot.virt_start - delta;
1350     memslot.generation = d->rom->slot_generation = 0;
1351     qxl_rom_set_dirty(d);
1352 
1353     qemu_spice_add_memslot(&d->ssd, &memslot, async);
1354     d->guest_slots[slot_id].mr = mr;
1355     d->guest_slots[slot_id].offset = memslot.virt_start - virt_start;
1356     d->guest_slots[slot_id].size = memslot.virt_end - memslot.virt_start;
1357     d->guest_slots[slot_id].delta = delta;
1358     d->guest_slots[slot_id].active = 1;
1359     return 0;
1360 }
1361 
1362 static void qxl_del_memslot(PCIQXLDevice *d, uint32_t slot_id)
1363 {
1364     qemu_spice_del_memslot(&d->ssd, MEMSLOT_GROUP_HOST, slot_id);
1365     d->guest_slots[slot_id].active = 0;
1366 }
1367 
1368 static void qxl_reset_memslots(PCIQXLDevice *d)
1369 {
1370     qxl_spice_reset_memslots(d);
1371     memset(&d->guest_slots, 0, sizeof(d->guest_slots));
1372 }
1373 
1374 static void qxl_reset_surfaces(PCIQXLDevice *d)
1375 {
1376     trace_qxl_reset_surfaces(d->id);
1377     d->mode = QXL_MODE_UNDEFINED;
1378     qxl_spice_destroy_surfaces(d, QXL_SYNC);
1379 }
1380 
1381 /* can be also called from spice server thread context */
1382 static bool qxl_get_check_slot_offset(PCIQXLDevice *qxl, QXLPHYSICAL pqxl,
1383                                       uint32_t *s, uint64_t *o)
1384 {
1385     uint64_t phys   = le64_to_cpu(pqxl);
1386     uint32_t slot   = (phys >> (64 -  8)) & 0xff;
1387     uint64_t offset = phys & 0xffffffffffff;
1388 
1389     if (slot >= NUM_MEMSLOTS) {
1390         qxl_set_guest_bug(qxl, "slot too large %d >= %d", slot,
1391                           NUM_MEMSLOTS);
1392         return false;
1393     }
1394     if (!qxl->guest_slots[slot].active) {
1395         qxl_set_guest_bug(qxl, "inactive slot %d\n", slot);
1396         return false;
1397     }
1398     if (offset < qxl->guest_slots[slot].delta) {
1399         qxl_set_guest_bug(qxl,
1400                           "slot %d offset %"PRIu64" < delta %"PRIu64"\n",
1401                           slot, offset, qxl->guest_slots[slot].delta);
1402         return false;
1403     }
1404     offset -= qxl->guest_slots[slot].delta;
1405     if (offset > qxl->guest_slots[slot].size) {
1406         qxl_set_guest_bug(qxl,
1407                           "slot %d offset %"PRIu64" > size %"PRIu64"\n",
1408                           slot, offset, qxl->guest_slots[slot].size);
1409         return false;
1410     }
1411 
1412     *s = slot;
1413     *o = offset;
1414     return true;
1415 }
1416 
1417 /* can be also called from spice server thread context */
1418 void *qxl_phys2virt(PCIQXLDevice *qxl, QXLPHYSICAL pqxl, int group_id)
1419 {
1420     uint64_t offset;
1421     uint32_t slot;
1422     void *ptr;
1423 
1424     switch (group_id) {
1425     case MEMSLOT_GROUP_HOST:
1426         offset = le64_to_cpu(pqxl) & 0xffffffffffff;
1427         return (void *)(intptr_t)offset;
1428     case MEMSLOT_GROUP_GUEST:
1429         if (!qxl_get_check_slot_offset(qxl, pqxl, &slot, &offset)) {
1430             return NULL;
1431         }
1432         ptr = memory_region_get_ram_ptr(qxl->guest_slots[slot].mr);
1433         ptr += qxl->guest_slots[slot].offset;
1434         ptr += offset;
1435         return ptr;
1436     }
1437     return NULL;
1438 }
1439 
1440 static void qxl_create_guest_primary_complete(PCIQXLDevice *qxl)
1441 {
1442     /* for local rendering */
1443     qxl_render_resize(qxl);
1444 }
1445 
1446 static void qxl_create_guest_primary(PCIQXLDevice *qxl, int loadvm,
1447                                      qxl_async_io async)
1448 {
1449     QXLDevSurfaceCreate surface;
1450     QXLSurfaceCreate *sc = &qxl->guest_primary.surface;
1451     uint32_t requested_height = le32_to_cpu(sc->height);
1452     int requested_stride = le32_to_cpu(sc->stride);
1453 
1454     if (requested_stride == INT32_MIN ||
1455         abs(requested_stride) * (uint64_t)requested_height
1456                                         > qxl->vgamem_size) {
1457         qxl_set_guest_bug(qxl, "%s: requested primary larger than framebuffer"
1458                                " stride %d x height %" PRIu32 " > %" PRIu32,
1459                                __func__, requested_stride, requested_height,
1460                                qxl->vgamem_size);
1461         return;
1462     }
1463 
1464     if (qxl->mode == QXL_MODE_NATIVE) {
1465         qxl_set_guest_bug(qxl, "%s: nop since already in QXL_MODE_NATIVE",
1466                       __func__);
1467     }
1468     qxl_exit_vga_mode(qxl);
1469 
1470     surface.format     = le32_to_cpu(sc->format);
1471     surface.height     = le32_to_cpu(sc->height);
1472     surface.mem        = le64_to_cpu(sc->mem);
1473     surface.position   = le32_to_cpu(sc->position);
1474     surface.stride     = le32_to_cpu(sc->stride);
1475     surface.width      = le32_to_cpu(sc->width);
1476     surface.type       = le32_to_cpu(sc->type);
1477     surface.flags      = le32_to_cpu(sc->flags);
1478     trace_qxl_create_guest_primary(qxl->id, sc->width, sc->height, sc->mem,
1479                                    sc->format, sc->position);
1480     trace_qxl_create_guest_primary_rest(qxl->id, sc->stride, sc->type,
1481                                         sc->flags);
1482 
1483     if ((surface.stride & 0x3) != 0) {
1484         qxl_set_guest_bug(qxl, "primary surface stride = %d %% 4 != 0",
1485                           surface.stride);
1486         return;
1487     }
1488 
1489     surface.mouse_mode = true;
1490     surface.group_id   = MEMSLOT_GROUP_GUEST;
1491     if (loadvm) {
1492         surface.flags |= QXL_SURF_FLAG_KEEP_DATA;
1493     }
1494 
1495     qxl->mode = QXL_MODE_NATIVE;
1496     qxl->cmdflags = 0;
1497     qemu_spice_create_primary_surface(&qxl->ssd, 0, &surface, async);
1498 
1499     if (async == QXL_SYNC) {
1500         qxl_create_guest_primary_complete(qxl);
1501     }
1502 }
1503 
1504 /* return 1 if surface destoy was initiated (in QXL_ASYNC case) or
1505  * done (in QXL_SYNC case), 0 otherwise. */
1506 static int qxl_destroy_primary(PCIQXLDevice *d, qxl_async_io async)
1507 {
1508     if (d->mode == QXL_MODE_UNDEFINED) {
1509         return 0;
1510     }
1511     trace_qxl_destroy_primary(d->id);
1512     d->mode = QXL_MODE_UNDEFINED;
1513     qemu_spice_destroy_primary_surface(&d->ssd, 0, async);
1514     qxl_spice_reset_cursor(d);
1515     return 1;
1516 }
1517 
1518 static void qxl_set_mode(PCIQXLDevice *d, unsigned int modenr, int loadvm)
1519 {
1520     pcibus_t start = d->pci.io_regions[QXL_RAM_RANGE_INDEX].addr;
1521     pcibus_t end   = d->pci.io_regions[QXL_RAM_RANGE_INDEX].size + start;
1522     QXLMode *mode = d->modes->modes + modenr;
1523     uint64_t devmem = d->pci.io_regions[QXL_RAM_RANGE_INDEX].addr;
1524     QXLMemSlot slot = {
1525         .mem_start = start,
1526         .mem_end = end
1527     };
1528 
1529     if (modenr >= d->modes->n_modes) {
1530         qxl_set_guest_bug(d, "mode number out of range");
1531         return;
1532     }
1533 
1534     QXLSurfaceCreate surface = {
1535         .width      = mode->x_res,
1536         .height     = mode->y_res,
1537         .stride     = -mode->x_res * 4,
1538         .format     = SPICE_SURFACE_FMT_32_xRGB,
1539         .flags      = loadvm ? QXL_SURF_FLAG_KEEP_DATA : 0,
1540         .mouse_mode = true,
1541         .mem        = devmem + d->shadow_rom.draw_area_offset,
1542     };
1543 
1544     trace_qxl_set_mode(d->id, modenr, mode->x_res, mode->y_res, mode->bits,
1545                        devmem);
1546     if (!loadvm) {
1547         qxl_hard_reset(d, 0);
1548     }
1549 
1550     d->guest_slots[0].slot = slot;
1551     assert(qxl_add_memslot(d, 0, devmem, QXL_SYNC) == 0);
1552 
1553     d->guest_primary.surface = surface;
1554     qxl_create_guest_primary(d, 0, QXL_SYNC);
1555 
1556     d->mode = QXL_MODE_COMPAT;
1557     d->cmdflags = QXL_COMMAND_FLAG_COMPAT;
1558     if (mode->bits == 16) {
1559         d->cmdflags |= QXL_COMMAND_FLAG_COMPAT_16BPP;
1560     }
1561     d->shadow_rom.mode = cpu_to_le32(modenr);
1562     d->rom->mode = cpu_to_le32(modenr);
1563     qxl_rom_set_dirty(d);
1564 }
1565 
1566 static void ioport_write(void *opaque, hwaddr addr,
1567                          uint64_t val, unsigned size)
1568 {
1569     PCIQXLDevice *d = opaque;
1570     uint32_t io_port = addr;
1571     qxl_async_io async = QXL_SYNC;
1572     uint32_t orig_io_port = io_port;
1573 
1574     if (d->guest_bug && io_port != QXL_IO_RESET) {
1575         return;
1576     }
1577 
1578     if (d->revision <= QXL_REVISION_STABLE_V10 &&
1579         io_port > QXL_IO_FLUSH_RELEASE) {
1580         qxl_set_guest_bug(d, "unsupported io %d for revision %d\n",
1581             io_port, d->revision);
1582         return;
1583     }
1584 
1585     switch (io_port) {
1586     case QXL_IO_RESET:
1587     case QXL_IO_SET_MODE:
1588     case QXL_IO_MEMSLOT_ADD:
1589     case QXL_IO_MEMSLOT_DEL:
1590     case QXL_IO_CREATE_PRIMARY:
1591     case QXL_IO_UPDATE_IRQ:
1592     case QXL_IO_LOG:
1593     case QXL_IO_MEMSLOT_ADD_ASYNC:
1594     case QXL_IO_CREATE_PRIMARY_ASYNC:
1595         break;
1596     default:
1597         if (d->mode != QXL_MODE_VGA) {
1598             break;
1599         }
1600         trace_qxl_io_unexpected_vga_mode(d->id,
1601             addr, val, io_port_to_string(io_port));
1602         /* be nice to buggy guest drivers */
1603         if (io_port >= QXL_IO_UPDATE_AREA_ASYNC &&
1604             io_port < QXL_IO_RANGE_SIZE) {
1605             qxl_send_events(d, QXL_INTERRUPT_IO_CMD);
1606         }
1607         return;
1608     }
1609 
1610     /* we change the io_port to avoid ifdeffery in the main switch */
1611     orig_io_port = io_port;
1612     switch (io_port) {
1613     case QXL_IO_UPDATE_AREA_ASYNC:
1614         io_port = QXL_IO_UPDATE_AREA;
1615         goto async_common;
1616     case QXL_IO_MEMSLOT_ADD_ASYNC:
1617         io_port = QXL_IO_MEMSLOT_ADD;
1618         goto async_common;
1619     case QXL_IO_CREATE_PRIMARY_ASYNC:
1620         io_port = QXL_IO_CREATE_PRIMARY;
1621         goto async_common;
1622     case QXL_IO_DESTROY_PRIMARY_ASYNC:
1623         io_port = QXL_IO_DESTROY_PRIMARY;
1624         goto async_common;
1625     case QXL_IO_DESTROY_SURFACE_ASYNC:
1626         io_port = QXL_IO_DESTROY_SURFACE_WAIT;
1627         goto async_common;
1628     case QXL_IO_DESTROY_ALL_SURFACES_ASYNC:
1629         io_port = QXL_IO_DESTROY_ALL_SURFACES;
1630         goto async_common;
1631     case QXL_IO_FLUSH_SURFACES_ASYNC:
1632     case QXL_IO_MONITORS_CONFIG_ASYNC:
1633 async_common:
1634         async = QXL_ASYNC;
1635         qemu_mutex_lock(&d->async_lock);
1636         if (d->current_async != QXL_UNDEFINED_IO) {
1637             qxl_set_guest_bug(d, "%d async started before last (%d) complete",
1638                 io_port, d->current_async);
1639             qemu_mutex_unlock(&d->async_lock);
1640             return;
1641         }
1642         d->current_async = orig_io_port;
1643         qemu_mutex_unlock(&d->async_lock);
1644         break;
1645     default:
1646         break;
1647     }
1648     trace_qxl_io_write(d->id, qxl_mode_to_string(d->mode),
1649                        addr, io_port_to_string(addr),
1650                        val, size, async);
1651 
1652     switch (io_port) {
1653     case QXL_IO_UPDATE_AREA:
1654     {
1655         QXLCookie *cookie = NULL;
1656         QXLRect update = d->ram->update_area;
1657 
1658         if (d->ram->update_surface > d->ssd.num_surfaces) {
1659             qxl_set_guest_bug(d, "QXL_IO_UPDATE_AREA: invalid surface id %d\n",
1660                               d->ram->update_surface);
1661             break;
1662         }
1663         if (update.left >= update.right || update.top >= update.bottom ||
1664             update.left < 0 || update.top < 0) {
1665             qxl_set_guest_bug(d,
1666                     "QXL_IO_UPDATE_AREA: invalid area (%ux%u)x(%ux%u)\n",
1667                     update.left, update.top, update.right, update.bottom);
1668             if (update.left == update.right || update.top == update.bottom) {
1669                 /* old drivers may provide empty area, keep going */
1670                 qxl_clear_guest_bug(d);
1671                 goto cancel_async;
1672             }
1673             break;
1674         }
1675         if (async == QXL_ASYNC) {
1676             cookie = qxl_cookie_new(QXL_COOKIE_TYPE_IO,
1677                                     QXL_IO_UPDATE_AREA_ASYNC);
1678             cookie->u.area = update;
1679         }
1680         qxl_spice_update_area(d, d->ram->update_surface,
1681                               cookie ? &cookie->u.area : &update,
1682                               NULL, 0, 0, async, cookie);
1683         break;
1684     }
1685     case QXL_IO_NOTIFY_CMD:
1686         qemu_spice_wakeup(&d->ssd);
1687         break;
1688     case QXL_IO_NOTIFY_CURSOR:
1689         qemu_spice_wakeup(&d->ssd);
1690         break;
1691     case QXL_IO_UPDATE_IRQ:
1692         qxl_update_irq(d);
1693         break;
1694     case QXL_IO_NOTIFY_OOM:
1695         if (!SPICE_RING_IS_EMPTY(&d->ram->release_ring)) {
1696             break;
1697         }
1698         d->oom_running = 1;
1699         qxl_spice_oom(d);
1700         d->oom_running = 0;
1701         break;
1702     case QXL_IO_SET_MODE:
1703         qxl_set_mode(d, val, 0);
1704         break;
1705     case QXL_IO_LOG:
1706         trace_qxl_io_log(d->id, d->ram->log_buf);
1707         if (d->guestdebug) {
1708             fprintf(stderr, "qxl/guest-%d: %" PRId64 ": %s", d->id,
1709                     qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL), d->ram->log_buf);
1710         }
1711         break;
1712     case QXL_IO_RESET:
1713         qxl_hard_reset(d, 0);
1714         break;
1715     case QXL_IO_MEMSLOT_ADD:
1716         if (val >= NUM_MEMSLOTS) {
1717             qxl_set_guest_bug(d, "QXL_IO_MEMSLOT_ADD: val out of range");
1718             break;
1719         }
1720         if (d->guest_slots[val].active) {
1721             qxl_set_guest_bug(d,
1722                         "QXL_IO_MEMSLOT_ADD: memory slot already active");
1723             break;
1724         }
1725         d->guest_slots[val].slot = d->ram->mem_slot;
1726         qxl_add_memslot(d, val, 0, async);
1727         break;
1728     case QXL_IO_MEMSLOT_DEL:
1729         if (val >= NUM_MEMSLOTS) {
1730             qxl_set_guest_bug(d, "QXL_IO_MEMSLOT_DEL: val out of range");
1731             break;
1732         }
1733         qxl_del_memslot(d, val);
1734         break;
1735     case QXL_IO_CREATE_PRIMARY:
1736         if (val != 0) {
1737             qxl_set_guest_bug(d, "QXL_IO_CREATE_PRIMARY (async=%d): val != 0",
1738                           async);
1739             goto cancel_async;
1740         }
1741         d->guest_primary.surface = d->ram->create_surface;
1742         qxl_create_guest_primary(d, 0, async);
1743         break;
1744     case QXL_IO_DESTROY_PRIMARY:
1745         if (val != 0) {
1746             qxl_set_guest_bug(d, "QXL_IO_DESTROY_PRIMARY (async=%d): val != 0",
1747                           async);
1748             goto cancel_async;
1749         }
1750         if (!qxl_destroy_primary(d, async)) {
1751             trace_qxl_io_destroy_primary_ignored(d->id,
1752                                                  qxl_mode_to_string(d->mode));
1753             goto cancel_async;
1754         }
1755         break;
1756     case QXL_IO_DESTROY_SURFACE_WAIT:
1757         if (val >= d->ssd.num_surfaces) {
1758             qxl_set_guest_bug(d, "QXL_IO_DESTROY_SURFACE (async=%d):"
1759                              "%" PRIu64 " >= NUM_SURFACES", async, val);
1760             goto cancel_async;
1761         }
1762         qxl_spice_destroy_surface_wait(d, val, async);
1763         break;
1764     case QXL_IO_FLUSH_RELEASE: {
1765         QXLReleaseRing *ring = &d->ram->release_ring;
1766         if (ring->prod - ring->cons + 1 == ring->num_items) {
1767             fprintf(stderr,
1768                 "ERROR: no flush, full release ring [p%d,%dc]\n",
1769                 ring->prod, ring->cons);
1770         }
1771         qxl_push_free_res(d, 1 /* flush */);
1772         break;
1773     }
1774     case QXL_IO_FLUSH_SURFACES_ASYNC:
1775         qxl_spice_flush_surfaces_async(d);
1776         break;
1777     case QXL_IO_DESTROY_ALL_SURFACES:
1778         d->mode = QXL_MODE_UNDEFINED;
1779         qxl_spice_destroy_surfaces(d, async);
1780         break;
1781     case QXL_IO_MONITORS_CONFIG_ASYNC:
1782         qxl_spice_monitors_config_async(d, 0);
1783         break;
1784     default:
1785         qxl_set_guest_bug(d, "%s: unexpected ioport=0x%x\n", __func__, io_port);
1786     }
1787     return;
1788 cancel_async:
1789     if (async) {
1790         qxl_send_events(d, QXL_INTERRUPT_IO_CMD);
1791         qemu_mutex_lock(&d->async_lock);
1792         d->current_async = QXL_UNDEFINED_IO;
1793         qemu_mutex_unlock(&d->async_lock);
1794     }
1795 }
1796 
1797 static uint64_t ioport_read(void *opaque, hwaddr addr,
1798                             unsigned size)
1799 {
1800     PCIQXLDevice *qxl = opaque;
1801 
1802     trace_qxl_io_read_unexpected(qxl->id);
1803     return 0xff;
1804 }
1805 
1806 static const MemoryRegionOps qxl_io_ops = {
1807     .read = ioport_read,
1808     .write = ioport_write,
1809     .valid = {
1810         .min_access_size = 1,
1811         .max_access_size = 1,
1812     },
1813 };
1814 
1815 static void qxl_update_irq_bh(void *opaque)
1816 {
1817     PCIQXLDevice *d = opaque;
1818     qxl_update_irq(d);
1819 }
1820 
1821 static void qxl_send_events(PCIQXLDevice *d, uint32_t events)
1822 {
1823     uint32_t old_pending;
1824     uint32_t le_events = cpu_to_le32(events);
1825 
1826     trace_qxl_send_events(d->id, events);
1827     if (!qemu_spice_display_is_running(&d->ssd)) {
1828         /* spice-server tracks guest running state and should not do this */
1829         fprintf(stderr, "%s: spice-server bug: guest stopped, ignoring\n",
1830                 __func__);
1831         trace_qxl_send_events_vm_stopped(d->id, events);
1832         return;
1833     }
1834     old_pending = atomic_fetch_or(&d->ram->int_pending, le_events);
1835     if ((old_pending & le_events) == le_events) {
1836         return;
1837     }
1838     qemu_bh_schedule(d->update_irq);
1839 }
1840 
1841 /* graphics console */
1842 
1843 static void qxl_hw_update(void *opaque)
1844 {
1845     PCIQXLDevice *qxl = opaque;
1846 
1847     qxl_render_update(qxl);
1848 }
1849 
1850 static void qxl_dirty_one_surface(PCIQXLDevice *qxl, QXLPHYSICAL pqxl,
1851                                   uint32_t height, int32_t stride)
1852 {
1853     uint64_t offset, size;
1854     uint32_t slot;
1855     bool rc;
1856 
1857     rc = qxl_get_check_slot_offset(qxl, pqxl, &slot, &offset);
1858     assert(rc == true);
1859     size = (uint64_t)height * abs(stride);
1860     trace_qxl_surfaces_dirty(qxl->id, offset, size);
1861     qxl_set_dirty(qxl->guest_slots[slot].mr,
1862                   qxl->guest_slots[slot].offset + offset,
1863                   qxl->guest_slots[slot].offset + offset + size);
1864 }
1865 
1866 static void qxl_dirty_surfaces(PCIQXLDevice *qxl)
1867 {
1868     int i;
1869 
1870     if (qxl->mode != QXL_MODE_NATIVE && qxl->mode != QXL_MODE_COMPAT) {
1871         return;
1872     }
1873 
1874     /* dirty the primary surface */
1875     qxl_dirty_one_surface(qxl, qxl->guest_primary.surface.mem,
1876                           qxl->guest_primary.surface.height,
1877                           qxl->guest_primary.surface.stride);
1878 
1879     /* dirty the off-screen surfaces */
1880     for (i = 0; i < qxl->ssd.num_surfaces; i++) {
1881         QXLSurfaceCmd *cmd;
1882 
1883         if (qxl->guest_surfaces.cmds[i] == 0) {
1884             continue;
1885         }
1886 
1887         cmd = qxl_phys2virt(qxl, qxl->guest_surfaces.cmds[i],
1888                             MEMSLOT_GROUP_GUEST);
1889         assert(cmd);
1890         assert(cmd->type == QXL_SURFACE_CMD_CREATE);
1891         qxl_dirty_one_surface(qxl, cmd->u.surface_create.data,
1892                               cmd->u.surface_create.height,
1893                               cmd->u.surface_create.stride);
1894     }
1895 }
1896 
1897 static void qxl_vm_change_state_handler(void *opaque, int running,
1898                                         RunState state)
1899 {
1900     PCIQXLDevice *qxl = opaque;
1901 
1902     if (running) {
1903         /*
1904          * if qxl_send_events was called from spice server context before
1905          * migration ended, qxl_update_irq for these events might not have been
1906          * called
1907          */
1908          qxl_update_irq(qxl);
1909     } else {
1910         /* make sure surfaces are saved before migration */
1911         qxl_dirty_surfaces(qxl);
1912     }
1913 }
1914 
1915 /* display change listener */
1916 
1917 static void display_update(DisplayChangeListener *dcl,
1918                            int x, int y, int w, int h)
1919 {
1920     PCIQXLDevice *qxl = container_of(dcl, PCIQXLDevice, ssd.dcl);
1921 
1922     if (qxl->mode == QXL_MODE_VGA) {
1923         qemu_spice_display_update(&qxl->ssd, x, y, w, h);
1924     }
1925 }
1926 
1927 static void display_switch(DisplayChangeListener *dcl,
1928                            struct DisplaySurface *surface)
1929 {
1930     PCIQXLDevice *qxl = container_of(dcl, PCIQXLDevice, ssd.dcl);
1931 
1932     qxl->ssd.ds = surface;
1933     if (qxl->mode == QXL_MODE_VGA) {
1934         qemu_spice_display_switch(&qxl->ssd, surface);
1935     }
1936 }
1937 
1938 static void display_refresh(DisplayChangeListener *dcl)
1939 {
1940     PCIQXLDevice *qxl = container_of(dcl, PCIQXLDevice, ssd.dcl);
1941 
1942     if (qxl->mode == QXL_MODE_VGA) {
1943         qemu_spice_display_refresh(&qxl->ssd);
1944     }
1945 }
1946 
1947 static DisplayChangeListenerOps display_listener_ops = {
1948     .dpy_name        = "spice/qxl",
1949     .dpy_gfx_update  = display_update,
1950     .dpy_gfx_switch  = display_switch,
1951     .dpy_refresh     = display_refresh,
1952 };
1953 
1954 static void qxl_init_ramsize(PCIQXLDevice *qxl)
1955 {
1956     /* vga mode framebuffer / primary surface (bar 0, first part) */
1957     if (qxl->vgamem_size_mb < 8) {
1958         qxl->vgamem_size_mb = 8;
1959     }
1960     /* XXX: we round vgamem_size_mb up to a nearest power of two and it must be
1961      * less than vga_common_init()'s maximum on qxl->vga.vram_size (512 now).
1962      */
1963     if (qxl->vgamem_size_mb > 256) {
1964         qxl->vgamem_size_mb = 256;
1965     }
1966     qxl->vgamem_size = qxl->vgamem_size_mb * 1024 * 1024;
1967 
1968     /* vga ram (bar 0, total) */
1969     if (qxl->ram_size_mb != -1) {
1970         qxl->vga.vram_size = qxl->ram_size_mb * 1024 * 1024;
1971     }
1972     if (qxl->vga.vram_size < qxl->vgamem_size * 2) {
1973         qxl->vga.vram_size = qxl->vgamem_size * 2;
1974     }
1975 
1976     /* vram32 (surfaces, 32bit, bar 1) */
1977     if (qxl->vram32_size_mb != -1) {
1978         qxl->vram32_size = qxl->vram32_size_mb * 1024 * 1024;
1979     }
1980     if (qxl->vram32_size < 4096) {
1981         qxl->vram32_size = 4096;
1982     }
1983 
1984     /* vram (surfaces, 64bit, bar 4+5) */
1985     if (qxl->vram_size_mb != -1) {
1986         qxl->vram_size = (uint64_t)qxl->vram_size_mb * 1024 * 1024;
1987     }
1988     if (qxl->vram_size < qxl->vram32_size) {
1989         qxl->vram_size = qxl->vram32_size;
1990     }
1991 
1992     if (qxl->revision == 1) {
1993         qxl->vram32_size = 4096;
1994         qxl->vram_size = 4096;
1995     }
1996     qxl->vgamem_size = pow2ceil(qxl->vgamem_size);
1997     qxl->vga.vram_size = pow2ceil(qxl->vga.vram_size);
1998     qxl->vram32_size = pow2ceil(qxl->vram32_size);
1999     qxl->vram_size = pow2ceil(qxl->vram_size);
2000 }
2001 
2002 static void qxl_realize_common(PCIQXLDevice *qxl, Error **errp)
2003 {
2004     uint8_t* config = qxl->pci.config;
2005     uint32_t pci_device_rev;
2006     uint32_t io_size;
2007 
2008     qxl->mode = QXL_MODE_UNDEFINED;
2009     qxl->generation = 1;
2010     qxl->num_memslots = NUM_MEMSLOTS;
2011     qemu_mutex_init(&qxl->track_lock);
2012     qemu_mutex_init(&qxl->async_lock);
2013     qxl->current_async = QXL_UNDEFINED_IO;
2014     qxl->guest_bug = 0;
2015 
2016     switch (qxl->revision) {
2017     case 1: /* spice 0.4 -- qxl-1 */
2018         pci_device_rev = QXL_REVISION_STABLE_V04;
2019         io_size = 8;
2020         break;
2021     case 2: /* spice 0.6 -- qxl-2 */
2022         pci_device_rev = QXL_REVISION_STABLE_V06;
2023         io_size = 16;
2024         break;
2025     case 3: /* qxl-3 */
2026         pci_device_rev = QXL_REVISION_STABLE_V10;
2027         io_size = 32; /* PCI region size must be pow2 */
2028         break;
2029     case 4: /* qxl-4 */
2030         pci_device_rev = QXL_REVISION_STABLE_V12;
2031         io_size = pow2ceil(QXL_IO_RANGE_SIZE);
2032         break;
2033     default:
2034         error_setg(errp, "Invalid revision %d for qxl device (max %d)",
2035                    qxl->revision, QXL_DEFAULT_REVISION);
2036         return;
2037     }
2038 
2039     pci_set_byte(&config[PCI_REVISION_ID], pci_device_rev);
2040     pci_set_byte(&config[PCI_INTERRUPT_PIN], 1);
2041 
2042     qxl->rom_size = qxl_rom_size();
2043     memory_region_init_ram(&qxl->rom_bar, OBJECT(qxl), "qxl.vrom",
2044                            qxl->rom_size, &error_fatal);
2045     vmstate_register_ram(&qxl->rom_bar, &qxl->pci.qdev);
2046     init_qxl_rom(qxl);
2047     init_qxl_ram(qxl);
2048 
2049     qxl->guest_surfaces.cmds = g_new0(QXLPHYSICAL, qxl->ssd.num_surfaces);
2050     memory_region_init_ram(&qxl->vram_bar, OBJECT(qxl), "qxl.vram",
2051                            qxl->vram_size, &error_fatal);
2052     vmstate_register_ram(&qxl->vram_bar, &qxl->pci.qdev);
2053     memory_region_init_alias(&qxl->vram32_bar, OBJECT(qxl), "qxl.vram32",
2054                              &qxl->vram_bar, 0, qxl->vram32_size);
2055 
2056     memory_region_init_io(&qxl->io_bar, OBJECT(qxl), &qxl_io_ops, qxl,
2057                           "qxl-ioports", io_size);
2058     if (qxl->id == 0) {
2059         vga_dirty_log_start(&qxl->vga);
2060     }
2061     memory_region_set_flush_coalesced(&qxl->io_bar);
2062 
2063 
2064     pci_register_bar(&qxl->pci, QXL_IO_RANGE_INDEX,
2065                      PCI_BASE_ADDRESS_SPACE_IO, &qxl->io_bar);
2066 
2067     pci_register_bar(&qxl->pci, QXL_ROM_RANGE_INDEX,
2068                      PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->rom_bar);
2069 
2070     pci_register_bar(&qxl->pci, QXL_RAM_RANGE_INDEX,
2071                      PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vga.vram);
2072 
2073     pci_register_bar(&qxl->pci, QXL_VRAM_RANGE_INDEX,
2074                      PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vram32_bar);
2075 
2076     if (qxl->vram32_size < qxl->vram_size) {
2077         /*
2078          * Make the 64bit vram bar show up only in case it is
2079          * configured to be larger than the 32bit vram bar.
2080          */
2081         pci_register_bar(&qxl->pci, QXL_VRAM64_RANGE_INDEX,
2082                          PCI_BASE_ADDRESS_SPACE_MEMORY |
2083                          PCI_BASE_ADDRESS_MEM_TYPE_64 |
2084                          PCI_BASE_ADDRESS_MEM_PREFETCH,
2085                          &qxl->vram_bar);
2086     }
2087 
2088     /* print pci bar details */
2089     dprint(qxl, 1, "ram/%s: %d MB [region 0]\n",
2090            qxl->id == 0 ? "pri" : "sec",
2091            qxl->vga.vram_size / (1024*1024));
2092     dprint(qxl, 1, "vram/32: %" PRIx64 "d MB [region 1]\n",
2093            qxl->vram32_size / (1024*1024));
2094     dprint(qxl, 1, "vram/64: %" PRIx64 "d MB %s\n",
2095            qxl->vram_size / (1024*1024),
2096            qxl->vram32_size < qxl->vram_size ? "[region 4]" : "[unmapped]");
2097 
2098     qxl->ssd.qxl.base.sif = &qxl_interface.base;
2099     if (qemu_spice_add_display_interface(&qxl->ssd.qxl, qxl->vga.con) != 0) {
2100         error_setg(errp, "qxl interface %d.%d not supported by spice-server",
2101                    SPICE_INTERFACE_QXL_MAJOR, SPICE_INTERFACE_QXL_MINOR);
2102         return;
2103     }
2104     qemu_add_vm_change_state_handler(qxl_vm_change_state_handler, qxl);
2105 
2106     qxl->update_irq = qemu_bh_new(qxl_update_irq_bh, qxl);
2107     qxl_reset_state(qxl);
2108 
2109     qxl->update_area_bh = qemu_bh_new(qxl_render_update_area_bh, qxl);
2110     qxl->ssd.cursor_bh = qemu_bh_new(qemu_spice_cursor_refresh_bh, &qxl->ssd);
2111 }
2112 
2113 static void qxl_realize_primary(PCIDevice *dev, Error **errp)
2114 {
2115     PCIQXLDevice *qxl = PCI_QXL(dev);
2116     VGACommonState *vga = &qxl->vga;
2117     Error *local_err = NULL;
2118 
2119     qxl->id = 0;
2120     qxl_init_ramsize(qxl);
2121     vga->vbe_size = qxl->vgamem_size;
2122     vga->vram_size_mb = qxl->vga.vram_size >> 20;
2123     vga_common_init(vga, OBJECT(dev), true);
2124     vga_init(vga, OBJECT(dev),
2125              pci_address_space(dev), pci_address_space_io(dev), false);
2126     portio_list_init(&qxl->vga_port_list, OBJECT(dev), qxl_vga_portio_list,
2127                      vga, "vga");
2128     portio_list_set_flush_coalesced(&qxl->vga_port_list);
2129     portio_list_add(&qxl->vga_port_list, pci_address_space_io(dev), 0x3b0);
2130 
2131     vga->con = graphic_console_init(DEVICE(dev), 0, &qxl_ops, qxl);
2132     qemu_spice_display_init_common(&qxl->ssd);
2133 
2134     qxl_realize_common(qxl, &local_err);
2135     if (local_err) {
2136         error_propagate(errp, local_err);
2137         return;
2138     }
2139 
2140     qxl->ssd.dcl.ops = &display_listener_ops;
2141     qxl->ssd.dcl.con = vga->con;
2142     register_displaychangelistener(&qxl->ssd.dcl);
2143 }
2144 
2145 static void qxl_realize_secondary(PCIDevice *dev, Error **errp)
2146 {
2147     static int device_id = 1;
2148     PCIQXLDevice *qxl = PCI_QXL(dev);
2149 
2150     qxl->id = device_id++;
2151     qxl_init_ramsize(qxl);
2152     memory_region_init_ram(&qxl->vga.vram, OBJECT(dev), "qxl.vgavram",
2153                            qxl->vga.vram_size, &error_fatal);
2154     vmstate_register_ram(&qxl->vga.vram, &qxl->pci.qdev);
2155     qxl->vga.vram_ptr = memory_region_get_ram_ptr(&qxl->vga.vram);
2156     qxl->vga.con = graphic_console_init(DEVICE(dev), 0, &qxl_ops, qxl);
2157 
2158     qxl_realize_common(qxl, errp);
2159 }
2160 
2161 static void qxl_pre_save(void *opaque)
2162 {
2163     PCIQXLDevice* d = opaque;
2164     uint8_t *ram_start = d->vga.vram_ptr;
2165 
2166     trace_qxl_pre_save(d->id);
2167     if (d->last_release == NULL) {
2168         d->last_release_offset = 0;
2169     } else {
2170         d->last_release_offset = (uint8_t *)d->last_release - ram_start;
2171     }
2172     assert(d->last_release_offset < d->vga.vram_size);
2173 }
2174 
2175 static int qxl_pre_load(void *opaque)
2176 {
2177     PCIQXLDevice* d = opaque;
2178 
2179     trace_qxl_pre_load(d->id);
2180     qxl_hard_reset(d, 1);
2181     qxl_exit_vga_mode(d);
2182     return 0;
2183 }
2184 
2185 static void qxl_create_memslots(PCIQXLDevice *d)
2186 {
2187     int i;
2188 
2189     for (i = 0; i < NUM_MEMSLOTS; i++) {
2190         if (!d->guest_slots[i].active) {
2191             continue;
2192         }
2193         qxl_add_memslot(d, i, 0, QXL_SYNC);
2194     }
2195 }
2196 
2197 static int qxl_post_load(void *opaque, int version)
2198 {
2199     PCIQXLDevice* d = opaque;
2200     uint8_t *ram_start = d->vga.vram_ptr;
2201     QXLCommandExt *cmds;
2202     int in, out, newmode;
2203 
2204     assert(d->last_release_offset < d->vga.vram_size);
2205     if (d->last_release_offset == 0) {
2206         d->last_release = NULL;
2207     } else {
2208         d->last_release = (QXLReleaseInfo *)(ram_start + d->last_release_offset);
2209     }
2210 
2211     d->modes = (QXLModes*)((uint8_t*)d->rom + d->rom->modes_offset);
2212 
2213     trace_qxl_post_load(d->id, qxl_mode_to_string(d->mode));
2214     newmode = d->mode;
2215     d->mode = QXL_MODE_UNDEFINED;
2216 
2217     switch (newmode) {
2218     case QXL_MODE_UNDEFINED:
2219         qxl_create_memslots(d);
2220         break;
2221     case QXL_MODE_VGA:
2222         qxl_create_memslots(d);
2223         qxl_enter_vga_mode(d);
2224         break;
2225     case QXL_MODE_NATIVE:
2226         qxl_create_memslots(d);
2227         qxl_create_guest_primary(d, 1, QXL_SYNC);
2228 
2229         /* replay surface-create and cursor-set commands */
2230         cmds = g_new0(QXLCommandExt, d->ssd.num_surfaces + 1);
2231         for (in = 0, out = 0; in < d->ssd.num_surfaces; in++) {
2232             if (d->guest_surfaces.cmds[in] == 0) {
2233                 continue;
2234             }
2235             cmds[out].cmd.data = d->guest_surfaces.cmds[in];
2236             cmds[out].cmd.type = QXL_CMD_SURFACE;
2237             cmds[out].group_id = MEMSLOT_GROUP_GUEST;
2238             out++;
2239         }
2240         if (d->guest_cursor) {
2241             cmds[out].cmd.data = d->guest_cursor;
2242             cmds[out].cmd.type = QXL_CMD_CURSOR;
2243             cmds[out].group_id = MEMSLOT_GROUP_GUEST;
2244             out++;
2245         }
2246         qxl_spice_loadvm_commands(d, cmds, out);
2247         g_free(cmds);
2248         if (d->guest_monitors_config) {
2249             qxl_spice_monitors_config_async(d, 1);
2250         }
2251         break;
2252     case QXL_MODE_COMPAT:
2253         /* note: no need to call qxl_create_memslots, qxl_set_mode
2254          * creates the mem slot. */
2255         qxl_set_mode(d, d->shadow_rom.mode, 1);
2256         break;
2257     }
2258     return 0;
2259 }
2260 
2261 #define QXL_SAVE_VERSION 21
2262 
2263 static bool qxl_monitors_config_needed(void *opaque)
2264 {
2265     PCIQXLDevice *qxl = opaque;
2266 
2267     return qxl->guest_monitors_config != 0;
2268 }
2269 
2270 
2271 static VMStateDescription qxl_memslot = {
2272     .name               = "qxl-memslot",
2273     .version_id         = QXL_SAVE_VERSION,
2274     .minimum_version_id = QXL_SAVE_VERSION,
2275     .fields = (VMStateField[]) {
2276         VMSTATE_UINT64(slot.mem_start, struct guest_slots),
2277         VMSTATE_UINT64(slot.mem_end,   struct guest_slots),
2278         VMSTATE_UINT32(active,         struct guest_slots),
2279         VMSTATE_END_OF_LIST()
2280     }
2281 };
2282 
2283 static VMStateDescription qxl_surface = {
2284     .name               = "qxl-surface",
2285     .version_id         = QXL_SAVE_VERSION,
2286     .minimum_version_id = QXL_SAVE_VERSION,
2287     .fields = (VMStateField[]) {
2288         VMSTATE_UINT32(width,      QXLSurfaceCreate),
2289         VMSTATE_UINT32(height,     QXLSurfaceCreate),
2290         VMSTATE_INT32(stride,      QXLSurfaceCreate),
2291         VMSTATE_UINT32(format,     QXLSurfaceCreate),
2292         VMSTATE_UINT32(position,   QXLSurfaceCreate),
2293         VMSTATE_UINT32(mouse_mode, QXLSurfaceCreate),
2294         VMSTATE_UINT32(flags,      QXLSurfaceCreate),
2295         VMSTATE_UINT32(type,       QXLSurfaceCreate),
2296         VMSTATE_UINT64(mem,        QXLSurfaceCreate),
2297         VMSTATE_END_OF_LIST()
2298     }
2299 };
2300 
2301 static VMStateDescription qxl_vmstate_monitors_config = {
2302     .name               = "qxl/monitors-config",
2303     .version_id         = 1,
2304     .minimum_version_id = 1,
2305     .needed = qxl_monitors_config_needed,
2306     .fields = (VMStateField[]) {
2307         VMSTATE_UINT64(guest_monitors_config, PCIQXLDevice),
2308         VMSTATE_END_OF_LIST()
2309     },
2310 };
2311 
2312 static VMStateDescription qxl_vmstate = {
2313     .name               = "qxl",
2314     .version_id         = QXL_SAVE_VERSION,
2315     .minimum_version_id = QXL_SAVE_VERSION,
2316     .pre_save           = qxl_pre_save,
2317     .pre_load           = qxl_pre_load,
2318     .post_load          = qxl_post_load,
2319     .fields = (VMStateField[]) {
2320         VMSTATE_PCI_DEVICE(pci, PCIQXLDevice),
2321         VMSTATE_STRUCT(vga, PCIQXLDevice, 0, vmstate_vga_common, VGACommonState),
2322         VMSTATE_UINT32(shadow_rom.mode, PCIQXLDevice),
2323         VMSTATE_UINT32(num_free_res, PCIQXLDevice),
2324         VMSTATE_UINT32(last_release_offset, PCIQXLDevice),
2325         VMSTATE_UINT32(mode, PCIQXLDevice),
2326         VMSTATE_UINT32(ssd.unique, PCIQXLDevice),
2327         VMSTATE_INT32_EQUAL(num_memslots, PCIQXLDevice),
2328         VMSTATE_STRUCT_ARRAY(guest_slots, PCIQXLDevice, NUM_MEMSLOTS, 0,
2329                              qxl_memslot, struct guest_slots),
2330         VMSTATE_STRUCT(guest_primary.surface, PCIQXLDevice, 0,
2331                        qxl_surface, QXLSurfaceCreate),
2332         VMSTATE_INT32_EQUAL(ssd.num_surfaces, PCIQXLDevice),
2333         VMSTATE_VARRAY_INT32(guest_surfaces.cmds, PCIQXLDevice,
2334                              ssd.num_surfaces, 0,
2335                              vmstate_info_uint64, uint64_t),
2336         VMSTATE_UINT64(guest_cursor, PCIQXLDevice),
2337         VMSTATE_END_OF_LIST()
2338     },
2339     .subsections = (const VMStateDescription*[]) {
2340         &qxl_vmstate_monitors_config,
2341         NULL
2342     }
2343 };
2344 
2345 static Property qxl_properties[] = {
2346         DEFINE_PROP_UINT32("ram_size", PCIQXLDevice, vga.vram_size,
2347                            64 * 1024 * 1024),
2348         DEFINE_PROP_UINT64("vram_size", PCIQXLDevice, vram32_size,
2349                            64 * 1024 * 1024),
2350         DEFINE_PROP_UINT32("revision", PCIQXLDevice, revision,
2351                            QXL_DEFAULT_REVISION),
2352         DEFINE_PROP_UINT32("debug", PCIQXLDevice, debug, 0),
2353         DEFINE_PROP_UINT32("guestdebug", PCIQXLDevice, guestdebug, 0),
2354         DEFINE_PROP_UINT32("cmdlog", PCIQXLDevice, cmdlog, 0),
2355         DEFINE_PROP_UINT32("ram_size_mb",  PCIQXLDevice, ram_size_mb, -1),
2356         DEFINE_PROP_UINT32("vram_size_mb", PCIQXLDevice, vram32_size_mb, -1),
2357         DEFINE_PROP_UINT32("vram64_size_mb", PCIQXLDevice, vram_size_mb, -1),
2358         DEFINE_PROP_UINT32("vgamem_mb", PCIQXLDevice, vgamem_size_mb, 16),
2359         DEFINE_PROP_INT32("surfaces", PCIQXLDevice, ssd.num_surfaces, 1024),
2360 #if SPICE_SERVER_VERSION >= 0x000c06 /* release 0.12.6 */
2361         DEFINE_PROP_UINT16("max_outputs", PCIQXLDevice, max_outputs, 0),
2362 #endif
2363         DEFINE_PROP_END_OF_LIST(),
2364 };
2365 
2366 static void qxl_pci_class_init(ObjectClass *klass, void *data)
2367 {
2368     DeviceClass *dc = DEVICE_CLASS(klass);
2369     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2370 
2371     k->vendor_id = REDHAT_PCI_VENDOR_ID;
2372     k->device_id = QXL_DEVICE_ID_STABLE;
2373     set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories);
2374     dc->reset = qxl_reset_handler;
2375     dc->vmsd = &qxl_vmstate;
2376     dc->props = qxl_properties;
2377 }
2378 
2379 static const TypeInfo qxl_pci_type_info = {
2380     .name = TYPE_PCI_QXL,
2381     .parent = TYPE_PCI_DEVICE,
2382     .instance_size = sizeof(PCIQXLDevice),
2383     .abstract = true,
2384     .class_init = qxl_pci_class_init,
2385 };
2386 
2387 static void qxl_primary_class_init(ObjectClass *klass, void *data)
2388 {
2389     DeviceClass *dc = DEVICE_CLASS(klass);
2390     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2391 
2392     k->realize = qxl_realize_primary;
2393     k->romfile = "vgabios-qxl.bin";
2394     k->class_id = PCI_CLASS_DISPLAY_VGA;
2395     dc->desc = "Spice QXL GPU (primary, vga compatible)";
2396     dc->hotpluggable = false;
2397 }
2398 
2399 static const TypeInfo qxl_primary_info = {
2400     .name          = "qxl-vga",
2401     .parent        = TYPE_PCI_QXL,
2402     .class_init    = qxl_primary_class_init,
2403 };
2404 
2405 static void qxl_secondary_class_init(ObjectClass *klass, void *data)
2406 {
2407     DeviceClass *dc = DEVICE_CLASS(klass);
2408     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
2409 
2410     k->realize = qxl_realize_secondary;
2411     k->class_id = PCI_CLASS_DISPLAY_OTHER;
2412     dc->desc = "Spice QXL GPU (secondary)";
2413 }
2414 
2415 static const TypeInfo qxl_secondary_info = {
2416     .name          = "qxl",
2417     .parent        = TYPE_PCI_QXL,
2418     .class_init    = qxl_secondary_class_init,
2419 };
2420 
2421 static void qxl_register_types(void)
2422 {
2423     type_register_static(&qxl_pci_type_info);
2424     type_register_static(&qxl_primary_info);
2425     type_register_static(&qxl_secondary_info);
2426 }
2427 
2428 type_init(qxl_register_types)
2429