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