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