Don't look up pid/tid on YAGL_LOG_FUNC_SET
[sdk/emulator/qemu.git] / ui / spice-display.c
1 /*
2  * Copyright (C) 2010 Red Hat, Inc.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 or
7  * (at your option) version 3 of the License.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include "qemu/osdep.h"
19 #include "qemu-common.h"
20 #include "ui/qemu-spice.h"
21 #include "qemu/timer.h"
22 #include "qemu/queue.h"
23 #include "ui/console.h"
24 #include "sysemu/sysemu.h"
25 #include "trace.h"
26
27 #include "ui/spice-display.h"
28
29 #ifdef CONFIG_MARU
30 #define RATIO_SCALE 2
31 #endif
32
33 static int debug = 0;
34
35 static void GCC_FMT_ATTR(2, 3) dprint(int level, const char *fmt, ...)
36 {
37     va_list args;
38
39     if (level <= debug) {
40         va_start(args, fmt);
41         vfprintf(stderr, fmt, args);
42         va_end(args);
43     }
44 }
45
46 int qemu_spice_rect_is_empty(const QXLRect* r)
47 {
48     return r->top == r->bottom || r->left == r->right;
49 }
50
51 void qemu_spice_rect_union(QXLRect *dest, const QXLRect *r)
52 {
53     if (qemu_spice_rect_is_empty(r)) {
54         return;
55     }
56
57     if (qemu_spice_rect_is_empty(dest)) {
58         *dest = *r;
59         return;
60     }
61
62     dest->top = MIN(dest->top, r->top);
63     dest->left = MIN(dest->left, r->left);
64     dest->bottom = MAX(dest->bottom, r->bottom);
65     dest->right = MAX(dest->right, r->right);
66 }
67
68 QXLCookie *qxl_cookie_new(int type, uint64_t io)
69 {
70     QXLCookie *cookie;
71
72     cookie = g_malloc0(sizeof(*cookie));
73     cookie->type = type;
74     cookie->io = io;
75     return cookie;
76 }
77
78 void qemu_spice_add_memslot(SimpleSpiceDisplay *ssd, QXLDevMemSlot *memslot,
79                             qxl_async_io async)
80 {
81     trace_qemu_spice_add_memslot(ssd->qxl.id, memslot->slot_id,
82                                 memslot->virt_start, memslot->virt_end,
83                                 async);
84
85     if (async != QXL_SYNC) {
86         spice_qxl_add_memslot_async(&ssd->qxl, memslot,
87                 (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_IO,
88                                           QXL_IO_MEMSLOT_ADD_ASYNC));
89     } else {
90         spice_qxl_add_memslot(&ssd->qxl, memslot);
91     }
92 }
93
94 void qemu_spice_del_memslot(SimpleSpiceDisplay *ssd, uint32_t gid, uint32_t sid)
95 {
96     trace_qemu_spice_del_memslot(ssd->qxl.id, gid, sid);
97     spice_qxl_del_memslot(&ssd->qxl, gid, sid);
98 }
99
100 void qemu_spice_create_primary_surface(SimpleSpiceDisplay *ssd, uint32_t id,
101                                        QXLDevSurfaceCreate *surface,
102                                        qxl_async_io async)
103 {
104     trace_qemu_spice_create_primary_surface(ssd->qxl.id, id, surface, async);
105     if (async != QXL_SYNC) {
106         spice_qxl_create_primary_surface_async(&ssd->qxl, id, surface,
107                 (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_IO,
108                                           QXL_IO_CREATE_PRIMARY_ASYNC));
109     } else {
110         spice_qxl_create_primary_surface(&ssd->qxl, id, surface);
111     }
112 }
113
114 void qemu_spice_destroy_primary_surface(SimpleSpiceDisplay *ssd,
115                                         uint32_t id, qxl_async_io async)
116 {
117     trace_qemu_spice_destroy_primary_surface(ssd->qxl.id, id, async);
118     if (async != QXL_SYNC) {
119         spice_qxl_destroy_primary_surface_async(&ssd->qxl, id,
120                 (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_IO,
121                                           QXL_IO_DESTROY_PRIMARY_ASYNC));
122     } else {
123         spice_qxl_destroy_primary_surface(&ssd->qxl, id);
124     }
125 }
126
127 void qemu_spice_wakeup(SimpleSpiceDisplay *ssd)
128 {
129     trace_qemu_spice_wakeup(ssd->qxl.id);
130     spice_qxl_wakeup(&ssd->qxl);
131 }
132
133 static void qemu_spice_create_one_update(SimpleSpiceDisplay *ssd,
134                                          QXLRect *rect)
135 {
136     SimpleSpiceUpdate *update;
137     QXLDrawable *drawable;
138     QXLImage *image;
139     QXLCommand *cmd;
140     int bw, bh;
141     struct timespec time_space;
142     pixman_image_t *dest;
143
144     trace_qemu_spice_create_update(
145            rect->left, rect->right,
146            rect->top, rect->bottom);
147
148     update   = g_malloc0(sizeof(*update));
149     drawable = &update->drawable;
150     image    = &update->image;
151     cmd      = &update->ext.cmd;
152
153     bw       = rect->right - rect->left;
154     bh       = rect->bottom - rect->top;
155     update->bitmap = g_malloc(bw * bh * 4);
156
157     drawable->bbox            = *rect;
158     drawable->clip.type       = SPICE_CLIP_TYPE_NONE;
159     drawable->effect          = QXL_EFFECT_OPAQUE;
160     drawable->release_info.id = (uintptr_t)(&update->ext);
161     drawable->type            = QXL_DRAW_COPY;
162     drawable->surfaces_dest[0] = -1;
163     drawable->surfaces_dest[1] = -1;
164     drawable->surfaces_dest[2] = -1;
165     clock_gettime(CLOCK_MONOTONIC, &time_space);
166     /* time in milliseconds from epoch. */
167     drawable->mm_time = time_space.tv_sec * 1000
168                       + time_space.tv_nsec / 1000 / 1000;
169
170     drawable->u.copy.rop_descriptor  = SPICE_ROPD_OP_PUT;
171     drawable->u.copy.src_bitmap      = (uintptr_t)image;
172     drawable->u.copy.src_area.right  = bw;
173     drawable->u.copy.src_area.bottom = bh;
174
175     QXL_SET_IMAGE_ID(image, QXL_IMAGE_GROUP_DEVICE, ssd->unique++);
176     image->descriptor.type   = SPICE_IMAGE_TYPE_BITMAP;
177     image->bitmap.flags      = QXL_BITMAP_DIRECT | QXL_BITMAP_TOP_DOWN;
178     image->bitmap.stride     = bw * 4;
179     image->descriptor.width  = image->bitmap.x = bw;
180     image->descriptor.height = image->bitmap.y = bh;
181     image->bitmap.data = (uintptr_t)(update->bitmap);
182     image->bitmap.palette = 0;
183     image->bitmap.format = SPICE_BITMAP_FMT_32BIT;
184
185     dest = pixman_image_create_bits(PIXMAN_LE_x8r8g8b8, bw, bh,
186                                     (void *)update->bitmap, bw * 4);
187     pixman_image_composite(PIXMAN_OP_SRC, ssd->surface, NULL, ssd->mirror,
188                            rect->left, rect->top, 0, 0,
189                            rect->left, rect->top, bw, bh);
190     pixman_image_composite(PIXMAN_OP_SRC, ssd->mirror, NULL, dest,
191                            rect->left, rect->top, 0, 0,
192                            0, 0, bw, bh);
193     pixman_image_unref(dest);
194
195     cmd->type = QXL_CMD_DRAW;
196     cmd->data = (uintptr_t)drawable;
197
198     QTAILQ_INSERT_TAIL(&ssd->updates, update, next);
199 }
200
201 static void qemu_spice_create_update(SimpleSpiceDisplay *ssd)
202 {
203 #ifndef CONFIG_MARU
204     static const int blksize = 32;
205     int blocks = DIV_ROUND_UP(surface_width(ssd->ds), blksize);
206     int dirty_top[blocks];
207     int y, yoff1, yoff2, x, xoff, blk, bw;
208     int bpp = surface_bytes_per_pixel(ssd->ds);
209     uint8_t *guest, *mirror;
210 #endif
211
212     if (qemu_spice_rect_is_empty(&ssd->dirty)) {
213         return;
214     };
215
216     if (ssd->surface == NULL) {
217         ssd->surface = pixman_image_ref(ssd->ds->image);
218         ssd->mirror  = qemu_pixman_mirror_create(ssd->ds->format,
219                                                  ssd->ds->image);
220     }
221
222 #ifndef CONFIG_MARU
223     for (blk = 0; blk < blocks; blk++) {
224         dirty_top[blk] = -1;
225     }
226
227     guest = surface_data(ssd->ds);
228     mirror = (void *)pixman_image_get_data(ssd->mirror);
229     for (y = ssd->dirty.top; y < ssd->dirty.bottom; y++) {
230         yoff1 = y * surface_stride(ssd->ds);
231         yoff2 = y * pixman_image_get_stride(ssd->mirror);
232         for (x = ssd->dirty.left; x < ssd->dirty.right; x += blksize) {
233             xoff = x * bpp;
234             blk = x / blksize;
235             bw = MIN(blksize, ssd->dirty.right - x);
236             if (memcmp(guest + yoff1 + xoff,
237                        mirror + yoff2 + xoff,
238                        bw * bpp) == 0) {
239                 if (dirty_top[blk] != -1) {
240                     QXLRect update = {
241                         .top    = dirty_top[blk],
242                         .bottom = y,
243                         .left   = x,
244                         .right  = x + bw,
245                     };
246                     qemu_spice_create_one_update(ssd, &update);
247                     dirty_top[blk] = -1;
248                 }
249             } else {
250                 if (dirty_top[blk] == -1) {
251                     dirty_top[blk] = y;
252                 }
253             }
254         }
255     }
256
257     for (x = ssd->dirty.left; x < ssd->dirty.right; x += blksize) {
258         blk = x / blksize;
259         bw = MIN(blksize, ssd->dirty.right - x);
260         if (dirty_top[blk] != -1) {
261             QXLRect update = {
262                 .top    = dirty_top[blk],
263                 .bottom = ssd->dirty.bottom,
264                 .left   = x,
265                 .right  = x + bw,
266             };
267             qemu_spice_create_one_update(ssd, &update);
268             dirty_top[blk] = -1;
269         }
270     }
271 #endif
272
273 #ifdef CONFIG_MARU
274     pixman_transform_t matrix;
275     struct pixman_f_transform matrix_f;
276
277     pixman_f_transform_init_identity(&matrix_f);
278     pixman_f_transform_scale(&matrix_f, NULL, RATIO_SCALE, RATIO_SCALE);
279     pixman_transform_from_pixman_f_transform(&matrix, &matrix_f);
280     pixman_image_set_transform(ssd->ds->image, &matrix);
281     pixman_image_set_filter(ssd->ds->image, PIXMAN_FILTER_BEST, NULL, 0);
282
283     QXLRect update = {
284         .top    = 0,
285         .bottom = surface_height(ssd->ds),
286         .left   = 0,
287         .right  = surface_width(ssd->ds),
288     };
289
290     qemu_spice_create_one_update(ssd, &update);
291 #endif
292
293     memset(&ssd->dirty, 0, sizeof(ssd->dirty));
294 }
295
296 static SimpleSpiceCursor*
297 qemu_spice_create_cursor_update(SimpleSpiceDisplay *ssd,
298                                 QEMUCursor *c,
299                                 int on)
300 {
301     size_t size = c ? c->width * c->height * 4 : 0;
302     SimpleSpiceCursor *update;
303     QXLCursorCmd *ccmd;
304     QXLCursor *cursor;
305     QXLCommand *cmd;
306
307     update   = g_malloc0(sizeof(*update) + size);
308     ccmd     = &update->cmd;
309     cursor   = &update->cursor;
310     cmd      = &update->ext.cmd;
311
312     if (c) {
313         ccmd->type = QXL_CURSOR_SET;
314         ccmd->u.set.position.x = ssd->ptr_x + ssd->hot_x;
315         ccmd->u.set.position.y = ssd->ptr_y + ssd->hot_y;
316         ccmd->u.set.visible    = true;
317         ccmd->u.set.shape      = (uintptr_t)cursor;
318         cursor->header.unique     = ssd->unique++;
319         cursor->header.type       = SPICE_CURSOR_TYPE_ALPHA;
320         cursor->header.width      = c->width;
321         cursor->header.height     = c->height;
322         cursor->header.hot_spot_x = c->hot_x;
323         cursor->header.hot_spot_y = c->hot_y;
324         cursor->data_size         = size;
325         cursor->chunk.data_size   = size;
326         memcpy(cursor->chunk.data, c->data, size);
327     } else if (!on) {
328         ccmd->type = QXL_CURSOR_HIDE;
329     } else {
330         ccmd->type = QXL_CURSOR_MOVE;
331         ccmd->u.position.x = ssd->ptr_x + ssd->hot_x;
332         ccmd->u.position.y = ssd->ptr_y + ssd->hot_y;
333     }
334     ccmd->release_info.id = (uintptr_t)(&update->ext);
335
336     cmd->type = QXL_CMD_CURSOR;
337     cmd->data = (uintptr_t)ccmd;
338
339     return update;
340 }
341
342 /*
343  * Called from spice server thread context (via interface_release_resource)
344  * We do *not* hold the global qemu mutex here, so extra care is needed
345  * when calling qemu functions.  QEMU interfaces used:
346  *    - g_free (underlying glibc free is re-entrant).
347  */
348 void qemu_spice_destroy_update(SimpleSpiceDisplay *sdpy, SimpleSpiceUpdate *update)
349 {
350     g_free(update->bitmap);
351     g_free(update);
352 }
353
354 void qemu_spice_create_host_memslot(SimpleSpiceDisplay *ssd)
355 {
356     QXLDevMemSlot memslot;
357
358     dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
359
360     memset(&memslot, 0, sizeof(memslot));
361     memslot.slot_group_id = MEMSLOT_GROUP_HOST;
362     memslot.virt_end = ~0;
363     qemu_spice_add_memslot(ssd, &memslot, QXL_SYNC);
364 }
365
366 void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)
367 {
368     QXLDevSurfaceCreate surface;
369     uint64_t surface_size;
370
371     memset(&surface, 0, sizeof(surface));
372
373     surface_size = (uint64_t) surface_width(ssd->ds) *
374         surface_height(ssd->ds) * 4;
375     assert(surface_size > 0);
376     assert(surface_size < INT_MAX);
377     if (ssd->bufsize < surface_size) {
378         ssd->bufsize = surface_size;
379         g_free(ssd->buf);
380         ssd->buf = g_malloc(ssd->bufsize);
381     }
382
383     dprint(1, "%s/%d: %ux%u (size %" PRIu64 "/%d)\n", __func__, ssd->qxl.id,
384            surface_width(ssd->ds), surface_height(ssd->ds),
385            surface_size, ssd->bufsize);
386
387     surface.format     = SPICE_SURFACE_FMT_32_xRGB;
388     surface.width      = surface_width(ssd->ds);
389     surface.height     = surface_height(ssd->ds);
390     surface.stride     = -surface.width * 4;
391     surface.mouse_mode = true;
392     surface.flags      = 0;
393     surface.type       = 0;
394     surface.mem        = (uintptr_t)ssd->buf;
395     surface.group_id   = MEMSLOT_GROUP_HOST;
396
397 #ifdef CONFIG_MARU
398     surface.width /= RATIO_SCALE;
399     surface.height /= RATIO_SCALE;
400 #endif
401
402     qemu_spice_create_primary_surface(ssd, 0, &surface, QXL_SYNC);
403 }
404
405 void qemu_spice_destroy_host_primary(SimpleSpiceDisplay *ssd)
406 {
407     dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
408
409     qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC);
410 }
411
412 void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd)
413 {
414     qemu_mutex_init(&ssd->lock);
415     QTAILQ_INIT(&ssd->updates);
416     ssd->mouse_x = -1;
417     ssd->mouse_y = -1;
418     if (ssd->num_surfaces == 0) {
419         ssd->num_surfaces = 1024;
420     }
421 }
422
423 /* display listener callbacks */
424
425 void qemu_spice_display_update(SimpleSpiceDisplay *ssd,
426                                int x, int y, int w, int h)
427 {
428     QXLRect update_area;
429
430     dprint(2, "%s/%d: x %d y %d w %d h %d\n", __func__,
431            ssd->qxl.id, x, y, w, h);
432     update_area.left = x,
433     update_area.right = x + w;
434     update_area.top = y;
435     update_area.bottom = y + h;
436
437     if (qemu_spice_rect_is_empty(&ssd->dirty)) {
438         ssd->notify++;
439     }
440     qemu_spice_rect_union(&ssd->dirty, &update_area);
441 }
442
443 void qemu_spice_display_switch(SimpleSpiceDisplay *ssd,
444                                DisplaySurface *surface)
445 {
446     SimpleSpiceUpdate *update;
447     bool need_destroy;
448
449     if (surface && ssd->surface &&
450         surface_width(surface) == pixman_image_get_width(ssd->surface) &&
451         surface_height(surface) == pixman_image_get_height(ssd->surface) &&
452         surface_format(surface) == pixman_image_get_format(ssd->surface)) {
453         /* no-resize fast path: just swap backing store */
454         dprint(1, "%s/%d: fast (%dx%d)\n", __func__, ssd->qxl.id,
455                surface_width(surface), surface_height(surface));
456         qemu_mutex_lock(&ssd->lock);
457         ssd->ds = surface;
458         pixman_image_unref(ssd->surface);
459         ssd->surface = pixman_image_ref(ssd->ds->image);
460         qemu_mutex_unlock(&ssd->lock);
461         qemu_spice_display_update(ssd, 0, 0,
462                                   surface_width(surface),
463                                   surface_height(surface));
464         return;
465     }
466
467     /* full mode switch */
468     dprint(1, "%s/%d: full (%dx%d -> %dx%d)\n", __func__, ssd->qxl.id,
469            ssd->surface ? pixman_image_get_width(ssd->surface)  : 0,
470            ssd->surface ? pixman_image_get_height(ssd->surface) : 0,
471            surface ? surface_width(surface)  : 0,
472            surface ? surface_height(surface) : 0);
473
474     memset(&ssd->dirty, 0, sizeof(ssd->dirty));
475     if (ssd->surface) {
476         pixman_image_unref(ssd->surface);
477         ssd->surface = NULL;
478         pixman_image_unref(ssd->mirror);
479         ssd->mirror = NULL;
480     }
481
482     qemu_mutex_lock(&ssd->lock);
483     need_destroy = (ssd->ds != NULL);
484     ssd->ds = surface;
485     while ((update = QTAILQ_FIRST(&ssd->updates)) != NULL) {
486         QTAILQ_REMOVE(&ssd->updates, update, next);
487         qemu_spice_destroy_update(ssd, update);
488     }
489     qemu_mutex_unlock(&ssd->lock);
490     if (need_destroy) {
491         qemu_spice_destroy_host_primary(ssd);
492     }
493     if (ssd->ds) {
494         ssd->surface = pixman_image_ref(ssd->ds->image);
495         ssd->mirror  = qemu_pixman_mirror_create(ssd->ds->format,
496                                                  ssd->ds->image);
497         qemu_spice_create_host_primary(ssd);
498     }
499
500     memset(&ssd->dirty, 0, sizeof(ssd->dirty));
501     ssd->notify++;
502
503     qemu_mutex_lock(&ssd->lock);
504     if (ssd->cursor) {
505         g_free(ssd->ptr_define);
506         ssd->ptr_define = qemu_spice_create_cursor_update(ssd, ssd->cursor, 0);
507     }
508     qemu_mutex_unlock(&ssd->lock);
509 }
510
511 static void qemu_spice_cursor_refresh_unlocked(SimpleSpiceDisplay *ssd)
512 {
513     if (ssd->cursor) {
514         assert(ssd->dcl.con);
515         dpy_cursor_define(ssd->dcl.con, ssd->cursor);
516     }
517     if (ssd->mouse_x != -1 && ssd->mouse_y != -1) {
518         assert(ssd->dcl.con);
519         dpy_mouse_set(ssd->dcl.con, ssd->mouse_x, ssd->mouse_y, 1);
520         ssd->mouse_x = -1;
521         ssd->mouse_y = -1;
522     }
523 }
524
525 void qemu_spice_cursor_refresh_bh(void *opaque)
526 {
527     SimpleSpiceDisplay *ssd = opaque;
528
529     qemu_mutex_lock(&ssd->lock);
530     qemu_spice_cursor_refresh_unlocked(ssd);
531     qemu_mutex_unlock(&ssd->lock);
532 }
533
534 void qemu_spice_display_refresh(SimpleSpiceDisplay *ssd)
535 {
536     dprint(3, "%s/%d:\n", __func__, ssd->qxl.id);
537     graphic_hw_update(ssd->dcl.con);
538
539     qemu_mutex_lock(&ssd->lock);
540     if (QTAILQ_EMPTY(&ssd->updates) && ssd->ds) {
541         qemu_spice_create_update(ssd);
542         ssd->notify++;
543     }
544     qemu_mutex_unlock(&ssd->lock);
545
546     if (ssd->notify) {
547         ssd->notify = 0;
548         qemu_spice_wakeup(ssd);
549         dprint(2, "%s/%d: notify\n", __func__, ssd->qxl.id);
550     }
551 }
552
553 /* spice display interface callbacks */
554
555 static void interface_attach_worker(QXLInstance *sin, QXLWorker *qxl_worker)
556 {
557     SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
558
559     dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
560     ssd->worker = qxl_worker;
561 }
562
563 static void interface_set_compression_level(QXLInstance *sin, int level)
564 {
565     dprint(1, "%s/%d:\n", __func__, sin->id);
566     /* nothing to do */
567 }
568
569 #if SPICE_NEEDS_SET_MM_TIME
570 static void interface_set_mm_time(QXLInstance *sin, uint32_t mm_time)
571 {
572     dprint(3, "%s/%d:\n", __func__, sin->id);
573     /* nothing to do */
574 }
575 #endif
576
577 static void interface_get_init_info(QXLInstance *sin, QXLDevInitInfo *info)
578 {
579     SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
580
581     info->memslot_gen_bits = MEMSLOT_GENERATION_BITS;
582     info->memslot_id_bits  = MEMSLOT_SLOT_BITS;
583     info->num_memslots = NUM_MEMSLOTS;
584     info->num_memslots_groups = NUM_MEMSLOTS_GROUPS;
585     info->internal_groupslot_id = 0;
586     info->qxl_ram_size = 16 * 1024 * 1024;
587     info->n_surfaces = ssd->num_surfaces;
588 }
589
590 static int interface_get_command(QXLInstance *sin, QXLCommandExt *ext)
591 {
592     SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
593     SimpleSpiceUpdate *update;
594     int ret = false;
595
596     dprint(3, "%s/%d:\n", __func__, ssd->qxl.id);
597
598     qemu_mutex_lock(&ssd->lock);
599     update = QTAILQ_FIRST(&ssd->updates);
600     if (update != NULL) {
601         QTAILQ_REMOVE(&ssd->updates, update, next);
602         *ext = update->ext;
603         ret = true;
604     }
605     qemu_mutex_unlock(&ssd->lock);
606
607     return ret;
608 }
609
610 static int interface_req_cmd_notification(QXLInstance *sin)
611 {
612     dprint(2, "%s/%d:\n", __func__, sin->id);
613     return 1;
614 }
615
616 static void interface_release_resource(QXLInstance *sin,
617                                        QXLReleaseInfoExt rext)
618 {
619     SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
620     SimpleSpiceUpdate *update;
621     SimpleSpiceCursor *cursor;
622     QXLCommandExt *ext;
623
624     dprint(2, "%s/%d:\n", __func__, ssd->qxl.id);
625     ext = (void *)(intptr_t)(rext.info->id);
626     switch (ext->cmd.type) {
627     case QXL_CMD_DRAW:
628         update = container_of(ext, SimpleSpiceUpdate, ext);
629         qemu_spice_destroy_update(ssd, update);
630         break;
631     case QXL_CMD_CURSOR:
632         cursor = container_of(ext, SimpleSpiceCursor, ext);
633         g_free(cursor);
634         break;
635     default:
636         g_assert_not_reached();
637     }
638 }
639
640 static int interface_get_cursor_command(QXLInstance *sin, QXLCommandExt *ext)
641 {
642     SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
643     int ret;
644
645     dprint(3, "%s/%d:\n", __func__, ssd->qxl.id);
646
647     qemu_mutex_lock(&ssd->lock);
648     if (ssd->ptr_define) {
649         *ext = ssd->ptr_define->ext;
650         ssd->ptr_define = NULL;
651         ret = true;
652     } else if (ssd->ptr_move) {
653         *ext = ssd->ptr_move->ext;
654         ssd->ptr_move = NULL;
655         ret = true;
656     } else {
657         ret = false;
658     }
659     qemu_mutex_unlock(&ssd->lock);
660     return ret;
661 }
662
663 static int interface_req_cursor_notification(QXLInstance *sin)
664 {
665     dprint(2, "%s:\n", __func__);
666     return 1;
667 }
668
669 static void interface_notify_update(QXLInstance *sin, uint32_t update_id)
670 {
671     fprintf(stderr, "%s: abort()\n", __FUNCTION__);
672     abort();
673 }
674
675 static int interface_flush_resources(QXLInstance *sin)
676 {
677     fprintf(stderr, "%s: abort()\n", __FUNCTION__);
678     abort();
679     return 0;
680 }
681
682 static void interface_update_area_complete(QXLInstance *sin,
683         uint32_t surface_id,
684         QXLRect *dirty, uint32_t num_updated_rects)
685 {
686     /* should never be called, used in qxl native mode only */
687     fprintf(stderr, "%s: abort()\n", __func__);
688     abort();
689 }
690
691 /* called from spice server thread context only */
692 static void interface_async_complete(QXLInstance *sin, uint64_t cookie_token)
693 {
694     QXLCookie *cookie = (QXLCookie *)(uintptr_t)cookie_token;
695
696     switch (cookie->type) {
697 #ifdef HAVE_SPICE_GL
698     case QXL_COOKIE_TYPE_GL_DRAW_DONE:
699     {
700         SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
701         qemu_bh_schedule(ssd->gl_unblock_bh);
702         break;
703     }
704     case QXL_COOKIE_TYPE_IO:
705         if (cookie->io == QXL_IO_MONITORS_CONFIG_ASYNC) {
706             g_free(cookie->u.data);
707         }
708         break;
709 #endif
710     default:
711         /* should never be called, used in qxl native mode only */
712         fprintf(stderr, "%s: abort()\n", __func__);
713         abort();
714     }
715     g_free(cookie);
716 }
717
718 static void interface_set_client_capabilities(QXLInstance *sin,
719                                               uint8_t client_present,
720                                               uint8_t caps[58])
721 {
722     dprint(3, "%s:\n", __func__);
723 }
724
725 static int interface_client_monitors_config(QXLInstance *sin,
726                                             VDAgentMonitorsConfig *mc)
727 {
728     SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
729     QemuUIInfo info;
730     int head;
731
732     if (!dpy_ui_info_supported(ssd->dcl.con)) {
733         return 0; /* == not supported by guest */
734     }
735
736     if (!mc) {
737         return 1;
738     }
739
740     memset(&info, 0, sizeof(info));
741
742     head = qemu_console_get_head(ssd->dcl.con);
743     if (mc->num_of_monitors > head) {
744         info.width  = mc->monitors[head].width;
745         info.height = mc->monitors[head].height;
746     }
747     dpy_set_ui_info(ssd->dcl.con, &info);
748     dprint(1, "%s/%d: size %dx%d\n", __func__, ssd->qxl.id,
749            info.width, info.height);
750     return 1;
751 }
752
753 static const QXLInterface dpy_interface = {
754     .base.type               = SPICE_INTERFACE_QXL,
755     .base.description        = "qemu simple display",
756     .base.major_version      = SPICE_INTERFACE_QXL_MAJOR,
757     .base.minor_version      = SPICE_INTERFACE_QXL_MINOR,
758
759     .attache_worker          = interface_attach_worker,
760     .set_compression_level   = interface_set_compression_level,
761 #if SPICE_NEEDS_SET_MM_TIME
762     .set_mm_time             = interface_set_mm_time,
763 #endif
764     .get_init_info           = interface_get_init_info,
765
766     /* the callbacks below are called from spice server thread context */
767     .get_command             = interface_get_command,
768     .req_cmd_notification    = interface_req_cmd_notification,
769     .release_resource        = interface_release_resource,
770     .get_cursor_command      = interface_get_cursor_command,
771     .req_cursor_notification = interface_req_cursor_notification,
772     .notify_update           = interface_notify_update,
773     .flush_resources         = interface_flush_resources,
774     .async_complete          = interface_async_complete,
775     .update_area_complete    = interface_update_area_complete,
776     .set_client_capabilities = interface_set_client_capabilities,
777     .client_monitors_config  = interface_client_monitors_config,
778 };
779
780 static void display_update(DisplayChangeListener *dcl,
781                            int x, int y, int w, int h)
782 {
783     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
784     qemu_spice_display_update(ssd, x, y, w, h);
785 }
786
787 static void display_switch(DisplayChangeListener *dcl,
788                            DisplaySurface *surface)
789 {
790     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
791     qemu_spice_display_switch(ssd, surface);
792 }
793
794 static void display_refresh(DisplayChangeListener *dcl)
795 {
796     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
797     qemu_spice_display_refresh(ssd);
798 }
799
800 static void display_mouse_set(DisplayChangeListener *dcl,
801                               int x, int y, int on)
802 {
803     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
804
805     qemu_mutex_lock(&ssd->lock);
806     ssd->ptr_x = x;
807     ssd->ptr_y = y;
808     g_free(ssd->ptr_move);
809     ssd->ptr_move = qemu_spice_create_cursor_update(ssd, NULL, on);
810     qemu_mutex_unlock(&ssd->lock);
811 }
812
813 static void display_mouse_define(DisplayChangeListener *dcl,
814                                  QEMUCursor *c)
815 {
816     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
817
818     qemu_mutex_lock(&ssd->lock);
819     cursor_get(c);
820     cursor_put(ssd->cursor);
821     ssd->cursor = c;
822     ssd->hot_x = c->hot_x;
823     ssd->hot_y = c->hot_y;
824     g_free(ssd->ptr_move);
825     ssd->ptr_move = NULL;
826     g_free(ssd->ptr_define);
827     ssd->ptr_define = qemu_spice_create_cursor_update(ssd, c, 0);
828     qemu_mutex_unlock(&ssd->lock);
829 }
830
831 static const DisplayChangeListenerOps display_listener_ops = {
832     .dpy_name             = "spice",
833     .dpy_gfx_update       = display_update,
834     .dpy_gfx_switch       = display_switch,
835     .dpy_gfx_check_format = qemu_pixman_check_format,
836     .dpy_refresh          = display_refresh,
837     .dpy_mouse_set        = display_mouse_set,
838     .dpy_cursor_define    = display_mouse_define,
839 };
840
841 #ifdef HAVE_SPICE_GL
842
843 static void qemu_spice_gl_monitor_config(SimpleSpiceDisplay *ssd,
844                                          int x, int y, int w, int h)
845 {
846     QXLMonitorsConfig *config;
847     QXLCookie *cookie;
848
849     config = g_malloc0(sizeof(QXLMonitorsConfig) + sizeof(QXLHead));
850     config->count = 1;
851     config->max_allowed = 1;
852     config->heads[0].x = x;
853     config->heads[0].y = y;
854     config->heads[0].width = w;
855     config->heads[0].height = h;
856     cookie = qxl_cookie_new(QXL_COOKIE_TYPE_IO,
857                             QXL_IO_MONITORS_CONFIG_ASYNC);
858     cookie->u.data = config;
859
860     spice_qxl_monitors_config_async(&ssd->qxl,
861                                     (uintptr_t)config,
862                                     MEMSLOT_GROUP_HOST,
863                                     (uintptr_t)cookie);
864 }
865
866 static void qemu_spice_gl_block(SimpleSpiceDisplay *ssd, bool block)
867 {
868     uint64_t timeout;
869
870     if (block) {
871         timeout = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
872         timeout += 1000; /* one sec */
873         timer_mod(ssd->gl_unblock_timer, timeout);
874     } else {
875         timer_del(ssd->gl_unblock_timer);
876     }
877     graphic_hw_gl_block(ssd->dcl.con, block);
878 }
879
880 static void qemu_spice_gl_unblock_bh(void *opaque)
881 {
882     SimpleSpiceDisplay *ssd = opaque;
883
884     qemu_spice_gl_block(ssd, false);
885 }
886
887 static void qemu_spice_gl_block_timer(void *opaque)
888 {
889     fprintf(stderr, "WARNING: spice: no gl-draw-done within one second\n");
890 }
891
892 static void spice_gl_refresh(DisplayChangeListener *dcl)
893 {
894     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
895     uint64_t cookie;
896
897     if (!ssd->ds || qemu_console_is_gl_blocked(ssd->dcl.con)) {
898         return;
899     }
900
901     graphic_hw_update(dcl->con);
902     if (ssd->gl_updates && ssd->have_surface) {
903         qemu_spice_gl_block(ssd, true);
904         cookie = (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_GL_DRAW_DONE, 0);
905         spice_qxl_gl_draw_async(&ssd->qxl, 0, 0,
906                                 surface_width(ssd->ds),
907                                 surface_height(ssd->ds),
908                                 cookie);
909         ssd->gl_updates = 0;
910     }
911 }
912
913 static void spice_gl_update(DisplayChangeListener *dcl,
914                             int x, int y, int w, int h)
915 {
916     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
917
918     surface_gl_update_texture(ssd->gls, ssd->ds, x, y, w, h);
919     ssd->gl_updates++;
920 }
921
922 static void spice_gl_switch(DisplayChangeListener *dcl,
923                             struct DisplaySurface *new_surface)
924 {
925     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
926     EGLint stride, fourcc;
927     int fd;
928
929     if (ssd->ds) {
930         surface_gl_destroy_texture(ssd->gls, ssd->ds);
931     }
932     ssd->ds = new_surface;
933     if (ssd->ds) {
934         surface_gl_create_texture(ssd->gls, ssd->ds);
935         fd = egl_get_fd_for_texture(ssd->ds->texture,
936                                     &stride, &fourcc);
937         if (fd < 0) {
938             surface_gl_destroy_texture(ssd->gls, ssd->ds);
939             return;
940         }
941
942         dprint(1, "%s: %dx%d (stride %d/%d, fourcc 0x%x)\n", __func__,
943                surface_width(ssd->ds), surface_height(ssd->ds),
944                surface_stride(ssd->ds), stride, fourcc);
945
946         /* note: spice server will close the fd */
947         spice_qxl_gl_scanout(&ssd->qxl, fd,
948                              surface_width(ssd->ds),
949                              surface_height(ssd->ds),
950                              stride, fourcc, false);
951         ssd->have_surface = true;
952         ssd->have_scanout = false;
953
954         qemu_spice_gl_monitor_config(ssd, 0, 0,
955                                      surface_width(ssd->ds),
956                                      surface_height(ssd->ds));
957     }
958 }
959
960 static QEMUGLContext qemu_spice_gl_create_context(DisplayChangeListener *dcl,
961                                                   QEMUGLParams *params)
962 {
963     eglMakeCurrent(qemu_egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
964                    qemu_egl_rn_ctx);
965     return qemu_egl_create_context(dcl, params);
966 }
967
968 static void qemu_spice_gl_scanout(DisplayChangeListener *dcl,
969                                   uint32_t tex_id,
970                                   bool y_0_top,
971                                   uint32_t backing_width,
972                                   uint32_t backing_height,
973                                   uint32_t x, uint32_t y,
974                                   uint32_t w, uint32_t h)
975 {
976     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
977     EGLint stride = 0, fourcc = 0;
978     int fd = -1;
979
980     if (tex_id) {
981         fd = egl_get_fd_for_texture(tex_id, &stride, &fourcc);
982         if (fd < 0) {
983             fprintf(stderr, "%s: failed to get fd for texture\n", __func__);
984             return;
985         }
986         dprint(1, "%s: %dx%d (stride %d, fourcc 0x%x)\n", __func__,
987                w, h, stride, fourcc);
988     } else {
989         dprint(1, "%s: no texture (no framebuffer)\n", __func__);
990     }
991
992     assert(!tex_id || fd >= 0);
993
994     /* note: spice server will close the fd */
995     spice_qxl_gl_scanout(&ssd->qxl, fd, backing_width, backing_height,
996                          stride, fourcc, y_0_top);
997     ssd->have_surface = false;
998     ssd->have_scanout = (tex_id != 0);
999
1000     qemu_spice_gl_monitor_config(ssd, x, y, w, h);
1001 }
1002
1003 static void qemu_spice_gl_update(DisplayChangeListener *dcl,
1004                                  uint32_t x, uint32_t y, uint32_t w, uint32_t h)
1005 {
1006     SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);
1007     uint64_t cookie;
1008
1009     if (!ssd->have_scanout) {
1010         return;
1011     }
1012
1013     dprint(2, "%s: %dx%d+%d+%d\n", __func__, w, h, x, y);
1014     qemu_spice_gl_block(ssd, true);
1015     cookie = (uintptr_t)qxl_cookie_new(QXL_COOKIE_TYPE_GL_DRAW_DONE, 0);
1016     spice_qxl_gl_draw_async(&ssd->qxl, x, y, w, h, cookie);
1017 }
1018
1019 static const DisplayChangeListenerOps display_listener_gl_ops = {
1020     .dpy_name                = "spice-egl",
1021     .dpy_gfx_update          = spice_gl_update,
1022     .dpy_gfx_switch          = spice_gl_switch,
1023     .dpy_gfx_check_format    = console_gl_check_format,
1024     .dpy_refresh             = spice_gl_refresh,
1025     .dpy_mouse_set           = display_mouse_set,
1026     .dpy_cursor_define       = display_mouse_define,
1027
1028     .dpy_gl_ctx_create       = qemu_spice_gl_create_context,
1029     .dpy_gl_ctx_destroy      = qemu_egl_destroy_context,
1030     .dpy_gl_ctx_make_current = qemu_egl_make_context_current,
1031     .dpy_gl_ctx_get_current  = qemu_egl_get_current_context,
1032
1033     .dpy_gl_scanout          = qemu_spice_gl_scanout,
1034     .dpy_gl_update           = qemu_spice_gl_update,
1035 };
1036
1037 #endif /* HAVE_SPICE_GL */
1038
1039 static void qemu_spice_display_init_one(QemuConsole *con)
1040 {
1041     SimpleSpiceDisplay *ssd = g_new0(SimpleSpiceDisplay, 1);
1042
1043     qemu_spice_display_init_common(ssd);
1044
1045     ssd->dcl.ops = &display_listener_ops;
1046 #ifdef HAVE_SPICE_GL
1047     if (display_opengl) {
1048         ssd->dcl.ops = &display_listener_gl_ops;
1049         ssd->gl_unblock_bh = qemu_bh_new(qemu_spice_gl_unblock_bh, ssd);
1050         ssd->gl_unblock_timer = timer_new_ms(QEMU_CLOCK_REALTIME,
1051                                              qemu_spice_gl_block_timer, ssd);
1052         ssd->gls = console_gl_init_context();
1053         ssd->have_surface = false;
1054         ssd->have_scanout = false;
1055     }
1056 #endif
1057     ssd->dcl.con = con;
1058
1059     ssd->qxl.base.sif = &dpy_interface.base;
1060     qemu_spice_add_display_interface(&ssd->qxl, con);
1061     assert(ssd->worker);
1062     qemu_spice_create_host_memslot(ssd);
1063
1064     register_displaychangelistener(&ssd->dcl);
1065 }
1066
1067 void qemu_spice_display_init(void)
1068 {
1069     QemuConsole *con;
1070     int i;
1071
1072     for (i = 0;; i++) {
1073         con = qemu_console_lookup_by_index(i);
1074         if (!con || !qemu_console_is_graphic(con)) {
1075             break;
1076         }
1077         if (qemu_spice_have_display_interface(con)) {
1078             continue;
1079         }
1080         qemu_spice_display_init_one(con);
1081     }
1082 }