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