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