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