xref: /qemu/hw/display/virtio-gpu.c (revision c8a7fc51)
1 /*
2  * Virtio GPU Device
3  *
4  * Copyright Red Hat, Inc. 2013-2014
5  *
6  * Authors:
7  *     Dave Airlie <airlied@redhat.com>
8  *     Gerd Hoffmann <kraxel@redhat.com>
9  *
10  * This work is licensed under the terms of the GNU GPL, version 2 or later.
11  * See the COPYING file in the top-level directory.
12  */
13 
14 #include "qemu/osdep.h"
15 #include "qemu/units.h"
16 #include "qemu/iov.h"
17 #include "sysemu/cpus.h"
18 #include "ui/console.h"
19 #include "trace.h"
20 #include "sysemu/dma.h"
21 #include "sysemu/sysemu.h"
22 #include "hw/virtio/virtio.h"
23 #include "migration/qemu-file-types.h"
24 #include "hw/virtio/virtio-gpu.h"
25 #include "hw/virtio/virtio-gpu-bswap.h"
26 #include "hw/virtio/virtio-gpu-pixman.h"
27 #include "hw/virtio/virtio-bus.h"
28 #include "hw/qdev-properties.h"
29 #include "qemu/log.h"
30 #include "qemu/module.h"
31 #include "qapi/error.h"
32 #include "qemu/error-report.h"
33 
34 #define VIRTIO_GPU_VM_VERSION 1
35 
36 static struct virtio_gpu_simple_resource *
37 virtio_gpu_find_check_resource(VirtIOGPU *g, uint32_t resource_id,
38                                bool require_backing,
39                                const char *caller, uint32_t *error);
40 
41 static void virtio_gpu_reset_bh(void *opaque);
42 
43 void virtio_gpu_update_cursor_data(VirtIOGPU *g,
44                                    struct virtio_gpu_scanout *s,
45                                    uint32_t resource_id)
46 {
47     struct virtio_gpu_simple_resource *res;
48     uint32_t pixels;
49     void *data;
50 
51     res = virtio_gpu_find_check_resource(g, resource_id, false,
52                                          __func__, NULL);
53     if (!res) {
54         return;
55     }
56 
57     if (res->blob_size) {
58         if (res->blob_size < (s->current_cursor->width *
59                               s->current_cursor->height * 4)) {
60             return;
61         }
62         data = res->blob;
63     } else {
64         if (pixman_image_get_width(res->image)  != s->current_cursor->width ||
65             pixman_image_get_height(res->image) != s->current_cursor->height) {
66             return;
67         }
68         data = pixman_image_get_data(res->image);
69     }
70 
71     pixels = s->current_cursor->width * s->current_cursor->height;
72     memcpy(s->current_cursor->data, data,
73            pixels * sizeof(uint32_t));
74 }
75 
76 static void update_cursor(VirtIOGPU *g, struct virtio_gpu_update_cursor *cursor)
77 {
78     struct virtio_gpu_scanout *s;
79     VirtIOGPUClass *vgc = VIRTIO_GPU_GET_CLASS(g);
80     bool move = cursor->hdr.type == VIRTIO_GPU_CMD_MOVE_CURSOR;
81 
82     if (cursor->pos.scanout_id >= g->parent_obj.conf.max_outputs) {
83         return;
84     }
85     s = &g->parent_obj.scanout[cursor->pos.scanout_id];
86 
87     trace_virtio_gpu_update_cursor(cursor->pos.scanout_id,
88                                    cursor->pos.x,
89                                    cursor->pos.y,
90                                    move ? "move" : "update",
91                                    cursor->resource_id);
92 
93     if (!move) {
94         if (!s->current_cursor) {
95             s->current_cursor = cursor_alloc(64, 64);
96         }
97 
98         s->current_cursor->hot_x = cursor->hot_x;
99         s->current_cursor->hot_y = cursor->hot_y;
100 
101         if (cursor->resource_id > 0) {
102             vgc->update_cursor_data(g, s, cursor->resource_id);
103         }
104         dpy_cursor_define(s->con, s->current_cursor);
105 
106         s->cursor = *cursor;
107     } else {
108         s->cursor.pos.x = cursor->pos.x;
109         s->cursor.pos.y = cursor->pos.y;
110     }
111     dpy_mouse_set(s->con, cursor->pos.x, cursor->pos.y,
112                   cursor->resource_id ? 1 : 0);
113 }
114 
115 struct virtio_gpu_simple_resource *
116 virtio_gpu_find_resource(VirtIOGPU *g, uint32_t resource_id)
117 {
118     struct virtio_gpu_simple_resource *res;
119 
120     QTAILQ_FOREACH(res, &g->reslist, next) {
121         if (res->resource_id == resource_id) {
122             return res;
123         }
124     }
125     return NULL;
126 }
127 
128 static struct virtio_gpu_simple_resource *
129 virtio_gpu_find_check_resource(VirtIOGPU *g, uint32_t resource_id,
130                                bool require_backing,
131                                const char *caller, uint32_t *error)
132 {
133     struct virtio_gpu_simple_resource *res;
134 
135     res = virtio_gpu_find_resource(g, resource_id);
136     if (!res) {
137         qemu_log_mask(LOG_GUEST_ERROR, "%s: invalid resource specified %d\n",
138                       caller, resource_id);
139         if (error) {
140             *error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
141         }
142         return NULL;
143     }
144 
145     if (require_backing) {
146         if (!res->iov || (!res->image && !res->blob)) {
147             qemu_log_mask(LOG_GUEST_ERROR, "%s: no backing storage %d\n",
148                           caller, resource_id);
149             if (error) {
150                 *error = VIRTIO_GPU_RESP_ERR_UNSPEC;
151             }
152             return NULL;
153         }
154     }
155 
156     return res;
157 }
158 
159 void virtio_gpu_ctrl_response(VirtIOGPU *g,
160                               struct virtio_gpu_ctrl_command *cmd,
161                               struct virtio_gpu_ctrl_hdr *resp,
162                               size_t resp_len)
163 {
164     size_t s;
165 
166     if (cmd->cmd_hdr.flags & VIRTIO_GPU_FLAG_FENCE) {
167         resp->flags |= VIRTIO_GPU_FLAG_FENCE;
168         resp->fence_id = cmd->cmd_hdr.fence_id;
169         resp->ctx_id = cmd->cmd_hdr.ctx_id;
170     }
171     virtio_gpu_ctrl_hdr_bswap(resp);
172     s = iov_from_buf(cmd->elem.in_sg, cmd->elem.in_num, 0, resp, resp_len);
173     if (s != resp_len) {
174         qemu_log_mask(LOG_GUEST_ERROR,
175                       "%s: response size incorrect %zu vs %zu\n",
176                       __func__, s, resp_len);
177     }
178     virtqueue_push(cmd->vq, &cmd->elem, s);
179     virtio_notify(VIRTIO_DEVICE(g), cmd->vq);
180     cmd->finished = true;
181 }
182 
183 void virtio_gpu_ctrl_response_nodata(VirtIOGPU *g,
184                                      struct virtio_gpu_ctrl_command *cmd,
185                                      enum virtio_gpu_ctrl_type type)
186 {
187     struct virtio_gpu_ctrl_hdr resp;
188 
189     memset(&resp, 0, sizeof(resp));
190     resp.type = type;
191     virtio_gpu_ctrl_response(g, cmd, &resp, sizeof(resp));
192 }
193 
194 void virtio_gpu_get_display_info(VirtIOGPU *g,
195                                  struct virtio_gpu_ctrl_command *cmd)
196 {
197     struct virtio_gpu_resp_display_info display_info;
198 
199     trace_virtio_gpu_cmd_get_display_info();
200     memset(&display_info, 0, sizeof(display_info));
201     display_info.hdr.type = VIRTIO_GPU_RESP_OK_DISPLAY_INFO;
202     virtio_gpu_base_fill_display_info(VIRTIO_GPU_BASE(g), &display_info);
203     virtio_gpu_ctrl_response(g, cmd, &display_info.hdr,
204                              sizeof(display_info));
205 }
206 
207 void virtio_gpu_get_edid(VirtIOGPU *g,
208                          struct virtio_gpu_ctrl_command *cmd)
209 {
210     struct virtio_gpu_resp_edid edid;
211     struct virtio_gpu_cmd_get_edid get_edid;
212     VirtIOGPUBase *b = VIRTIO_GPU_BASE(g);
213 
214     VIRTIO_GPU_FILL_CMD(get_edid);
215     virtio_gpu_bswap_32(&get_edid, sizeof(get_edid));
216 
217     if (get_edid.scanout >= b->conf.max_outputs) {
218         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
219         return;
220     }
221 
222     trace_virtio_gpu_cmd_get_edid(get_edid.scanout);
223     memset(&edid, 0, sizeof(edid));
224     edid.hdr.type = VIRTIO_GPU_RESP_OK_EDID;
225     virtio_gpu_base_generate_edid(VIRTIO_GPU_BASE(g), get_edid.scanout, &edid);
226     virtio_gpu_ctrl_response(g, cmd, &edid.hdr, sizeof(edid));
227 }
228 
229 static uint32_t calc_image_hostmem(pixman_format_code_t pformat,
230                                    uint32_t width, uint32_t height)
231 {
232     /* Copied from pixman/pixman-bits-image.c, skip integer overflow check.
233      * pixman_image_create_bits will fail in case it overflow.
234      */
235 
236     int bpp = PIXMAN_FORMAT_BPP(pformat);
237     int stride = ((width * bpp + 0x1f) >> 5) * sizeof(uint32_t);
238     return height * stride;
239 }
240 
241 #ifdef WIN32
242 static void
243 win32_pixman_image_destroy(pixman_image_t *image, void *data)
244 {
245     HANDLE handle = data;
246 
247     qemu_win32_map_free(pixman_image_get_data(image), handle, &error_warn);
248 }
249 #endif
250 
251 static void virtio_gpu_resource_create_2d(VirtIOGPU *g,
252                                           struct virtio_gpu_ctrl_command *cmd)
253 {
254     pixman_format_code_t pformat;
255     struct virtio_gpu_simple_resource *res;
256     struct virtio_gpu_resource_create_2d c2d;
257 
258     VIRTIO_GPU_FILL_CMD(c2d);
259     virtio_gpu_bswap_32(&c2d, sizeof(c2d));
260     trace_virtio_gpu_cmd_res_create_2d(c2d.resource_id, c2d.format,
261                                        c2d.width, c2d.height);
262 
263     if (c2d.resource_id == 0) {
264         qemu_log_mask(LOG_GUEST_ERROR, "%s: resource id 0 is not allowed\n",
265                       __func__);
266         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
267         return;
268     }
269 
270     res = virtio_gpu_find_resource(g, c2d.resource_id);
271     if (res) {
272         qemu_log_mask(LOG_GUEST_ERROR, "%s: resource already exists %d\n",
273                       __func__, c2d.resource_id);
274         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
275         return;
276     }
277 
278     res = g_new0(struct virtio_gpu_simple_resource, 1);
279 
280     res->width = c2d.width;
281     res->height = c2d.height;
282     res->format = c2d.format;
283     res->resource_id = c2d.resource_id;
284 
285     pformat = virtio_gpu_get_pixman_format(c2d.format);
286     if (!pformat) {
287         qemu_log_mask(LOG_GUEST_ERROR,
288                       "%s: host couldn't handle guest format %d\n",
289                       __func__, c2d.format);
290         g_free(res);
291         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
292         return;
293     }
294 
295     res->hostmem = calc_image_hostmem(pformat, c2d.width, c2d.height);
296     if (res->hostmem + g->hostmem < g->conf_max_hostmem) {
297         void *bits = NULL;
298 #ifdef WIN32
299         bits = qemu_win32_map_alloc(res->hostmem, &res->handle, &error_warn);
300         if (!bits) {
301             goto end;
302         }
303 #endif
304         res->image = pixman_image_create_bits(
305             pformat,
306             c2d.width,
307             c2d.height,
308             bits, c2d.height ? res->hostmem / c2d.height : 0);
309 #ifdef WIN32
310         if (res->image) {
311             pixman_image_set_destroy_function(res->image, win32_pixman_image_destroy, res->handle);
312         }
313 #endif
314     }
315 
316 #ifdef WIN32
317 end:
318 #endif
319     if (!res->image) {
320         qemu_log_mask(LOG_GUEST_ERROR,
321                       "%s: resource creation failed %d %d %d\n",
322                       __func__, c2d.resource_id, c2d.width, c2d.height);
323         g_free(res);
324         cmd->error = VIRTIO_GPU_RESP_ERR_OUT_OF_MEMORY;
325         return;
326     }
327 
328     QTAILQ_INSERT_HEAD(&g->reslist, res, next);
329     g->hostmem += res->hostmem;
330 }
331 
332 static void virtio_gpu_resource_create_blob(VirtIOGPU *g,
333                                             struct virtio_gpu_ctrl_command *cmd)
334 {
335     struct virtio_gpu_simple_resource *res;
336     struct virtio_gpu_resource_create_blob cblob;
337     int ret;
338 
339     VIRTIO_GPU_FILL_CMD(cblob);
340     virtio_gpu_create_blob_bswap(&cblob);
341     trace_virtio_gpu_cmd_res_create_blob(cblob.resource_id, cblob.size);
342 
343     if (cblob.resource_id == 0) {
344         qemu_log_mask(LOG_GUEST_ERROR, "%s: resource id 0 is not allowed\n",
345                       __func__);
346         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
347         return;
348     }
349 
350     if (cblob.blob_mem != VIRTIO_GPU_BLOB_MEM_GUEST &&
351         cblob.blob_flags != VIRTIO_GPU_BLOB_FLAG_USE_SHAREABLE) {
352         qemu_log_mask(LOG_GUEST_ERROR, "%s: invalid memory type\n",
353                       __func__);
354         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
355         return;
356     }
357 
358     if (virtio_gpu_find_resource(g, cblob.resource_id)) {
359         qemu_log_mask(LOG_GUEST_ERROR, "%s: resource already exists %d\n",
360                       __func__, cblob.resource_id);
361         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
362         return;
363     }
364 
365     res = g_new0(struct virtio_gpu_simple_resource, 1);
366     res->resource_id = cblob.resource_id;
367     res->blob_size = cblob.size;
368 
369     ret = virtio_gpu_create_mapping_iov(g, cblob.nr_entries, sizeof(cblob),
370                                         cmd, &res->addrs, &res->iov,
371                                         &res->iov_cnt);
372     if (ret != 0) {
373         cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
374         g_free(res);
375         return;
376     }
377 
378     virtio_gpu_init_udmabuf(res);
379     QTAILQ_INSERT_HEAD(&g->reslist, res, next);
380 }
381 
382 static void virtio_gpu_disable_scanout(VirtIOGPU *g, int scanout_id)
383 {
384     struct virtio_gpu_scanout *scanout = &g->parent_obj.scanout[scanout_id];
385     struct virtio_gpu_simple_resource *res;
386 
387     if (scanout->resource_id == 0) {
388         return;
389     }
390 
391     res = virtio_gpu_find_resource(g, scanout->resource_id);
392     if (res) {
393         res->scanout_bitmask &= ~(1 << scanout_id);
394     }
395 
396     dpy_gfx_replace_surface(scanout->con, NULL);
397     scanout->resource_id = 0;
398     scanout->ds = NULL;
399     scanout->width = 0;
400     scanout->height = 0;
401 }
402 
403 static void virtio_gpu_resource_destroy(VirtIOGPU *g,
404                                         struct virtio_gpu_simple_resource *res)
405 {
406     int i;
407 
408     if (res->scanout_bitmask) {
409         for (i = 0; i < g->parent_obj.conf.max_outputs; i++) {
410             if (res->scanout_bitmask & (1 << i)) {
411                 virtio_gpu_disable_scanout(g, i);
412             }
413         }
414     }
415 
416     qemu_pixman_image_unref(res->image);
417     virtio_gpu_cleanup_mapping(g, res);
418     QTAILQ_REMOVE(&g->reslist, res, next);
419     g->hostmem -= res->hostmem;
420     g_free(res);
421 }
422 
423 static void virtio_gpu_resource_unref(VirtIOGPU *g,
424                                       struct virtio_gpu_ctrl_command *cmd)
425 {
426     struct virtio_gpu_simple_resource *res;
427     struct virtio_gpu_resource_unref unref;
428 
429     VIRTIO_GPU_FILL_CMD(unref);
430     virtio_gpu_bswap_32(&unref, sizeof(unref));
431     trace_virtio_gpu_cmd_res_unref(unref.resource_id);
432 
433     res = virtio_gpu_find_resource(g, unref.resource_id);
434     if (!res) {
435         qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
436                       __func__, unref.resource_id);
437         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
438         return;
439     }
440     virtio_gpu_resource_destroy(g, res);
441 }
442 
443 static void virtio_gpu_transfer_to_host_2d(VirtIOGPU *g,
444                                            struct virtio_gpu_ctrl_command *cmd)
445 {
446     struct virtio_gpu_simple_resource *res;
447     int h, bpp;
448     uint32_t src_offset, dst_offset, stride;
449     pixman_format_code_t format;
450     struct virtio_gpu_transfer_to_host_2d t2d;
451     void *img_data;
452 
453     VIRTIO_GPU_FILL_CMD(t2d);
454     virtio_gpu_t2d_bswap(&t2d);
455     trace_virtio_gpu_cmd_res_xfer_toh_2d(t2d.resource_id);
456 
457     res = virtio_gpu_find_check_resource(g, t2d.resource_id, true,
458                                          __func__, &cmd->error);
459     if (!res || res->blob) {
460         return;
461     }
462 
463     if (t2d.r.x > res->width ||
464         t2d.r.y > res->height ||
465         t2d.r.width > res->width ||
466         t2d.r.height > res->height ||
467         t2d.r.x + t2d.r.width > res->width ||
468         t2d.r.y + t2d.r.height > res->height) {
469         qemu_log_mask(LOG_GUEST_ERROR, "%s: transfer bounds outside resource"
470                       " bounds for resource %d: %d %d %d %d vs %d %d\n",
471                       __func__, t2d.resource_id, t2d.r.x, t2d.r.y,
472                       t2d.r.width, t2d.r.height, res->width, res->height);
473         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
474         return;
475     }
476 
477     format = pixman_image_get_format(res->image);
478     bpp = DIV_ROUND_UP(PIXMAN_FORMAT_BPP(format), 8);
479     stride = pixman_image_get_stride(res->image);
480     img_data = pixman_image_get_data(res->image);
481 
482     if (t2d.r.x || t2d.r.width != pixman_image_get_width(res->image)) {
483         for (h = 0; h < t2d.r.height; h++) {
484             src_offset = t2d.offset + stride * h;
485             dst_offset = (t2d.r.y + h) * stride + (t2d.r.x * bpp);
486 
487             iov_to_buf(res->iov, res->iov_cnt, src_offset,
488                        (uint8_t *)img_data + dst_offset,
489                        t2d.r.width * bpp);
490         }
491     } else {
492         src_offset = t2d.offset;
493         dst_offset = t2d.r.y * stride + t2d.r.x * bpp;
494         iov_to_buf(res->iov, res->iov_cnt, src_offset,
495                    (uint8_t *)img_data + dst_offset,
496                    stride * t2d.r.height);
497     }
498 }
499 
500 static void virtio_gpu_resource_flush(VirtIOGPU *g,
501                                       struct virtio_gpu_ctrl_command *cmd)
502 {
503     struct virtio_gpu_simple_resource *res;
504     struct virtio_gpu_resource_flush rf;
505     struct virtio_gpu_scanout *scanout;
506     pixman_region16_t flush_region;
507     bool within_bounds = false;
508     bool update_submitted = false;
509     int i;
510 
511     VIRTIO_GPU_FILL_CMD(rf);
512     virtio_gpu_bswap_32(&rf, sizeof(rf));
513     trace_virtio_gpu_cmd_res_flush(rf.resource_id,
514                                    rf.r.width, rf.r.height, rf.r.x, rf.r.y);
515 
516     res = virtio_gpu_find_check_resource(g, rf.resource_id, false,
517                                          __func__, &cmd->error);
518     if (!res) {
519         return;
520     }
521 
522     if (res->blob) {
523         for (i = 0; i < g->parent_obj.conf.max_outputs; i++) {
524             scanout = &g->parent_obj.scanout[i];
525             if (scanout->resource_id == res->resource_id &&
526                 rf.r.x < scanout->x + scanout->width &&
527                 rf.r.x + rf.r.width >= scanout->x &&
528                 rf.r.y < scanout->y + scanout->height &&
529                 rf.r.y + rf.r.height >= scanout->y) {
530                 within_bounds = true;
531 
532                 if (console_has_gl(scanout->con)) {
533                     dpy_gl_update(scanout->con, 0, 0, scanout->width,
534                                   scanout->height);
535                     update_submitted = true;
536                 }
537             }
538         }
539 
540         if (update_submitted) {
541             return;
542         }
543         if (!within_bounds) {
544             qemu_log_mask(LOG_GUEST_ERROR, "%s: flush bounds outside scanouts"
545                           " bounds for flush %d: %d %d %d %d\n",
546                           __func__, rf.resource_id, rf.r.x, rf.r.y,
547                           rf.r.width, rf.r.height);
548             cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
549             return;
550         }
551     }
552 
553     if (!res->blob &&
554         (rf.r.x > res->width ||
555         rf.r.y > res->height ||
556         rf.r.width > res->width ||
557         rf.r.height > res->height ||
558         rf.r.x + rf.r.width > res->width ||
559         rf.r.y + rf.r.height > res->height)) {
560         qemu_log_mask(LOG_GUEST_ERROR, "%s: flush bounds outside resource"
561                       " bounds for resource %d: %d %d %d %d vs %d %d\n",
562                       __func__, rf.resource_id, rf.r.x, rf.r.y,
563                       rf.r.width, rf.r.height, res->width, res->height);
564         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
565         return;
566     }
567 
568     pixman_region_init_rect(&flush_region,
569                             rf.r.x, rf.r.y, rf.r.width, rf.r.height);
570     for (i = 0; i < g->parent_obj.conf.max_outputs; i++) {
571         pixman_region16_t region, finalregion;
572         pixman_box16_t *extents;
573 
574         if (!(res->scanout_bitmask & (1 << i))) {
575             continue;
576         }
577         scanout = &g->parent_obj.scanout[i];
578 
579         pixman_region_init(&finalregion);
580         pixman_region_init_rect(&region, scanout->x, scanout->y,
581                                 scanout->width, scanout->height);
582 
583         pixman_region_intersect(&finalregion, &flush_region, &region);
584         pixman_region_translate(&finalregion, -scanout->x, -scanout->y);
585         extents = pixman_region_extents(&finalregion);
586         /* work out the area we need to update for each console */
587         dpy_gfx_update(g->parent_obj.scanout[i].con,
588                        extents->x1, extents->y1,
589                        extents->x2 - extents->x1,
590                        extents->y2 - extents->y1);
591 
592         pixman_region_fini(&region);
593         pixman_region_fini(&finalregion);
594     }
595     pixman_region_fini(&flush_region);
596 }
597 
598 static void virtio_unref_resource(pixman_image_t *image, void *data)
599 {
600     pixman_image_unref(data);
601 }
602 
603 static void virtio_gpu_update_scanout(VirtIOGPU *g,
604                                       uint32_t scanout_id,
605                                       struct virtio_gpu_simple_resource *res,
606                                       struct virtio_gpu_rect *r)
607 {
608     struct virtio_gpu_simple_resource *ores;
609     struct virtio_gpu_scanout *scanout;
610 
611     scanout = &g->parent_obj.scanout[scanout_id];
612     ores = virtio_gpu_find_resource(g, scanout->resource_id);
613     if (ores) {
614         ores->scanout_bitmask &= ~(1 << scanout_id);
615     }
616 
617     res->scanout_bitmask |= (1 << scanout_id);
618     scanout->resource_id = res->resource_id;
619     scanout->x = r->x;
620     scanout->y = r->y;
621     scanout->width = r->width;
622     scanout->height = r->height;
623 }
624 
625 static void virtio_gpu_do_set_scanout(VirtIOGPU *g,
626                                       uint32_t scanout_id,
627                                       struct virtio_gpu_framebuffer *fb,
628                                       struct virtio_gpu_simple_resource *res,
629                                       struct virtio_gpu_rect *r,
630                                       uint32_t *error)
631 {
632     struct virtio_gpu_scanout *scanout;
633     uint8_t *data;
634 
635     scanout = &g->parent_obj.scanout[scanout_id];
636 
637     if (r->x > fb->width ||
638         r->y > fb->height ||
639         r->width < 16 ||
640         r->height < 16 ||
641         r->width > fb->width ||
642         r->height > fb->height ||
643         r->x + r->width > fb->width ||
644         r->y + r->height > fb->height) {
645         qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for"
646                       " resource %d, rect (%d,%d)+%d,%d, fb %d %d\n",
647                       __func__, scanout_id, res->resource_id,
648                       r->x, r->y, r->width, r->height,
649                       fb->width, fb->height);
650         *error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
651         return;
652     }
653 
654     g->parent_obj.enable = 1;
655 
656     if (res->blob) {
657         if (console_has_gl(scanout->con)) {
658             if (!virtio_gpu_update_dmabuf(g, scanout_id, res, fb, r)) {
659                 virtio_gpu_update_scanout(g, scanout_id, res, r);
660             } else {
661                 *error = VIRTIO_GPU_RESP_ERR_OUT_OF_MEMORY;
662             }
663             return;
664         }
665 
666         data = res->blob;
667     } else {
668         data = (uint8_t *)pixman_image_get_data(res->image);
669     }
670 
671     /* create a surface for this scanout */
672     if ((res->blob && !console_has_gl(scanout->con)) ||
673         !scanout->ds ||
674         surface_data(scanout->ds) != data + fb->offset ||
675         scanout->width != r->width ||
676         scanout->height != r->height) {
677         pixman_image_t *rect;
678         void *ptr = data + fb->offset;
679         rect = pixman_image_create_bits(fb->format, r->width, r->height,
680                                         ptr, fb->stride);
681 
682         if (res->image) {
683             pixman_image_ref(res->image);
684             pixman_image_set_destroy_function(rect, virtio_unref_resource,
685                                               res->image);
686         }
687 
688         /* realloc the surface ptr */
689         scanout->ds = qemu_create_displaysurface_pixman(rect);
690         if (!scanout->ds) {
691             *error = VIRTIO_GPU_RESP_ERR_UNSPEC;
692             return;
693         }
694 #ifdef WIN32
695         qemu_displaysurface_win32_set_handle(scanout->ds, res->handle, fb->offset);
696 #endif
697 
698         pixman_image_unref(rect);
699         dpy_gfx_replace_surface(g->parent_obj.scanout[scanout_id].con,
700                                 scanout->ds);
701     }
702 
703     virtio_gpu_update_scanout(g, scanout_id, res, r);
704 }
705 
706 static void virtio_gpu_set_scanout(VirtIOGPU *g,
707                                    struct virtio_gpu_ctrl_command *cmd)
708 {
709     struct virtio_gpu_simple_resource *res;
710     struct virtio_gpu_framebuffer fb = { 0 };
711     struct virtio_gpu_set_scanout ss;
712 
713     VIRTIO_GPU_FILL_CMD(ss);
714     virtio_gpu_bswap_32(&ss, sizeof(ss));
715     trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id,
716                                      ss.r.width, ss.r.height, ss.r.x, ss.r.y);
717 
718     if (ss.scanout_id >= g->parent_obj.conf.max_outputs) {
719         qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d",
720                       __func__, ss.scanout_id);
721         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
722         return;
723     }
724 
725     if (ss.resource_id == 0) {
726         virtio_gpu_disable_scanout(g, ss.scanout_id);
727         return;
728     }
729 
730     res = virtio_gpu_find_check_resource(g, ss.resource_id, true,
731                                          __func__, &cmd->error);
732     if (!res) {
733         return;
734     }
735 
736     fb.format = pixman_image_get_format(res->image);
737     fb.bytes_pp = DIV_ROUND_UP(PIXMAN_FORMAT_BPP(fb.format), 8);
738     fb.width  = pixman_image_get_width(res->image);
739     fb.height = pixman_image_get_height(res->image);
740     fb.stride = pixman_image_get_stride(res->image);
741     fb.offset = ss.r.x * fb.bytes_pp + ss.r.y * fb.stride;
742 
743     virtio_gpu_do_set_scanout(g, ss.scanout_id,
744                               &fb, res, &ss.r, &cmd->error);
745 }
746 
747 static void virtio_gpu_set_scanout_blob(VirtIOGPU *g,
748                                         struct virtio_gpu_ctrl_command *cmd)
749 {
750     struct virtio_gpu_simple_resource *res;
751     struct virtio_gpu_framebuffer fb = { 0 };
752     struct virtio_gpu_set_scanout_blob ss;
753     uint64_t fbend;
754 
755     VIRTIO_GPU_FILL_CMD(ss);
756     virtio_gpu_scanout_blob_bswap(&ss);
757     trace_virtio_gpu_cmd_set_scanout_blob(ss.scanout_id, ss.resource_id,
758                                           ss.r.width, ss.r.height, ss.r.x,
759                                           ss.r.y);
760 
761     if (ss.scanout_id >= g->parent_obj.conf.max_outputs) {
762         qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d",
763                       __func__, ss.scanout_id);
764         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
765         return;
766     }
767 
768     if (ss.resource_id == 0) {
769         virtio_gpu_disable_scanout(g, ss.scanout_id);
770         return;
771     }
772 
773     res = virtio_gpu_find_check_resource(g, ss.resource_id, true,
774                                          __func__, &cmd->error);
775     if (!res) {
776         return;
777     }
778 
779     fb.format = virtio_gpu_get_pixman_format(ss.format);
780     if (!fb.format) {
781         qemu_log_mask(LOG_GUEST_ERROR,
782                       "%s: host couldn't handle guest format %d\n",
783                       __func__, ss.format);
784         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
785         return;
786     }
787 
788     fb.bytes_pp = DIV_ROUND_UP(PIXMAN_FORMAT_BPP(fb.format), 8);
789     fb.width = ss.width;
790     fb.height = ss.height;
791     fb.stride = ss.strides[0];
792     fb.offset = ss.offsets[0] + ss.r.x * fb.bytes_pp + ss.r.y * fb.stride;
793 
794     fbend = fb.offset;
795     fbend += fb.stride * (ss.r.height - 1);
796     fbend += fb.bytes_pp * ss.r.width;
797     if (fbend > res->blob_size) {
798         qemu_log_mask(LOG_GUEST_ERROR,
799                       "%s: fb end out of range\n",
800                       __func__);
801         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
802         return;
803     }
804 
805     virtio_gpu_do_set_scanout(g, ss.scanout_id,
806                               &fb, res, &ss.r, &cmd->error);
807 }
808 
809 int virtio_gpu_create_mapping_iov(VirtIOGPU *g,
810                                   uint32_t nr_entries, uint32_t offset,
811                                   struct virtio_gpu_ctrl_command *cmd,
812                                   uint64_t **addr, struct iovec **iov,
813                                   uint32_t *niov)
814 {
815     struct virtio_gpu_mem_entry *ents;
816     size_t esize, s;
817     int e, v;
818 
819     if (nr_entries > 16384) {
820         qemu_log_mask(LOG_GUEST_ERROR,
821                       "%s: nr_entries is too big (%d > 16384)\n",
822                       __func__, nr_entries);
823         return -1;
824     }
825 
826     esize = sizeof(*ents) * nr_entries;
827     ents = g_malloc(esize);
828     s = iov_to_buf(cmd->elem.out_sg, cmd->elem.out_num,
829                    offset, ents, esize);
830     if (s != esize) {
831         qemu_log_mask(LOG_GUEST_ERROR,
832                       "%s: command data size incorrect %zu vs %zu\n",
833                       __func__, s, esize);
834         g_free(ents);
835         return -1;
836     }
837 
838     *iov = NULL;
839     if (addr) {
840         *addr = NULL;
841     }
842     for (e = 0, v = 0; e < nr_entries; e++) {
843         uint64_t a = le64_to_cpu(ents[e].addr);
844         uint32_t l = le32_to_cpu(ents[e].length);
845         hwaddr len;
846         void *map;
847 
848         do {
849             len = l;
850             map = dma_memory_map(VIRTIO_DEVICE(g)->dma_as, a, &len,
851                                  DMA_DIRECTION_TO_DEVICE,
852                                  MEMTXATTRS_UNSPECIFIED);
853             if (!map) {
854                 qemu_log_mask(LOG_GUEST_ERROR, "%s: failed to map MMIO memory for"
855                               " element %d\n", __func__, e);
856                 virtio_gpu_cleanup_mapping_iov(g, *iov, v);
857                 g_free(ents);
858                 *iov = NULL;
859                 if (addr) {
860                     g_free(*addr);
861                     *addr = NULL;
862                 }
863                 return -1;
864             }
865 
866             if (!(v % 16)) {
867                 *iov = g_renew(struct iovec, *iov, v + 16);
868                 if (addr) {
869                     *addr = g_renew(uint64_t, *addr, v + 16);
870                 }
871             }
872             (*iov)[v].iov_base = map;
873             (*iov)[v].iov_len = len;
874             if (addr) {
875                 (*addr)[v] = a;
876             }
877 
878             a += len;
879             l -= len;
880             v += 1;
881         } while (l > 0);
882     }
883     *niov = v;
884 
885     g_free(ents);
886     return 0;
887 }
888 
889 void virtio_gpu_cleanup_mapping_iov(VirtIOGPU *g,
890                                     struct iovec *iov, uint32_t count)
891 {
892     int i;
893 
894     for (i = 0; i < count; i++) {
895         dma_memory_unmap(VIRTIO_DEVICE(g)->dma_as,
896                          iov[i].iov_base, iov[i].iov_len,
897                          DMA_DIRECTION_TO_DEVICE,
898                          iov[i].iov_len);
899     }
900     g_free(iov);
901 }
902 
903 void virtio_gpu_cleanup_mapping(VirtIOGPU *g,
904                                 struct virtio_gpu_simple_resource *res)
905 {
906     virtio_gpu_cleanup_mapping_iov(g, res->iov, res->iov_cnt);
907     res->iov = NULL;
908     res->iov_cnt = 0;
909     g_free(res->addrs);
910     res->addrs = NULL;
911 
912     if (res->blob) {
913         virtio_gpu_fini_udmabuf(res);
914     }
915 }
916 
917 static void
918 virtio_gpu_resource_attach_backing(VirtIOGPU *g,
919                                    struct virtio_gpu_ctrl_command *cmd)
920 {
921     struct virtio_gpu_simple_resource *res;
922     struct virtio_gpu_resource_attach_backing ab;
923     int ret;
924 
925     VIRTIO_GPU_FILL_CMD(ab);
926     virtio_gpu_bswap_32(&ab, sizeof(ab));
927     trace_virtio_gpu_cmd_res_back_attach(ab.resource_id);
928 
929     res = virtio_gpu_find_resource(g, ab.resource_id);
930     if (!res) {
931         qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
932                       __func__, ab.resource_id);
933         cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
934         return;
935     }
936 
937     if (res->iov) {
938         cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
939         return;
940     }
941 
942     ret = virtio_gpu_create_mapping_iov(g, ab.nr_entries, sizeof(ab), cmd,
943                                         &res->addrs, &res->iov, &res->iov_cnt);
944     if (ret != 0) {
945         cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
946         return;
947     }
948 }
949 
950 static void
951 virtio_gpu_resource_detach_backing(VirtIOGPU *g,
952                                    struct virtio_gpu_ctrl_command *cmd)
953 {
954     struct virtio_gpu_simple_resource *res;
955     struct virtio_gpu_resource_detach_backing detach;
956 
957     VIRTIO_GPU_FILL_CMD(detach);
958     virtio_gpu_bswap_32(&detach, sizeof(detach));
959     trace_virtio_gpu_cmd_res_back_detach(detach.resource_id);
960 
961     res = virtio_gpu_find_check_resource(g, detach.resource_id, true,
962                                          __func__, &cmd->error);
963     if (!res) {
964         return;
965     }
966     virtio_gpu_cleanup_mapping(g, res);
967 }
968 
969 void virtio_gpu_simple_process_cmd(VirtIOGPU *g,
970                                    struct virtio_gpu_ctrl_command *cmd)
971 {
972     VIRTIO_GPU_FILL_CMD(cmd->cmd_hdr);
973     virtio_gpu_ctrl_hdr_bswap(&cmd->cmd_hdr);
974 
975     switch (cmd->cmd_hdr.type) {
976     case VIRTIO_GPU_CMD_GET_DISPLAY_INFO:
977         virtio_gpu_get_display_info(g, cmd);
978         break;
979     case VIRTIO_GPU_CMD_GET_EDID:
980         virtio_gpu_get_edid(g, cmd);
981         break;
982     case VIRTIO_GPU_CMD_RESOURCE_CREATE_2D:
983         virtio_gpu_resource_create_2d(g, cmd);
984         break;
985     case VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB:
986         if (!virtio_gpu_blob_enabled(g->parent_obj.conf)) {
987             cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
988             break;
989         }
990         virtio_gpu_resource_create_blob(g, cmd);
991         break;
992     case VIRTIO_GPU_CMD_RESOURCE_UNREF:
993         virtio_gpu_resource_unref(g, cmd);
994         break;
995     case VIRTIO_GPU_CMD_RESOURCE_FLUSH:
996         virtio_gpu_resource_flush(g, cmd);
997         break;
998     case VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D:
999         virtio_gpu_transfer_to_host_2d(g, cmd);
1000         break;
1001     case VIRTIO_GPU_CMD_SET_SCANOUT:
1002         virtio_gpu_set_scanout(g, cmd);
1003         break;
1004     case VIRTIO_GPU_CMD_SET_SCANOUT_BLOB:
1005         if (!virtio_gpu_blob_enabled(g->parent_obj.conf)) {
1006             cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
1007             break;
1008         }
1009         virtio_gpu_set_scanout_blob(g, cmd);
1010         break;
1011     case VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING:
1012         virtio_gpu_resource_attach_backing(g, cmd);
1013         break;
1014     case VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING:
1015         virtio_gpu_resource_detach_backing(g, cmd);
1016         break;
1017     default:
1018         cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
1019         break;
1020     }
1021     if (!cmd->finished) {
1022         if (!g->parent_obj.renderer_blocked) {
1023             virtio_gpu_ctrl_response_nodata(g, cmd, cmd->error ? cmd->error :
1024                                             VIRTIO_GPU_RESP_OK_NODATA);
1025         }
1026     }
1027 }
1028 
1029 static void virtio_gpu_handle_ctrl_cb(VirtIODevice *vdev, VirtQueue *vq)
1030 {
1031     VirtIOGPU *g = VIRTIO_GPU(vdev);
1032     qemu_bh_schedule(g->ctrl_bh);
1033 }
1034 
1035 static void virtio_gpu_handle_cursor_cb(VirtIODevice *vdev, VirtQueue *vq)
1036 {
1037     VirtIOGPU *g = VIRTIO_GPU(vdev);
1038     qemu_bh_schedule(g->cursor_bh);
1039 }
1040 
1041 void virtio_gpu_process_cmdq(VirtIOGPU *g)
1042 {
1043     struct virtio_gpu_ctrl_command *cmd;
1044     VirtIOGPUClass *vgc = VIRTIO_GPU_GET_CLASS(g);
1045 
1046     if (g->processing_cmdq) {
1047         return;
1048     }
1049     g->processing_cmdq = true;
1050     while (!QTAILQ_EMPTY(&g->cmdq)) {
1051         cmd = QTAILQ_FIRST(&g->cmdq);
1052 
1053         if (g->parent_obj.renderer_blocked) {
1054             break;
1055         }
1056 
1057         /* process command */
1058         vgc->process_cmd(g, cmd);
1059 
1060         QTAILQ_REMOVE(&g->cmdq, cmd, next);
1061         if (virtio_gpu_stats_enabled(g->parent_obj.conf)) {
1062             g->stats.requests++;
1063         }
1064 
1065         if (!cmd->finished) {
1066             QTAILQ_INSERT_TAIL(&g->fenceq, cmd, next);
1067             g->inflight++;
1068             if (virtio_gpu_stats_enabled(g->parent_obj.conf)) {
1069                 if (g->stats.max_inflight < g->inflight) {
1070                     g->stats.max_inflight = g->inflight;
1071                 }
1072                 fprintf(stderr, "inflight: %3d (+)\r", g->inflight);
1073             }
1074         } else {
1075             g_free(cmd);
1076         }
1077     }
1078     g->processing_cmdq = false;
1079 }
1080 
1081 static void virtio_gpu_process_fenceq(VirtIOGPU *g)
1082 {
1083     struct virtio_gpu_ctrl_command *cmd, *tmp;
1084 
1085     QTAILQ_FOREACH_SAFE(cmd, &g->fenceq, next, tmp) {
1086         trace_virtio_gpu_fence_resp(cmd->cmd_hdr.fence_id);
1087         virtio_gpu_ctrl_response_nodata(g, cmd, VIRTIO_GPU_RESP_OK_NODATA);
1088         QTAILQ_REMOVE(&g->fenceq, cmd, next);
1089         g_free(cmd);
1090         g->inflight--;
1091         if (virtio_gpu_stats_enabled(g->parent_obj.conf)) {
1092             fprintf(stderr, "inflight: %3d (-)\r", g->inflight);
1093         }
1094     }
1095 }
1096 
1097 static void virtio_gpu_handle_gl_flushed(VirtIOGPUBase *b)
1098 {
1099     VirtIOGPU *g = container_of(b, VirtIOGPU, parent_obj);
1100 
1101     virtio_gpu_process_fenceq(g);
1102     virtio_gpu_process_cmdq(g);
1103 }
1104 
1105 static void virtio_gpu_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
1106 {
1107     VirtIOGPU *g = VIRTIO_GPU(vdev);
1108     struct virtio_gpu_ctrl_command *cmd;
1109 
1110     if (!virtio_queue_ready(vq)) {
1111         return;
1112     }
1113 
1114     cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
1115     while (cmd) {
1116         cmd->vq = vq;
1117         cmd->error = 0;
1118         cmd->finished = false;
1119         QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next);
1120         cmd = virtqueue_pop(vq, sizeof(struct virtio_gpu_ctrl_command));
1121     }
1122 
1123     virtio_gpu_process_cmdq(g);
1124 }
1125 
1126 static void virtio_gpu_ctrl_bh(void *opaque)
1127 {
1128     VirtIOGPU *g = opaque;
1129     VirtIOGPUClass *vgc = VIRTIO_GPU_GET_CLASS(g);
1130 
1131     vgc->handle_ctrl(&g->parent_obj.parent_obj, g->ctrl_vq);
1132 }
1133 
1134 static void virtio_gpu_handle_cursor(VirtIODevice *vdev, VirtQueue *vq)
1135 {
1136     VirtIOGPU *g = VIRTIO_GPU(vdev);
1137     VirtQueueElement *elem;
1138     size_t s;
1139     struct virtio_gpu_update_cursor cursor_info;
1140 
1141     if (!virtio_queue_ready(vq)) {
1142         return;
1143     }
1144     for (;;) {
1145         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
1146         if (!elem) {
1147             break;
1148         }
1149 
1150         s = iov_to_buf(elem->out_sg, elem->out_num, 0,
1151                        &cursor_info, sizeof(cursor_info));
1152         if (s != sizeof(cursor_info)) {
1153             qemu_log_mask(LOG_GUEST_ERROR,
1154                           "%s: cursor size incorrect %zu vs %zu\n",
1155                           __func__, s, sizeof(cursor_info));
1156         } else {
1157             virtio_gpu_bswap_32(&cursor_info, sizeof(cursor_info));
1158             update_cursor(g, &cursor_info);
1159         }
1160         virtqueue_push(vq, elem, 0);
1161         virtio_notify(vdev, vq);
1162         g_free(elem);
1163     }
1164 }
1165 
1166 static void virtio_gpu_cursor_bh(void *opaque)
1167 {
1168     VirtIOGPU *g = opaque;
1169     virtio_gpu_handle_cursor(&g->parent_obj.parent_obj, g->cursor_vq);
1170 }
1171 
1172 static const VMStateDescription vmstate_virtio_gpu_scanout = {
1173     .name = "virtio-gpu-one-scanout",
1174     .version_id = 1,
1175     .fields = (VMStateField[]) {
1176         VMSTATE_UINT32(resource_id, struct virtio_gpu_scanout),
1177         VMSTATE_UINT32(width, struct virtio_gpu_scanout),
1178         VMSTATE_UINT32(height, struct virtio_gpu_scanout),
1179         VMSTATE_INT32(x, struct virtio_gpu_scanout),
1180         VMSTATE_INT32(y, struct virtio_gpu_scanout),
1181         VMSTATE_UINT32(cursor.resource_id, struct virtio_gpu_scanout),
1182         VMSTATE_UINT32(cursor.hot_x, struct virtio_gpu_scanout),
1183         VMSTATE_UINT32(cursor.hot_y, struct virtio_gpu_scanout),
1184         VMSTATE_UINT32(cursor.pos.x, struct virtio_gpu_scanout),
1185         VMSTATE_UINT32(cursor.pos.y, struct virtio_gpu_scanout),
1186         VMSTATE_END_OF_LIST()
1187     },
1188 };
1189 
1190 static const VMStateDescription vmstate_virtio_gpu_scanouts = {
1191     .name = "virtio-gpu-scanouts",
1192     .version_id = 1,
1193     .fields = (VMStateField[]) {
1194         VMSTATE_INT32(parent_obj.enable, struct VirtIOGPU),
1195         VMSTATE_UINT32_EQUAL(parent_obj.conf.max_outputs,
1196                              struct VirtIOGPU, NULL),
1197         VMSTATE_STRUCT_VARRAY_UINT32(parent_obj.scanout, struct VirtIOGPU,
1198                                      parent_obj.conf.max_outputs, 1,
1199                                      vmstate_virtio_gpu_scanout,
1200                                      struct virtio_gpu_scanout),
1201         VMSTATE_END_OF_LIST()
1202     },
1203 };
1204 
1205 static int virtio_gpu_save(QEMUFile *f, void *opaque, size_t size,
1206                            const VMStateField *field, JSONWriter *vmdesc)
1207 {
1208     VirtIOGPU *g = opaque;
1209     struct virtio_gpu_simple_resource *res;
1210     int i;
1211 
1212     /* in 2d mode we should never find unprocessed commands here */
1213     assert(QTAILQ_EMPTY(&g->cmdq));
1214 
1215     QTAILQ_FOREACH(res, &g->reslist, next) {
1216         qemu_put_be32(f, res->resource_id);
1217         qemu_put_be32(f, res->width);
1218         qemu_put_be32(f, res->height);
1219         qemu_put_be32(f, res->format);
1220         qemu_put_be32(f, res->iov_cnt);
1221         for (i = 0; i < res->iov_cnt; i++) {
1222             qemu_put_be64(f, res->addrs[i]);
1223             qemu_put_be32(f, res->iov[i].iov_len);
1224         }
1225         qemu_put_buffer(f, (void *)pixman_image_get_data(res->image),
1226                         pixman_image_get_stride(res->image) * res->height);
1227     }
1228     qemu_put_be32(f, 0); /* end of list */
1229 
1230     return vmstate_save_state(f, &vmstate_virtio_gpu_scanouts, g, NULL);
1231 }
1232 
1233 static int virtio_gpu_load(QEMUFile *f, void *opaque, size_t size,
1234                            const VMStateField *field)
1235 {
1236     VirtIOGPU *g = opaque;
1237     struct virtio_gpu_simple_resource *res;
1238     struct virtio_gpu_scanout *scanout;
1239     uint32_t resource_id, pformat;
1240     void *bits = NULL;
1241     int i;
1242 
1243     g->hostmem = 0;
1244 
1245     resource_id = qemu_get_be32(f);
1246     while (resource_id != 0) {
1247         res = virtio_gpu_find_resource(g, resource_id);
1248         if (res) {
1249             return -EINVAL;
1250         }
1251 
1252         res = g_new0(struct virtio_gpu_simple_resource, 1);
1253         res->resource_id = resource_id;
1254         res->width = qemu_get_be32(f);
1255         res->height = qemu_get_be32(f);
1256         res->format = qemu_get_be32(f);
1257         res->iov_cnt = qemu_get_be32(f);
1258 
1259         /* allocate */
1260         pformat = virtio_gpu_get_pixman_format(res->format);
1261         if (!pformat) {
1262             g_free(res);
1263             return -EINVAL;
1264         }
1265 
1266         res->hostmem = calc_image_hostmem(pformat, res->width, res->height);
1267 #ifdef WIN32
1268         bits = qemu_win32_map_alloc(res->hostmem, &res->handle, &error_warn);
1269         if (!bits) {
1270             g_free(res);
1271             return -EINVAL;
1272         }
1273 #endif
1274         res->image = pixman_image_create_bits(
1275             pformat,
1276             res->width, res->height,
1277             bits, res->height ? res->hostmem / res->height : 0);
1278         if (!res->image) {
1279             g_free(res);
1280             return -EINVAL;
1281         }
1282 #ifdef WIN32
1283         pixman_image_set_destroy_function(res->image, win32_pixman_image_destroy, res->handle);
1284 #endif
1285 
1286         res->addrs = g_new(uint64_t, res->iov_cnt);
1287         res->iov = g_new(struct iovec, res->iov_cnt);
1288 
1289         /* read data */
1290         for (i = 0; i < res->iov_cnt; i++) {
1291             res->addrs[i] = qemu_get_be64(f);
1292             res->iov[i].iov_len = qemu_get_be32(f);
1293         }
1294         qemu_get_buffer(f, (void *)pixman_image_get_data(res->image),
1295                         pixman_image_get_stride(res->image) * res->height);
1296 
1297         /* restore mapping */
1298         for (i = 0; i < res->iov_cnt; i++) {
1299             hwaddr len = res->iov[i].iov_len;
1300             res->iov[i].iov_base =
1301                 dma_memory_map(VIRTIO_DEVICE(g)->dma_as, res->addrs[i], &len,
1302                                DMA_DIRECTION_TO_DEVICE,
1303                                MEMTXATTRS_UNSPECIFIED);
1304 
1305             if (!res->iov[i].iov_base || len != res->iov[i].iov_len) {
1306                 /* Clean up the half-a-mapping we just created... */
1307                 if (res->iov[i].iov_base) {
1308                     dma_memory_unmap(VIRTIO_DEVICE(g)->dma_as,
1309                                      res->iov[i].iov_base,
1310                                      len,
1311                                      DMA_DIRECTION_TO_DEVICE,
1312                                      0);
1313                 }
1314                 /* ...and the mappings for previous loop iterations */
1315                 res->iov_cnt = i;
1316                 virtio_gpu_cleanup_mapping(g, res);
1317                 pixman_image_unref(res->image);
1318                 g_free(res);
1319                 return -EINVAL;
1320             }
1321         }
1322 
1323         QTAILQ_INSERT_HEAD(&g->reslist, res, next);
1324         g->hostmem += res->hostmem;
1325 
1326         resource_id = qemu_get_be32(f);
1327     }
1328 
1329     /* load & apply scanout state */
1330     vmstate_load_state(f, &vmstate_virtio_gpu_scanouts, g, 1);
1331     for (i = 0; i < g->parent_obj.conf.max_outputs; i++) {
1332         /* FIXME: should take scanout.r.{x,y} into account */
1333         scanout = &g->parent_obj.scanout[i];
1334         if (!scanout->resource_id) {
1335             continue;
1336         }
1337         res = virtio_gpu_find_resource(g, scanout->resource_id);
1338         if (!res) {
1339             return -EINVAL;
1340         }
1341         scanout->ds = qemu_create_displaysurface_pixman(res->image);
1342         if (!scanout->ds) {
1343             return -EINVAL;
1344         }
1345 #ifdef WIN32
1346         qemu_displaysurface_win32_set_handle(scanout->ds, res->handle, 0);
1347 #endif
1348 
1349         dpy_gfx_replace_surface(scanout->con, scanout->ds);
1350         dpy_gfx_update_full(scanout->con);
1351         if (scanout->cursor.resource_id) {
1352             update_cursor(g, &scanout->cursor);
1353         }
1354         res->scanout_bitmask |= (1 << i);
1355     }
1356 
1357     return 0;
1358 }
1359 
1360 void virtio_gpu_device_realize(DeviceState *qdev, Error **errp)
1361 {
1362     VirtIODevice *vdev = VIRTIO_DEVICE(qdev);
1363     VirtIOGPU *g = VIRTIO_GPU(qdev);
1364 
1365     if (virtio_gpu_blob_enabled(g->parent_obj.conf)) {
1366         if (!virtio_gpu_rutabaga_enabled(g->parent_obj.conf) &&
1367             !virtio_gpu_have_udmabuf()) {
1368             error_setg(errp, "need rutabaga or udmabuf for blob resources");
1369             return;
1370         }
1371 
1372         if (virtio_gpu_virgl_enabled(g->parent_obj.conf)) {
1373             error_setg(errp, "blobs and virgl are not compatible (yet)");
1374             return;
1375         }
1376     }
1377 
1378     if (!virtio_gpu_base_device_realize(qdev,
1379                                         virtio_gpu_handle_ctrl_cb,
1380                                         virtio_gpu_handle_cursor_cb,
1381                                         errp)) {
1382         return;
1383     }
1384 
1385     g->ctrl_vq = virtio_get_queue(vdev, 0);
1386     g->cursor_vq = virtio_get_queue(vdev, 1);
1387     g->ctrl_bh = qemu_bh_new_guarded(virtio_gpu_ctrl_bh, g,
1388                                      &qdev->mem_reentrancy_guard);
1389     g->cursor_bh = qemu_bh_new_guarded(virtio_gpu_cursor_bh, g,
1390                                        &qdev->mem_reentrancy_guard);
1391     g->reset_bh = qemu_bh_new(virtio_gpu_reset_bh, g);
1392     qemu_cond_init(&g->reset_cond);
1393     QTAILQ_INIT(&g->reslist);
1394     QTAILQ_INIT(&g->cmdq);
1395     QTAILQ_INIT(&g->fenceq);
1396 }
1397 
1398 static void virtio_gpu_device_unrealize(DeviceState *qdev)
1399 {
1400     VirtIOGPU *g = VIRTIO_GPU(qdev);
1401 
1402     g_clear_pointer(&g->ctrl_bh, qemu_bh_delete);
1403     g_clear_pointer(&g->cursor_bh, qemu_bh_delete);
1404     g_clear_pointer(&g->reset_bh, qemu_bh_delete);
1405     qemu_cond_destroy(&g->reset_cond);
1406     virtio_gpu_base_device_unrealize(qdev);
1407 }
1408 
1409 static void virtio_gpu_reset_bh(void *opaque)
1410 {
1411     VirtIOGPU *g = VIRTIO_GPU(opaque);
1412     struct virtio_gpu_simple_resource *res, *tmp;
1413     int i = 0;
1414 
1415     QTAILQ_FOREACH_SAFE(res, &g->reslist, next, tmp) {
1416         virtio_gpu_resource_destroy(g, res);
1417     }
1418 
1419     for (i = 0; i < g->parent_obj.conf.max_outputs; i++) {
1420         dpy_gfx_replace_surface(g->parent_obj.scanout[i].con, NULL);
1421     }
1422 
1423     g->reset_finished = true;
1424     qemu_cond_signal(&g->reset_cond);
1425 }
1426 
1427 void virtio_gpu_reset(VirtIODevice *vdev)
1428 {
1429     VirtIOGPU *g = VIRTIO_GPU(vdev);
1430     struct virtio_gpu_ctrl_command *cmd;
1431 
1432     if (qemu_in_vcpu_thread()) {
1433         g->reset_finished = false;
1434         qemu_bh_schedule(g->reset_bh);
1435         while (!g->reset_finished) {
1436             qemu_cond_wait_iothread(&g->reset_cond);
1437         }
1438     } else {
1439         virtio_gpu_reset_bh(g);
1440     }
1441 
1442     while (!QTAILQ_EMPTY(&g->cmdq)) {
1443         cmd = QTAILQ_FIRST(&g->cmdq);
1444         QTAILQ_REMOVE(&g->cmdq, cmd, next);
1445         g_free(cmd);
1446     }
1447 
1448     while (!QTAILQ_EMPTY(&g->fenceq)) {
1449         cmd = QTAILQ_FIRST(&g->fenceq);
1450         QTAILQ_REMOVE(&g->fenceq, cmd, next);
1451         g->inflight--;
1452         g_free(cmd);
1453     }
1454 
1455     virtio_gpu_base_reset(VIRTIO_GPU_BASE(vdev));
1456 }
1457 
1458 static void
1459 virtio_gpu_get_config(VirtIODevice *vdev, uint8_t *config)
1460 {
1461     VirtIOGPUBase *g = VIRTIO_GPU_BASE(vdev);
1462 
1463     memcpy(config, &g->virtio_config, sizeof(g->virtio_config));
1464 }
1465 
1466 static void
1467 virtio_gpu_set_config(VirtIODevice *vdev, const uint8_t *config)
1468 {
1469     VirtIOGPUBase *g = VIRTIO_GPU_BASE(vdev);
1470     const struct virtio_gpu_config *vgconfig =
1471         (const struct virtio_gpu_config *)config;
1472 
1473     if (vgconfig->events_clear) {
1474         g->virtio_config.events_read &= ~vgconfig->events_clear;
1475     }
1476 }
1477 
1478 /*
1479  * For historical reasons virtio_gpu does not adhere to virtio migration
1480  * scheme as described in doc/virtio-migration.txt, in a sense that no
1481  * save/load callback are provided to the core. Instead the device data
1482  * is saved/loaded after the core data.
1483  *
1484  * Because of this we need a special vmsd.
1485  */
1486 static const VMStateDescription vmstate_virtio_gpu = {
1487     .name = "virtio-gpu",
1488     .minimum_version_id = VIRTIO_GPU_VM_VERSION,
1489     .version_id = VIRTIO_GPU_VM_VERSION,
1490     .fields = (VMStateField[]) {
1491         VMSTATE_VIRTIO_DEVICE /* core */,
1492         {
1493             .name = "virtio-gpu",
1494             .info = &(const VMStateInfo) {
1495                         .name = "virtio-gpu",
1496                         .get = virtio_gpu_load,
1497                         .put = virtio_gpu_save,
1498             },
1499             .flags = VMS_SINGLE,
1500         } /* device */,
1501         VMSTATE_END_OF_LIST()
1502     },
1503 };
1504 
1505 static Property virtio_gpu_properties[] = {
1506     VIRTIO_GPU_BASE_PROPERTIES(VirtIOGPU, parent_obj.conf),
1507     DEFINE_PROP_SIZE("max_hostmem", VirtIOGPU, conf_max_hostmem,
1508                      256 * MiB),
1509     DEFINE_PROP_BIT("blob", VirtIOGPU, parent_obj.conf.flags,
1510                     VIRTIO_GPU_FLAG_BLOB_ENABLED, false),
1511     DEFINE_PROP_SIZE("hostmem", VirtIOGPU, parent_obj.conf.hostmem, 0),
1512     DEFINE_PROP_END_OF_LIST(),
1513 };
1514 
1515 static void virtio_gpu_class_init(ObjectClass *klass, void *data)
1516 {
1517     DeviceClass *dc = DEVICE_CLASS(klass);
1518     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1519     VirtIOGPUClass *vgc = VIRTIO_GPU_CLASS(klass);
1520     VirtIOGPUBaseClass *vgbc = &vgc->parent;
1521 
1522     vgc->handle_ctrl = virtio_gpu_handle_ctrl;
1523     vgc->process_cmd = virtio_gpu_simple_process_cmd;
1524     vgc->update_cursor_data = virtio_gpu_update_cursor_data;
1525     vgbc->gl_flushed = virtio_gpu_handle_gl_flushed;
1526 
1527     vdc->realize = virtio_gpu_device_realize;
1528     vdc->unrealize = virtio_gpu_device_unrealize;
1529     vdc->reset = virtio_gpu_reset;
1530     vdc->get_config = virtio_gpu_get_config;
1531     vdc->set_config = virtio_gpu_set_config;
1532 
1533     dc->vmsd = &vmstate_virtio_gpu;
1534     device_class_set_props(dc, virtio_gpu_properties);
1535 }
1536 
1537 static const TypeInfo virtio_gpu_info = {
1538     .name = TYPE_VIRTIO_GPU,
1539     .parent = TYPE_VIRTIO_GPU_BASE,
1540     .instance_size = sizeof(VirtIOGPU),
1541     .class_size = sizeof(VirtIOGPUClass),
1542     .class_init = virtio_gpu_class_init,
1543 };
1544 module_obj(TYPE_VIRTIO_GPU);
1545 module_kconfig(VIRTIO_GPU);
1546 
1547 static void virtio_register_types(void)
1548 {
1549     type_register_static(&virtio_gpu_info);
1550 }
1551 
1552 type_init(virtio_register_types)
1553