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