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