static void gen_mipsdsp_add_cmp_pick(DisasContext *ctx,

                                     uint32_t op1, uint32_t op2,

                                     int ret, int v1, int v2, int check_ret)

{

    const char *opn = "mipsdsp add compare pick";

    TCGv_i32 t0;

    TCGv t1;

    TCGv v1_t;

    TCGv v2_t;

    if ((ret == 0) && (check_ret == 1)) {

        /* Treat as NOP. */

        MIPS_DEBUG("NOP");

        return;

    }

    t0 = tcg_temp_new_i32();

    t1 = tcg_temp_new();

    v1_t = tcg_temp_new();

    v2_t = tcg_temp_new();

    gen_load_gpr(v1_t, v1);

    gen_load_gpr(v2_t, v2);

    switch (op1) {

    case OPC_APPEND_DSP:

        switch (op2) {

        case OPC_APPEND:

            tcg_gen_movi_i32(t0, v2);

            gen_helper_append(cpu_gpr[ret], cpu_gpr[ret], v1_t, t0);

            break;

        case OPC_PREPEND:

            tcg_gen_movi_i32(t0, v2);

            gen_helper_prepend(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);

            break;

        case OPC_BALIGN:

            tcg_gen_movi_i32(t0, v2);

            gen_helper_balign(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);

            break;

        default:            /* Invid */

            MIPS_INVAL("MASK APPEND");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_CMPU_EQ_QB_DSP:

        switch (op2) {

        case OPC_CMPU_EQ_QB:

            check_dsp(ctx);

            gen_helper_cmpu_eq_qb(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPU_LT_QB:

            check_dsp(ctx);

            gen_helper_cmpu_lt_qb(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPU_LE_QB:

            check_dsp(ctx);

            gen_helper_cmpu_le_qb(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPGU_EQ_QB:

            check_dsp(ctx);

            gen_helper_cmpgu_eq_qb(cpu_gpr[ret], v1_t, v2_t);

            break;

        case OPC_CMPGU_LT_QB:

            check_dsp(ctx);

            gen_helper_cmpgu_lt_qb(cpu_gpr[ret], v1_t, v2_t);

            break;

        case OPC_CMPGU_LE_QB:

            check_dsp(ctx);

            gen_helper_cmpgu_le_qb(cpu_gpr[ret], v1_t, v2_t);

            break;

        case OPC_CMPGDU_EQ_QB:

            check_dspr2(ctx);

            gen_helper_cmpgu_eq_qb(t1, v1_t, v2_t);

            tcg_gen_mov_tl(cpu_gpr[ret], t1);

            tcg_gen_andi_tl(cpu_dspctrl, cpu_dspctrl, 0xF0FFFFFF);

            tcg_gen_shli_tl(t1, t1, 24);

            tcg_gen_or_tl(cpu_dspctrl, cpu_dspctrl, t1);

            break;

        case OPC_CMPGDU_LT_QB:

            check_dspr2(ctx);

            gen_helper_cmpgu_lt_qb(t1, v1_t, v2_t);

            tcg_gen_mov_tl(cpu_gpr[ret], t1);

            tcg_gen_andi_tl(cpu_dspctrl, cpu_dspctrl, 0xF0FFFFFF);

            tcg_gen_shli_tl(t1, t1, 24);

            tcg_gen_or_tl(cpu_dspctrl, cpu_dspctrl, t1);

            break;

        case OPC_CMPGDU_LE_QB:

            check_dspr2(ctx);

            gen_helper_cmpgu_le_qb(t1, v1_t, v2_t);

            tcg_gen_mov_tl(cpu_gpr[ret], t1);

            tcg_gen_andi_tl(cpu_dspctrl, cpu_dspctrl, 0xF0FFFFFF);

            tcg_gen_shli_tl(t1, t1, 24);

            tcg_gen_or_tl(cpu_dspctrl, cpu_dspctrl, t1);

            break;

        case OPC_CMP_EQ_PH:

            check_dsp(ctx);

            gen_helper_cmp_eq_ph(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMP_LT_PH:

            check_dsp(ctx);

            gen_helper_cmp_lt_ph(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMP_LE_PH:

            check_dsp(ctx);

            gen_helper_cmp_le_ph(v1_t, v2_t, cpu_env);

            break;

        case OPC_PICK_QB:

            check_dsp(ctx);

            gen_helper_pick_qb(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        case OPC_PICK_PH:

            check_dsp(ctx);

            gen_helper_pick_ph(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        case OPC_PACKRL_PH:

            check_dsp(ctx);

            gen_helper_packrl_ph(cpu_gpr[ret], v1_t, v2_t);

            break;

        }

        break;

#ifdef TARGET_MIPS64

    case OPC_CMPU_EQ_OB_DSP:

        switch (op2) {

        case OPC_CMP_EQ_PW:

            check_dsp(ctx);

            gen_helper_cmp_eq_pw(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMP_LT_PW:

            check_dsp(ctx);

            gen_helper_cmp_lt_pw(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMP_LE_PW:

            check_dsp(ctx);

            gen_helper_cmp_le_pw(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMP_EQ_QH:

            check_dsp(ctx);

            gen_helper_cmp_eq_qh(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMP_LT_QH:

            check_dsp(ctx);

            gen_helper_cmp_lt_qh(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMP_LE_QH:

            check_dsp(ctx);

            gen_helper_cmp_le_qh(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPGDU_EQ_OB:

            check_dspr2(ctx);

            gen_helper_cmpgdu_eq_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPGDU_LT_OB:

            check_dspr2(ctx);

            gen_helper_cmpgdu_lt_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPGDU_LE_OB:

            check_dspr2(ctx);

            gen_helper_cmpgdu_le_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPGU_EQ_OB:

            check_dsp(ctx);

            gen_helper_cmpgu_eq_ob(cpu_gpr[ret], v1_t, v2_t);

            break;

        case OPC_CMPGU_LT_OB:

            check_dsp(ctx);

            gen_helper_cmpgu_lt_ob(cpu_gpr[ret], v1_t, v2_t);

            break;

        case OPC_CMPGU_LE_OB:

            check_dsp(ctx);

            gen_helper_cmpgu_le_ob(cpu_gpr[ret], v1_t, v2_t);

            break;

        case OPC_CMPU_EQ_OB:

            check_dsp(ctx);

            gen_helper_cmpu_eq_ob(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPU_LT_OB:

            check_dsp(ctx);

            gen_helper_cmpu_lt_ob(v1_t, v2_t, cpu_env);

            break;

        case OPC_CMPU_LE_OB:

            check_dsp(ctx);

            gen_helper_cmpu_le_ob(v1_t, v2_t, cpu_env);

            break;

        case OPC_PACKRL_PW:

            check_dsp(ctx);

            gen_helper_packrl_pw(cpu_gpr[ret], v1_t, v2_t);

            break;

        case OPC_PICK_OB:

            check_dsp(ctx);

            gen_helper_pick_ob(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        case OPC_PICK_PW:

            check_dsp(ctx);

            gen_helper_pick_pw(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        case OPC_PICK_QH:

            check_dsp(ctx);

            gen_helper_pick_qh(cpu_gpr[ret], v1_t, v2_t, cpu_env);

            break;

        }

        break;

    case OPC_DAPPEND_DSP:

        switch (op2) {

        case OPC_DAPPEND:

            tcg_gen_movi_i32(t0, v2);

            gen_helper_dappend(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);

            break;

        case OPC_PREPENDD:

            tcg_gen_movi_i32(t0, v2);

            gen_helper_prependd(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);

            break;

        case OPC_PREPENDW:

            tcg_gen_movi_i32(t0, v2);

            gen_helper_prependw(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);

            break;

        case OPC_DBALIGN:

            tcg_gen_movi_i32(t0, v2);

            gen_helper_dbalign(cpu_gpr[ret], v1_t, cpu_gpr[ret], t0);

            break;

        default:            /* Invalid */

            MIPS_INVAL("MASK DAPPEND");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

#endif

    }

    tcg_temp_free_i32(t0);

    tcg_temp_free(t1);

    tcg_temp_free(v1_t);

    tcg_temp_free(v2_t);

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s", opn);

}


static inline int IRQ_testbit(IRQQueue *q, int n_IRQ)

{

    return test_bit(q->queue, n_IRQ);

}


static int pic_arrays_init(HEVCContext *s)

{

    int log2_min_cb_size     = s->sps->log2_min_cb_size;

    int width                = s->sps->width;

    int height               = s->sps->height;

    int pic_size             = width * height;

    int pic_size_in_ctb      = ((width  >> log2_min_cb_size) + 1) *

                               ((height >> log2_min_cb_size) + 1);

    int ctb_count            = s->sps->ctb_width * s->sps->ctb_height;

    int min_pu_width  = width  >> s->sps->log2_min_pu_size;

    int pic_height_in_min_pu = height >> s->sps->log2_min_pu_size;

    int pic_size_in_min_pu   = min_pu_width * pic_height_in_min_pu;

    int pic_width_in_min_tu  = width  >> s->sps->log2_min_tb_size;

    int pic_height_in_min_tu = height >> s->sps->log2_min_tb_size;

    s->bs_width  = width  >> 3;

    s->bs_height = height >> 3;

    s->sao           = av_mallocz_array(ctb_count, sizeof(*s->sao));

    s->deblock       = av_mallocz_array(ctb_count, sizeof(*s->deblock));

    s->split_cu_flag = av_malloc(pic_size);

    if (!s->sao || !s->deblock || !s->split_cu_flag)

        goto fail;

    s->skip_flag    = av_malloc(pic_size_in_ctb);

    s->tab_ct_depth = av_malloc(s->sps->min_cb_height * s->sps->min_cb_width);

    if (!s->skip_flag || !s->tab_ct_depth)

        goto fail;

    s->tab_ipm  = av_malloc(pic_size_in_min_pu);

    s->cbf_luma = av_malloc(pic_width_in_min_tu * pic_height_in_min_tu);

    s->is_pcm   = av_malloc(pic_size_in_min_pu);

    if (!s->tab_ipm || !s->cbf_luma || !s->is_pcm)

        goto fail;

    s->filter_slice_edges = av_malloc(ctb_count);

    s->tab_slice_address  = av_malloc(pic_size_in_ctb * sizeof(*s->tab_slice_address));

    s->qp_y_tab           = av_malloc(pic_size_in_ctb * sizeof(*s->qp_y_tab));

    if (!s->qp_y_tab || !s->filter_slice_edges || !s->tab_slice_address)

        goto fail;

    s->horizontal_bs = av_mallocz(2 * s->bs_width * (s->bs_height + 1));

    s->vertical_bs   = av_mallocz(2 * s->bs_width * (s->bs_height + 1));

    if (!s->horizontal_bs || !s->vertical_bs)

        goto fail;

    s->tab_mvf_pool = av_buffer_pool_init(pic_size_in_min_pu * sizeof(MvField),

                                          av_buffer_alloc);

    s->rpl_tab_pool = av_buffer_pool_init(ctb_count * sizeof(RefPicListTab),

                                          av_buffer_allocz);

    if (!s->tab_mvf_pool || !s->rpl_tab_pool)

        goto fail;

    return 0;

fail:

    pic_arrays_free(s);

    return AVERROR(ENOMEM);

}


static void ioreq_finish(struct ioreq *ioreq)

{

    struct XenBlkDev *blkdev = ioreq->blkdev;

    LIST_REMOVE(ioreq, list);

    LIST_INSERT_HEAD(&blkdev->finished, ioreq, list);

    blkdev->requests_inflight--;

    blkdev->requests_finished++;

}


static void test_qemu_strtosz_invalid(void)

{

    const char *str;

    char *endptr = NULL;

    int64_t res;

    str = "";

    res = qemu_strtosz(str, &endptr);

    g_assert_cmpint(res, ==, -EINVAL);

    g_assert(endptr == str);

    str = " \t ";

    res = qemu_strtosz(str, &endptr);

    g_assert_cmpint(res, ==, -EINVAL);

    g_assert(endptr == str);

    str = "crap";

    res = qemu_strtosz(str, &endptr);

    g_assert_cmpint(res, ==, -EINVAL);

    g_assert(endptr == str);

}


static void virtio_gpu_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)

{

    VirtIOGPU *g = VIRTIO_GPU(vdev);

    struct virtio_gpu_ctrl_command *cmd;

    if (!virtio_queue_ready(vq)) {

        return;

    }

#ifdef CONFIG_VIRGL

    if (!g->renderer_inited && g->use_virgl_renderer) {

        virtio_gpu_virgl_init(g);

        g->renderer_inited = true;

    }

#endif

    cmd = g_new(struct virtio_gpu_ctrl_command, 1);

    while (virtqueue_pop(vq, &cmd->elem)) {

        cmd->vq = vq;

        cmd->error = 0;

        cmd->finished = false;

        cmd->waiting = false;

        QTAILQ_INSERT_TAIL(&g->cmdq, cmd, next);

        cmd = g_new(struct virtio_gpu_ctrl_command, 1);

    }

    g_free(cmd);

    virtio_gpu_process_cmdq(g);

#ifdef CONFIG_VIRGL

    if (g->use_virgl_renderer) {

        virtio_gpu_virgl_fence_poll(g);

    }

#endif

}


static void handle_mousemotion(DisplayState *ds, SDL_Event *ev)

{

    int max_x, max_y;

    if (is_graphic_console() &&

        (kbd_mouse_is_absolute() || absolute_enabled)) {

        max_x = real_screen->w - 1;

        max_y = real_screen->h - 1;

        if (gui_grab && (ev->motion.x == 0 || ev->motion.y == 0 ||

            ev->motion.x == max_x || ev->motion.y == max_y)) {

            sdl_grab_end();

        }

        if (!gui_grab && SDL_GetAppState() & SDL_APPINPUTFOCUS &&

            (ev->motion.x > 0 && ev->motion.x < max_x &&

            ev->motion.y > 0 && ev->motion.y < max_y)) {

            sdl_grab_start();

        }

    }

    if (gui_grab || kbd_mouse_is_absolute() || absolute_enabled) {

        sdl_send_mouse_event(ev->motion.xrel, ev->motion.yrel, 0,

                             ev->motion.x, ev->motion.y, ev->motion.state);

    }

}


void helper_mwait(CPUX86State *env, int next_eip_addend)

{

    CPUState *cs;

    X86CPU *cpu;

    if ((uint32_t)env->regs[R_ECX] != 0) {

        raise_exception(env, EXCP0D_GPF);

    }

    cpu_svm_check_intercept_param(env, SVM_EXIT_MWAIT, 0);

    env->eip += next_eip_addend;

    cpu = x86_env_get_cpu(env);

    cs = CPU(cpu);

    /* XXX: not complete but not completely erroneous */

    if (cs->cpu_index != 0 || CPU_NEXT(cs) != NULL) {

        /* more than one CPU: do not sleep because another CPU may

           wake this one */

    } else {

        do_hlt(cpu);

    }

}


QemuConsole *graphic_console_init(DeviceState *dev, uint32_t head,

                                  const GraphicHwOps *hw_ops,

                                  void *opaque)

{

    Error *local_err = NULL;

    int width = 640;

    int height = 480;

    QemuConsole *s;

    DisplayState *ds;

    ds = get_alloc_displaystate();

    trace_console_gfx_new();

    s = new_console(ds, GRAPHIC_CONSOLE);

    s->hw_ops = hw_ops;

    s->hw = opaque;

    if (dev) {

        object_property_set_link(OBJECT(s), OBJECT(dev),

                                 "device", &local_err);

        object_property_set_int(OBJECT(s), head,

                                "head", &local_err);

    }

    s->surface = qemu_create_displaysurface(width, height);

    return s;

}


static int ram_save_setup(QEMUFile *f, void *opaque)

{

    RAMBlock *block;

    int64_t ram_pages = last_ram_offset() >> TARGET_PAGE_BITS;

    migration_bitmap = bitmap_new(ram_pages);

    bitmap_set(migration_bitmap, 0, ram_pages);

    migration_dirty_pages = ram_pages;

    mig_throttle_on = false;

    dirty_rate_high_cnt = 0;

    if (migrate_use_xbzrle()) {

        qemu_mutex_lock_iothread();

        XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /

                                  TARGET_PAGE_SIZE,

                                  TARGET_PAGE_SIZE);

        if (!XBZRLE.cache) {

            qemu_mutex_unlock_iothread();

            DPRINTF("Error creating cache\n");

            return -1;

        }

        qemu_mutex_init(&XBZRLE.lock);

        qemu_mutex_unlock_iothread();

        /* We prefer not to abort if there is no memory */

        XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);

        if (!XBZRLE.encoded_buf) {

            DPRINTF("Error allocating encoded_buf\n");

            return -1;

        }

        XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);

        if (!XBZRLE.current_buf) {

            DPRINTF("Error allocating current_buf\n");

            g_free(XBZRLE.encoded_buf);

            XBZRLE.encoded_buf = NULL;

            return -1;

        }

        acct_clear();

    }

    qemu_mutex_lock_iothread();

    qemu_mutex_lock_ramlist();

    bytes_transferred = 0;

    reset_ram_globals();

    memory_global_dirty_log_start();

    migration_bitmap_sync();

    qemu_mutex_unlock_iothread();

    qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);

    QTAILQ_FOREACH(block, &ram_list.blocks, next) {

        qemu_put_byte(f, strlen(block->idstr));

        qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));

        qemu_put_be64(f, block->length);

    }

    qemu_mutex_unlock_ramlist();

    ram_control_before_iterate(f, RAM_CONTROL_SETUP);

    ram_control_after_iterate(f, RAM_CONTROL_SETUP);

    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);

    return 0;

}


static int xan_decode_chroma(AVCodecContext *avctx, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    XanContext *s = avctx->priv_data;

    uint8_t *U, *V;

    unsigned chroma_off;

    int val, uval, vval;

    int i, j;

    const uint8_t *src, *src_end;

    const uint8_t *table;

    int mode, offset, dec_size;

    chroma_off = AV_RL32(buf + 4);

    if (!chroma_off)

        return 0;

    if (chroma_off + 10 >= avpkt->size) {

        av_log(avctx, AV_LOG_ERROR, "Invalid chroma block position\n");

        return -1;

    }

    src    = avpkt->data + 4 + chroma_off;

    table  = src + 2;

    mode   = bytestream_get_le16(&src);

    offset = bytestream_get_le16(&src) * 2;

    if (src - avpkt->data >= avpkt->size - offset) {

        av_log(avctx, AV_LOG_ERROR, "Invalid chroma block offset\n");

        return -1;

    }

    memset(s->scratch_buffer, 0, s->buffer_size);

    dec_size = xan_unpack(s->scratch_buffer, s->buffer_size, src + offset,

                          avpkt->size - offset - (src - avpkt->data));

    if (dec_size < 0) {

        av_log(avctx, AV_LOG_ERROR, "Chroma unpacking failed\n");

        return -1;

    }

    U = s->pic.data[1];

    V = s->pic.data[2];

    src     = s->scratch_buffer;

    src_end = src + dec_size;

    if (mode) {

        for (j = 0; j < avctx->height >> 1; j++) {

            for (i = 0; i < avctx->width >> 1; i++) {

                val = *src++;

                if (val) {

                    val  = AV_RL16(table + (val << 1));

                    uval = (val >> 3) & 0xF8;

                    vval = (val >> 8) & 0xF8;

                    U[i] = uval | (uval >> 5);

                    V[i] = vval | (vval >> 5);

                }

                if (src == src_end)

                    return 0;

            }

            U += s->pic.linesize[1];

            V += s->pic.linesize[2];

        }

    } else {

        uint8_t *U2 = U + s->pic.linesize[1];

        uint8_t *V2 = V + s->pic.linesize[2];

        for (j = 0; j < avctx->height >> 2; j++) {

            for (i = 0; i < avctx->width >> 1; i += 2) {

                val = *src++;

                if (val) {

                    val  = AV_RL16(table + (val << 1));

                    uval = (val >> 3) & 0xF8;

                    vval = (val >> 8) & 0xF8;

                    U[i] = U[i+1] = U2[i] = U2[i+1] = uval | (uval >> 5);

                    V[i] = V[i+1] = V2[i] = V2[i+1] = vval | (vval >> 5);

                }

            }

            U  += s->pic.linesize[1] * 2;

            V  += s->pic.linesize[2] * 2;

            U2 += s->pic.linesize[1] * 2;

            V2 += s->pic.linesize[2] * 2;

        }

    }

    return 0;

}


static int av_thread_message_queue_send_locked(AVThreadMessageQueue *mq,

                                               void *msg,

                                               unsigned flags)

{

    while (!mq->err_send && av_fifo_space(mq->fifo) < mq->elsize) {

        if ((flags & AV_THREAD_MESSAGE_NONBLOCK))

            return AVERROR(EAGAIN);

        pthread_cond_wait(&mq->cond, &mq->lock);

    }

    if (mq->err_send)

        return mq->err_send;

    av_fifo_generic_write(mq->fifo, msg, mq->elsize, NULL);

    pthread_cond_signal(&mq->cond);

    return 0;

}


static int rsd_probe(AVProbeData *p)

{

    if (!memcmp(p->buf, "RSD", 3) &&

        p->buf[3] - '0' >= 2 && p->buf[3] - '0' <= 6)

        return AVPROBE_SCORE_EXTENSION;

    return 0;

}


static uint64_t ntohll(uint64_t v) {

    union { uint32_t lv[2]; uint64_t llv; } u;

    u.llv = v;

    return ((uint64_t)ntohl(u.lv[0]) << 32) | (uint64_t) ntohl(u.lv[1]);

}


static av_always_inline int simple_limit(uint8_t *p, ptrdiff_t stride, int flim)

{

    LOAD_PIXELS

    return 2 * FFABS(p0 - q0) + (FFABS(p1 - q1) >> 1) <= flim;

}


void sample_dump(int fnum, INT32 *tab, int n)

{

    static FILE *files[16], *f;

    char buf[512];

    f = files[fnum];

    if (!f) {

        sprintf(buf, "/tmp/out%d.pcm", fnum);

        f = fopen(buf, "w");

        if (!f)

            return;

        files[fnum] = f;

    }

    if (fnum == 0) {

        int i;

        static int pos = 0;

        printf("pos=%d\n", pos);

        for(i=0;i<n;i++) {

            printf(" %f", (double)tab[i] / 32768.0);

            if ((i % 18) == 17)

                printf("\n");

        }

        pos += n;

    }

    fwrite(tab, 1, n * sizeof(INT32), f);

}


static void mb_cpu_realizefn(DeviceState *dev, Error **errp)

{

    MicroBlazeCPU *cpu = MICROBLAZE_CPU(dev);

    MicroBlazeCPUClass *mcc = MICROBLAZE_CPU_GET_CLASS(dev);

    cpu_reset(CPU(cpu));

    mcc->parent_realize(dev, errp);

}


static int dxva2_create_decoder(AVCodecContext *s)

{

    InputStream  *ist = s->opaque;

    int loglevel = (ist->hwaccel_id == HWACCEL_AUTO) ? AV_LOG_VERBOSE : AV_LOG_ERROR;

    DXVA2Context *ctx = ist->hwaccel_ctx;

    struct dxva_context *dxva_ctx = s->hwaccel_context;

    GUID *guid_list = NULL;

    unsigned guid_count = 0, i, j;

    GUID device_guid = GUID_NULL;

    const D3DFORMAT surface_format = (s->sw_pix_fmt == AV_PIX_FMT_YUV420P10) ? MKTAG('P','0','1','0') : MKTAG('N','V','1','2');

    D3DFORMAT target_format = 0;

    DXVA2_VideoDesc desc = { 0 };

    DXVA2_ConfigPictureDecode config;

    HRESULT hr;

    int surface_alignment, num_surfaces;

    int ret;

    AVDXVA2FramesContext *frames_hwctx;

    AVHWFramesContext *frames_ctx;

    hr = IDirectXVideoDecoderService_GetDecoderDeviceGuids(ctx->decoder_service, &guid_count, &guid_list);

    if (FAILED(hr)) {

        av_log(NULL, loglevel, "Failed to retrieve decoder device GUIDs\n");

        goto fail;

    }

    for (i = 0; dxva2_modes[i].guid; i++) {

        D3DFORMAT *target_list = NULL;

        unsigned target_count = 0;

        const dxva2_mode *mode = &dxva2_modes[i];

        if (mode->codec != s->codec_id)

            continue;

        for (j = 0; j < guid_count; j++) {

            if (IsEqualGUID(mode->guid, &guid_list[j]))

                break;

        }

        if (j == guid_count)

            continue;

        hr = IDirectXVideoDecoderService_GetDecoderRenderTargets(ctx->decoder_service, mode->guid, &target_count, &target_list);

        if (FAILED(hr)) {

            continue;

        }

        for (j = 0; j < target_count; j++) {

            const D3DFORMAT format = target_list[j];

            if (format == surface_format) {

                target_format = format;

                break;

            }

        }

        CoTaskMemFree(target_list);

        if (target_format) {

            device_guid = *mode->guid;

            break;

        }

    }

    CoTaskMemFree(guid_list);

    if (IsEqualGUID(&device_guid, &GUID_NULL)) {

        av_log(NULL, loglevel, "No decoder device for codec found\n");

        goto fail;

    }

    desc.SampleWidth  = s->coded_width;

    desc.SampleHeight = s->coded_height;

    desc.Format       = target_format;

    ret = dxva2_get_decoder_configuration(s, &device_guid, &desc, &config);

    if (ret < 0) {

        goto fail;

    }

    /* decoding MPEG-2 requires additional alignment on some Intel GPUs,

       but it causes issues for H.264 on certain AMD GPUs..... */

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO)

        surface_alignment = 32;

    /* the HEVC DXVA2 spec asks for 128 pixel aligned surfaces to ensure

       all coding features have enough room to work with */

    else if  (s->codec_id == AV_CODEC_ID_HEVC)

        surface_alignment = 128;

    else

        surface_alignment = 16;

    /* 4 base work surfaces */

    num_surfaces = 4;

    /* add surfaces based on number of possible refs */

    if (s->codec_id == AV_CODEC_ID_H264 || s->codec_id == AV_CODEC_ID_HEVC)

        num_surfaces += 16;

    else if (s->codec_id == AV_CODEC_ID_VP9)

        num_surfaces += 8;

    else

        num_surfaces += 2;

    /* add extra surfaces for frame threading */

    if (s->active_thread_type & FF_THREAD_FRAME)

        num_surfaces += s->thread_count;

    ctx->hw_frames_ctx = av_hwframe_ctx_alloc(ctx->hw_device_ctx);

    if (!ctx->hw_frames_ctx)

        goto fail;

    frames_ctx   = (AVHWFramesContext*)ctx->hw_frames_ctx->data;

    frames_hwctx = frames_ctx->hwctx;

    frames_ctx->format            = AV_PIX_FMT_DXVA2_VLD;

    frames_ctx->sw_format         = (target_format == MKTAG('P','0','1','0') ? AV_PIX_FMT_P010 : AV_PIX_FMT_NV12);

    frames_ctx->width             = FFALIGN(s->coded_width, surface_alignment);

    frames_ctx->height            = FFALIGN(s->coded_height, surface_alignment);

    frames_ctx->initial_pool_size = num_surfaces;

    frames_hwctx->surface_type = DXVA2_VideoDecoderRenderTarget;

    ret = av_hwframe_ctx_init(ctx->hw_frames_ctx);

    if (ret < 0) {

        av_log(NULL, loglevel, "Failed to initialize the HW frames context\n");

        goto fail;

    }

    hr = IDirectXVideoDecoderService_CreateVideoDecoder(ctx->decoder_service, &device_guid,

                                                        &desc, &config, frames_hwctx->surfaces,

                                                        frames_hwctx->nb_surfaces, &frames_hwctx->decoder_to_release);

    if (FAILED(hr)) {

        av_log(NULL, loglevel, "Failed to create DXVA2 video decoder\n");

        goto fail;

    }

    ctx->decoder_guid   = device_guid;

    ctx->decoder_config = config;

    dxva_ctx->cfg           = &ctx->decoder_config;

    dxva_ctx->decoder       = frames_hwctx->decoder_to_release;

    dxva_ctx->surface       = frames_hwctx->surfaces;

    dxva_ctx->surface_count = frames_hwctx->nb_surfaces;

    if (IsEqualGUID(&ctx->decoder_guid, &DXVADDI_Intel_ModeH264_E))

        dxva_ctx->workaround |= FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO;

    return 0;

fail:

    av_buffer_unref(&ctx->hw_frames_ctx);

    return AVERROR(EINVAL);

}


const uint8_t *ff_h263_find_resync_marker(MpegEncContext *s, const uint8_t *av_restrict p, const uint8_t *av_restrict end)

{

    av_assert2(p < end);

    end-=2;

    p++;

    if(s->resync_marker){

        for(;p<end; p+=2){

            if(!*p){

                if     (!p[-1] && p[1]) return p - 1;

                else if(!p[ 1] && p[2]) return p;

            }

        }

    }

    return end+2;

}


static int start_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, ebml_master *master,

                                   unsigned int elementid, uint64_t expectedsize)

{

    int ret;

    if ((ret = avio_open_dyn_buf(dyn_cp)) < 0)

        return ret;

    if (pb->seekable)

        *master = start_ebml_master(pb, elementid, expectedsize);

    else

        *master = start_ebml_master(*dyn_cp, elementid, expectedsize);

    return 0;

}


static int decode_pic_hdr(IVI45DecContext *ctx, AVCodecContext *avctx)

{

    int             pic_size_indx, i, p;

    IVIPicConfig    pic_conf;

    if (get_bits(&ctx->gb, 18) != 0x3FFF8) {

        av_log(avctx, AV_LOG_ERROR, "Invalid picture start code!\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->prev_frame_type = ctx->frame_type;

    ctx->frame_type      = get_bits(&ctx->gb, 3);

    if (ctx->frame_type == 7) {

        av_log(avctx, AV_LOG_ERROR, "Invalid frame type: %d\n", ctx->frame_type);

        return AVERROR_INVALIDDATA;

    }

    if (ctx->frame_type == IVI4_FRAMETYPE_BIDIR)

        ctx->has_b_frames = 1;

    ctx->transp_status = get_bits1(&ctx->gb);

    if (ctx->transp_status) {

        ctx->has_transp = 1;

    }

    /* unknown bit: Mac decoder ignores this bit, XANIM returns error */

    if (get_bits1(&ctx->gb)) {

        av_log(avctx, AV_LOG_ERROR, "Sync bit is set!\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->data_size = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 24) : 0;

    /* null frames don't contain anything else so we just return */

    if (ctx->frame_type >= IVI4_FRAMETYPE_NULL_FIRST) {

        ff_dlog(avctx, "Null frame encountered!\n");

        return 0;

    }

    /* Check key lock status. If enabled - ignore lock word.         */

    /* Usually we have to prompt the user for the password, but      */

    /* we don't do that because Indeo 4 videos can be decoded anyway */

    if (get_bits1(&ctx->gb)) {

        skip_bits_long(&ctx->gb, 32);

        ff_dlog(avctx, "Password-protected clip!\n");

    }

    pic_size_indx = get_bits(&ctx->gb, 3);

    if (pic_size_indx == IVI4_PIC_SIZE_ESC) {

        pic_conf.pic_height = get_bits(&ctx->gb, 16);

        pic_conf.pic_width  = get_bits(&ctx->gb, 16);

    } else {

        pic_conf.pic_height = ivi4_common_pic_sizes[pic_size_indx * 2 + 1];

        pic_conf.pic_width  = ivi4_common_pic_sizes[pic_size_indx * 2    ];

    }

    /* Decode tile dimensions. */

    if (get_bits1(&ctx->gb)) {

        pic_conf.tile_height = scale_tile_size(pic_conf.pic_height, get_bits(&ctx->gb, 4));

        pic_conf.tile_width  = scale_tile_size(pic_conf.pic_width,  get_bits(&ctx->gb, 4));

        ctx->uses_tiling = 1;

    } else {

        pic_conf.tile_height = pic_conf.pic_height;

        pic_conf.tile_width  = pic_conf.pic_width;

    }

    /* Decode chroma subsampling. We support only 4:4 aka YVU9. */

    if (get_bits(&ctx->gb, 2)) {

        av_log(avctx, AV_LOG_ERROR, "Only YVU9 picture format is supported!\n");

        return AVERROR_INVALIDDATA;

    }

    pic_conf.chroma_height = (pic_conf.pic_height + 3) >> 2;

    pic_conf.chroma_width  = (pic_conf.pic_width  + 3) >> 2;

    /* decode subdivision of the planes */

    pic_conf.luma_bands = decode_plane_subdivision(&ctx->gb);

    if (pic_conf.luma_bands)

        pic_conf.chroma_bands = decode_plane_subdivision(&ctx->gb);

    ctx->is_scalable = pic_conf.luma_bands != 1 || pic_conf.chroma_bands != 1;

    if (ctx->is_scalable && (pic_conf.luma_bands != 4 || pic_conf.chroma_bands != 1)) {

        av_log(avctx, AV_LOG_ERROR, "Scalability: unsupported subdivision! Luma bands: %d, chroma bands: %d\n",

               pic_conf.luma_bands, pic_conf.chroma_bands);

        return AVERROR_INVALIDDATA;

    }

    /* check if picture layout was changed and reallocate buffers */

    if (ivi_pic_config_cmp(&pic_conf, &ctx->pic_conf)) {

        if (ff_ivi_init_planes(ctx->planes, &pic_conf, 1)) {

            av_log(avctx, AV_LOG_ERROR, "Couldn't reallocate color planes!\n");

            ctx->pic_conf.luma_bands = 0;

            return AVERROR(ENOMEM);

        }

        ctx->pic_conf = pic_conf;

        /* set default macroblock/block dimensions */

        for (p = 0; p <= 2; p++) {

            for (i = 0; i < (!p ? pic_conf.luma_bands : pic_conf.chroma_bands); i++) {

                ctx->planes[p].bands[i].mb_size  = !p ? (!ctx->is_scalable ? 16 : 8) : 4;

                ctx->planes[p].bands[i].blk_size = !p ? 8 : 4;

            }

        }

        if (ff_ivi_init_tiles(ctx->planes, ctx->pic_conf.tile_width,

                              ctx->pic_conf.tile_height)) {

            av_log(avctx, AV_LOG_ERROR,

                   "Couldn't reallocate internal structures!\n");

            return AVERROR(ENOMEM);

        }

    }

    ctx->frame_num = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 20) : 0;

    /* skip decTimeEst field if present */

    if (get_bits1(&ctx->gb))

        skip_bits(&ctx->gb, 8);

    /* decode macroblock and block huffman codebooks */

    if (ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_MB_HUFF,  &ctx->mb_vlc,  avctx) ||

        ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_BLK_HUFF, &ctx->blk_vlc, avctx))

        return AVERROR_INVALIDDATA;

    ctx->rvmap_sel = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 8;

    ctx->in_imf = get_bits1(&ctx->gb);

    ctx->in_q   = get_bits1(&ctx->gb);

    ctx->pic_glob_quant = get_bits(&ctx->gb, 5);

    /* TODO: ignore this parameter if unused */

    ctx->unknown1 = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 0;

    ctx->checksum = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 16) : 0;

    /* skip picture header extension if any */

    while (get_bits1(&ctx->gb)) {

        ff_dlog(avctx, "Pic hdr extension encountered!\n");

        skip_bits(&ctx->gb, 8);

    }

    if (get_bits1(&ctx->gb)) {

        av_log(avctx, AV_LOG_ERROR, "Bad blocks bits encountered!\n");

    }

    align_get_bits(&ctx->gb);

    return 0;

}


static void decode_finish_row(H264Context *h, H264SliceContext *sl)

{

    int top            = 16 * (h->mb_y      >> FIELD_PICTURE(h));

    int pic_height     = 16 *  h->mb_height >> FIELD_PICTURE(h);

    int height         =  16      << FRAME_MBAFF(h);

    int deblock_border = (16 + 4) << FRAME_MBAFF(h);

    if (h->deblocking_filter) {

        if ((top + height) >= pic_height)

            height += deblock_border;

        top -= deblock_border;

    }

    if (top >= pic_height || (top + height) < 0)

        return;

    height = FFMIN(height, pic_height - top);

    if (top < 0) {

        height = top + height;

        top    = 0;

    }

    ff_h264_draw_horiz_band(h, sl, top, height);

    if (h->droppable)

        return;

    ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,

                              h->picture_structure == PICT_BOTTOM_FIELD);

}


static inline void show_tags(WriterContext *wctx, AVDictionary *tags, int section_id)

{

    AVDictionaryEntry *tag = NULL;

    if (!tags)

        return;

    writer_print_section_header(wctx, section_id);

    while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX)))

        writer_print_string(wctx, tag->key, tag->value, 0);

    writer_print_section_footer(wctx);

}


void qemu_spice_display_update(SimpleSpiceDisplay *ssd,

                               int x, int y, int w, int h)

{

    QXLRect update_area;

    dprint(2, "%s: x %d y %d w %d h %d\n", __FUNCTION__, x, y, w, h);

    update_area.left = x,

    update_area.right = x + w;

    update_area.top = y;

    update_area.bottom = y + h;

    pthread_mutex_lock(&ssd->lock);

    if (qemu_spice_rect_is_empty(&ssd->dirty)) {

        ssd->notify++;

    }

    qemu_spice_rect_union(&ssd->dirty, &update_area);

    pthread_mutex_unlock(&ssd->lock);

}


static void blk_alloc(struct XenDevice *xendev)

{

    struct XenBlkDev *blkdev = container_of(xendev, struct XenBlkDev, xendev);

    LIST_INIT(&blkdev->inflight);

    LIST_INIT(&blkdev->finished);

    LIST_INIT(&blkdev->freelist);

    blkdev->bh = qemu_bh_new(blk_bh, blkdev);

    if (xen_mode != XEN_EMULATE)

        batch_maps = 1;

}


static Suite *qstring_suite(void)

{

    Suite *s;

    TCase *qstring_public_tcase;

    s = suite_create("QString test-suite");

    qstring_public_tcase = tcase_create("Public Interface");

    suite_add_tcase(s, qstring_public_tcase);

    tcase_add_test(qstring_public_tcase, qstring_from_str_test);

    tcase_add_test(qstring_public_tcase, qstring_destroy_test);

    tcase_add_test(qstring_public_tcase, qstring_get_str_test);

    tcase_add_test(qstring_public_tcase, qstring_append_chr_test);

    tcase_add_test(qstring_public_tcase, qstring_from_substr_test);

    tcase_add_test(qstring_public_tcase, qobject_to_qstring_test);

    return s;

}


static inline TranslationBlock *tb_find(CPUState *cpu,

                                        TranslationBlock *last_tb,

                                        int tb_exit)

{

    TranslationBlock *tb;

    target_ulong cs_base, pc;

    uint32_t flags;

    bool acquired_tb_lock = false;

    uint32_t cf_mask = curr_cflags();

    tb = tb_lookup__cpu_state(cpu, &pc, &cs_base, &flags, cf_mask);

    if (tb == NULL) {

        /* mmap_lock is needed by tb_gen_code, and mmap_lock must be

         * taken outside tb_lock. As system emulation is currently

         * single threaded the locks are NOPs.

         */

        mmap_lock();

        tb_lock();

        acquired_tb_lock = true;

        /* There's a chance that our desired tb has been translated while

         * taking the locks so we check again inside the lock.

         */

        tb = tb_htable_lookup(cpu, pc, cs_base, flags, cf_mask);

        if (likely(tb == NULL)) {

            /* if no translated code available, then translate it now */

            tb = tb_gen_code(cpu, pc, cs_base, flags, cf_mask);

        }

        mmap_unlock();

        /* We add the TB in the virtual pc hash table for the fast lookup */

        atomic_set(&cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)], tb);

    }

#ifndef CONFIG_USER_ONLY

    /* We don't take care of direct jumps when address mapping changes in

     * system emulation. So it's not safe to make a direct jump to a TB

     * spanning two pages because the mapping for the second page can change.

     */

    if (tb->page_addr[1] != -1) {

        last_tb = NULL;

    }

#endif

    /* See if we can patch the calling TB. */

    if (last_tb && !qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) {

        if (!acquired_tb_lock) {

            tb_lock();

            acquired_tb_lock = true;

        }

        if (!(tb->cflags & CF_INVALID)) {

            tb_add_jump(last_tb, tb_exit, tb);

        }

    }

    if (acquired_tb_lock) {

        tb_unlock();

    }

    return tb;

}


static VncServerInfo2List *qmp_query_server_entry(QIOChannelSocket *ioc,

                                                  bool websocket,

                                                  int auth,

                                                  int subauth,

                                                  VncServerInfo2List *prev)

{

    VncServerInfo2List *list;

    VncServerInfo2 *info;

    Error *err = NULL;

    SocketAddress *addr;

    addr = qio_channel_socket_get_local_address(ioc, &err);

    if (!addr) {

        error_free(err);

        return prev;

    }

    info = g_new0(VncServerInfo2, 1);

    vnc_init_basic_info(addr, qapi_VncServerInfo2_base(info), &err);

    qapi_free_SocketAddress(addr);

    if (err) {

        qapi_free_VncServerInfo2(info);

        error_free(err);

        return prev;

    }

    info->websocket = websocket;

    qmp_query_auth(auth, subauth, &info->auth,

                   &info->vencrypt, &info->has_vencrypt);

    list = g_new0(VncServerInfo2List, 1);

    list->value = info;

    list->next = prev;

    return list;

}


static void tcx_invalidate_cursor_position(TCXState *s)

{

    int ymin, ymax, start, end;

    /* invalidate only near the cursor */

    ymin = s->cursy;

    if (ymin >= s->height) {

        return;

    }

    ymax = MIN(s->height, ymin + 32);

    start = ymin * 1024;

    end   = ymax * 1024;

    memory_region_set_dirty(&s->vram_mem, start, end-start);

}


static int pxa2xx_timer_init(SysBusDevice *dev)

{

    int i;

    int iomemtype;

    PXA2xxTimerInfo *s;

    qemu_irq irq4;

    s = FROM_SYSBUS(PXA2xxTimerInfo, dev);

    s->irq_enabled = 0;

    s->oldclock = 0;

    s->clock = 0;

    s->lastload = qemu_get_clock(vm_clock);

    s->reset3 = 0;

    for (i = 0; i < 4; i ++) {

        s->timer[i].value = 0;

        sysbus_init_irq(dev, &s->timer[i].irq);

        s->timer[i].info = s;

        s->timer[i].num = i;

        s->timer[i].level = 0;

        s->timer[i].qtimer = qemu_new_timer(vm_clock,

                        pxa2xx_timer_tick, &s->timer[i]);

    }

    if (s->flags & (1 << PXA2XX_TIMER_HAVE_TM4)) {

        sysbus_init_irq(dev, &irq4);

        for (i = 0; i < 8; i ++) {

            s->tm4[i].tm.value = 0;

            s->tm4[i].tm.info = s;

            s->tm4[i].tm.num = i + 4;

            s->tm4[i].tm.level = 0;

            s->tm4[i].freq = 0;

            s->tm4[i].control = 0x0;

            s->tm4[i].tm.qtimer = qemu_new_timer(vm_clock,

                        pxa2xx_timer_tick4, &s->tm4[i]);

            s->tm4[i].tm.irq = irq4;

        }

    }

    iomemtype = cpu_register_io_memory(pxa2xx_timer_readfn,

                    pxa2xx_timer_writefn, s, DEVICE_NATIVE_ENDIAN);

    sysbus_init_mmio(dev, 0x00001000, iomemtype);

    return 0;

}


static void xenfb_mouse_event(void *opaque,

			      int dx, int dy, int dz, int button_state)

{

    struct XenInput *xenfb = opaque;

    DisplaySurface *surface = qemu_console_surface(xenfb->c.con);

    int dw = surface_width(surface);

    int dh = surface_height(surface);

    int i;

    trace_xenfb_mouse_event(opaque, dx, dy, dz, button_state,

                            xenfb->abs_pointer_wanted);

    if (xenfb->abs_pointer_wanted)

	xenfb_send_position(xenfb,

			    dx * (dw - 1) / 0x7fff,

			    dy * (dh - 1) / 0x7fff,

			    dz);

    else

	xenfb_send_motion(xenfb, dx, dy, dz);

    for (i = 0 ; i < 8 ; i++) {

	int lastDown = xenfb->button_state & (1 << i);

	int down = button_state & (1 << i);

	if (down == lastDown)

	    continue;

	if (xenfb_send_key(xenfb, down, BTN_LEFT+i) < 0)

	    return;

    }

    xenfb->button_state = button_state;

}


BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,

                                  const char *child_name,

                                  const BdrvChildRole *child_role,

                                  void *opaque)

{

    BdrvChild *child = g_new(BdrvChild, 1);

    *child = (BdrvChild) {

        .bs     = NULL,

        .name   = g_strdup(child_name),

        .role   = child_role,

        .opaque = opaque,

    };

    bdrv_replace_child(child, child_bs);

    return child;

}


static av_cold int movie_common_init(AVFilterContext *ctx)

{

    MovieContext *movie = ctx->priv;

    AVInputFormat *iformat = NULL;

    int64_t timestamp;

    int nb_streams, ret, i;

    char default_streams[16], *stream_specs, *spec, *cursor;

    char name[16];

    AVStream *st;

    if (!*movie->file_name) {

        av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");

        return AVERROR(EINVAL);

    }

    movie->seek_point = movie->seek_point_d * 1000000 + 0.5;

    stream_specs = movie->stream_specs;

    if (!stream_specs) {

        snprintf(default_streams, sizeof(default_streams), "d%c%d",

                 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',

                 movie->stream_index);

        stream_specs = default_streams;

    }

    for (cursor = stream_specs, nb_streams = 1; *cursor; cursor++)

        if (*cursor == '+')

            nb_streams++;

    if (movie->loop_count != 1 && nb_streams != 1) {

        av_log(ctx, AV_LOG_ERROR,

               "Loop with several streams is currently unsupported\n");

        return AVERROR_PATCHWELCOME;

    }

    av_register_all();

    // Try to find the movie format (container)

    iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;

    movie->format_ctx = NULL;

    if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {

        av_log(ctx, AV_LOG_ERROR,

               "Failed to avformat_open_input '%s'\n", movie->file_name);

        return ret;

    }

    if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)

        av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");

    // if seeking requested, we execute it

    if (movie->seek_point > 0) {

        timestamp = movie->seek_point;

        // add the stream start time, should it exist

        if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {

            if (timestamp > INT64_MAX - movie->format_ctx->start_time) {

                av_log(ctx, AV_LOG_ERROR,

                       "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",

                       movie->file_name, movie->format_ctx->start_time, movie->seek_point);

                return AVERROR(EINVAL);

            }

            timestamp += movie->format_ctx->start_time;

        }

        if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {

            av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",

                   movie->file_name, timestamp);

            return ret;

        }

    }

    for (i = 0; i < movie->format_ctx->nb_streams; i++)

        movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;

    movie->st = av_calloc(nb_streams, sizeof(*movie->st));

    if (!movie->st)

        return AVERROR(ENOMEM);

    for (i = 0; i < nb_streams; i++) {

        spec = av_strtok(stream_specs, "+", &cursor);

        if (!spec)

            return AVERROR_BUG;

        stream_specs = NULL; /* for next strtok */

        st = find_stream(ctx, movie->format_ctx, spec);

        if (!st)

            return AVERROR(EINVAL);

        st->discard = AVDISCARD_DEFAULT;

        movie->st[i].st = st;

        movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);

    }

    if (av_strtok(NULL, "+", &cursor))

        return AVERROR_BUG;

    movie->out_index = av_calloc(movie->max_stream_index + 1,

                                 sizeof(*movie->out_index));

    if (!movie->out_index)

        return AVERROR(ENOMEM);

    for (i = 0; i <= movie->max_stream_index; i++)

        movie->out_index[i] = -1;

    for (i = 0; i < nb_streams; i++)

        movie->out_index[movie->st[i].st->index] = i;

    for (i = 0; i < nb_streams; i++) {

        AVFilterPad pad = { 0 };

        snprintf(name, sizeof(name), "out%d", i);

        pad.type          = movie->st[i].st->codec->codec_type;

        pad.name          = av_strdup(name);

        pad.config_props  = movie_config_output_props;

        pad.request_frame = movie_request_frame;

        ff_insert_outpad(ctx, i, &pad);

        ret = open_stream(ctx, &movie->st[i]);

        if (ret < 0)

            return ret;

        if ( movie->st[i].st->codec->codec->type == AVMEDIA_TYPE_AUDIO &&

            !movie->st[i].st->codec->channel_layout) {

            ret = guess_channel_layout(&movie->st[i], i, ctx);

            if (ret < 0)

                return ret;

        }

    }

    av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",

           movie->seek_point, movie->format_name, movie->file_name,

           movie->stream_index);

    return 0;

}


static ssize_t proxy_llistxattr(FsContext *ctx, V9fsPath *fs_path,

                                void *value, size_t size)

{

    int retval;

    retval = v9fs_request(ctx->private, T_LLISTXATTR, value, "ds", size,

                        fs_path);

    if (retval < 0) {

        errno = -retval;

    }

    return retval;

}


int qemu_paio_read(struct qemu_paiocb *aiocb)

{

    return qemu_paio_submit(aiocb, QEMU_PAIO_READ);

}


static void do_io_interrupt(CPUS390XState *env)

{

    LowCore *lowcore;

    IOIntQueue *q;

    uint8_t isc;

    int disable = 1;

    int found = 0;

    if (!(env->psw.mask & PSW_MASK_IO)) {

        cpu_abort(env, "I/O int w/o I/O mask\n");

    }

    for (isc = 0; isc < ARRAY_SIZE(env->io_index); isc++) {

        if (env->io_index[isc] < 0) {

            continue;

        }

        if (env->io_index[isc] > MAX_IO_QUEUE) {

            cpu_abort(env, "I/O queue overrun for isc %d: %d\n",

                      isc, env->io_index[isc]);

        }

        q = &env->io_queue[env->io_index[isc]][isc];

        if (!(env->cregs[6] & q->word)) {

            disable = 0;

            continue;

        }

        if (!found) {

            uint64_t mask, addr;

            found = 1;

            lowcore = cpu_map_lowcore(env);

            lowcore->subchannel_id = cpu_to_be16(q->id);

            lowcore->subchannel_nr = cpu_to_be16(q->nr);

            lowcore->io_int_parm = cpu_to_be32(q->parm);

            lowcore->io_int_word = cpu_to_be32(q->word);

            lowcore->io_old_psw.mask = cpu_to_be64(get_psw_mask(env));

            lowcore->io_old_psw.addr = cpu_to_be64(env->psw.addr);

            mask = be64_to_cpu(lowcore->io_new_psw.mask);

            addr = be64_to_cpu(lowcore->io_new_psw.addr);

            cpu_unmap_lowcore(lowcore);

            env->io_index[isc]--;

            DPRINTF("%s: %" PRIx64 " %" PRIx64 "\n", __func__,

                    env->psw.mask, env->psw.addr);

            load_psw(env, mask, addr);

        }

        if (env->io_index[isc] >= 0) {

            disable = 0;

        }

        continue;

    }

    if (disable) {

        env->pending_int &= ~INTERRUPT_IO;

    }

}


static int piix3_initfn(PCIDevice *dev)

{

    PIIX3State *d = DO_UPCAST(PIIX3State, dev, dev);

    uint8_t *pci_conf;

    isa_bus_new(&d->dev.qdev);

    pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371SB_0); // 82371SB PIIX3 PCI-to-ISA bridge (Step A1)

    pci_config_set_class(pci_conf, PCI_CLASS_BRIDGE_ISA);

    pci_conf[PCI_HEADER_TYPE] =

        PCI_HEADER_TYPE_NORMAL | PCI_HEADER_TYPE_MULTI_FUNCTION; // header_type = PCI_multifunction, generic

    qemu_register_reset(piix3_reset, d);

    return 0;

}


static bool event_notifier_poll(void *opaque)

{

    EventNotifier *e = opaque;

    AioContext *ctx = container_of(e, AioContext, notifier);

    return atomic_read(&ctx->notified);

}


coroutine_fn iscsi_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,

                                   int nb_sectors, BdrvRequestFlags flags)

{

    IscsiLun *iscsilun = bs->opaque;

    struct IscsiTask iTask;

    uint64_t lba;

    uint32_t nb_blocks;

    if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {

        return -EINVAL;

    }

    if (!(flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->has_write_same) {

        /* WRITE SAME without UNMAP is not supported by the target */

        return -ENOTSUP;

    }

    if ((flags & BDRV_REQ_MAY_UNMAP) && !iscsilun->lbp.lbpws) {

        /* WRITE SAME with UNMAP is not supported by the target */

        return -ENOTSUP;

    }

    lba = sector_qemu2lun(sector_num, iscsilun);

    nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);

    if (iscsilun->zeroblock == NULL) {

        iscsilun->zeroblock = g_malloc0(iscsilun->block_size);

    }

    iscsi_co_init_iscsitask(iscsilun, &iTask);

retry:

    if (iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,

                               iscsilun->zeroblock, iscsilun->block_size,

                               nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),

                               0, 0, iscsi_co_generic_cb, &iTask) == NULL) {

        return -ENOMEM;

    }

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_coroutine_yield();

    }

    if (iTask.status == SCSI_STATUS_CHECK_CONDITION &&

        iTask.task->sense.key == SCSI_SENSE_ILLEGAL_REQUEST &&

        iTask.task->sense.ascq == SCSI_SENSE_ASCQ_INVALID_OPERATION_CODE) {

        /* WRITE SAME is not supported by the target */

        iscsilun->has_write_same = false;

        scsi_free_scsi_task(iTask.task);

        return -ENOTSUP;

    }

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

        iTask.task = NULL;

    }

    if (iTask.do_retry) {

        iTask.complete = 0;

        goto retry;

    }

    if (iTask.status != SCSI_STATUS_GOOD) {

        return -EIO;

    }

    return 0;

}


static size_t fd_getpagesize(int fd)

{

#ifdef CONFIG_LINUX

    struct statfs fs;

    int ret;

    if (fd != -1) {

        do {

            ret = fstatfs(fd, &fs);

        } while (ret != 0 && errno == EINTR);

        if (ret == 0 && fs.f_type == HUGETLBFS_MAGIC) {

            return fs.f_bsize;

        }

    }

#endif

    return getpagesize();

}


static void m5206_mbar_writel(void *opaque, target_phys_addr_t offset,

                              uint32_t value)

{

    m5206_mbar_state *s = (m5206_mbar_state *)opaque;

    int width;

    offset &= 0x3ff;

    if (offset >= 0x200) {

        hw_error("Bad MBAR write offset 0x%x", (int)offset);

    }

    width = m5206_mbar_width[offset >> 2];

    if (width < 4) {

        m5206_mbar_writew(opaque, offset, value >> 16);

        m5206_mbar_writew(opaque, offset + 2, value & 0xffff);

        return;

    }

    m5206_mbar_write(s, offset, value, 4);

}


static QVirtIO9P *qvirtio_9p_pci_init(void)

{

    QVirtIO9P *v9p;

    QVirtioPCIDevice *dev;

    v9p = g_new0(QVirtIO9P, 1);

    v9p->alloc = pc_alloc_init();

    v9p->bus = qpci_init_pc(NULL);

    dev = qvirtio_pci_device_find(v9p->bus, VIRTIO_ID_9P);

    g_assert_nonnull(dev);

    g_assert_cmphex(dev->vdev.device_type, ==, VIRTIO_ID_9P);

    v9p->dev = (QVirtioDevice *) dev;

    qvirtio_pci_device_enable(dev);

    qvirtio_reset(v9p->dev);

    qvirtio_set_acknowledge(v9p->dev);

    qvirtio_set_driver(v9p->dev);

    v9p->vq = qvirtqueue_setup(v9p->dev, v9p->alloc, 0);

    return v9p;

}


void drive_uninit(BlockDriverState *bdrv)

{

    DriveInfo *dinfo;

    TAILQ_FOREACH(dinfo, &drives, next) {

        if (dinfo->bdrv != bdrv)

            continue;

        qemu_opts_del(dinfo->opts);

        TAILQ_REMOVE(&drives, dinfo, next);

        qemu_free(dinfo);

        break;

    }

}


static void qio_dns_resolver_lookup_data_free(gpointer opaque)

{

    struct QIODNSResolverLookupData *data = opaque;

    size_t i;

    qapi_free_SocketAddressLegacy(data->addr);

    for (i = 0; i < data->naddrs; i++) {

        qapi_free_SocketAddressLegacy(data->addrs[i]);

    }

    g_free(data->addrs);

    g_free(data);

}


static void vnc_write(VncState *vs, const void *data, size_t len)

{

    buffer_reserve(&vs->output, len);

    if (buffer_empty(&vs->output)) {

	qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);

    }

    buffer_append(&vs->output, data, len);

}


static void tcx_stip_writel(void *opaque, hwaddr addr,

                            uint64_t val, unsigned size)

{

    TCXState *s = opaque;

    int i;

    uint32_t col;

    if (!(addr & 4)) {

        s->tmpblit = val;

    } else {

        addr = (addr >> 3) & 0xfffff;

        col = cpu_to_be32(s->tmpblit);

        if (s->depth == 24) {

            for (i = 0; i < 32; i++)  {

                if (val & 0x80000000) {

                    s->vram[addr + i] = s->tmpblit;

                    s->vram24[addr + i] = col;

                }

                val <<= 1;

            }

        } else {

            for (i = 0; i < 32; i++)  {

                if (val & 0x80000000) {

                    s->vram[addr + i] = s->tmpblit;

                }

                val <<= 1;

            }

        }

        memory_region_set_dirty(&s->vram_mem, addr, 32);

    }

}


int main(int argc, char *argv[])

{

    const char *sparc_machines[] = { "SPARCbook", "Voyager", "SS-20", NULL };

    const char *sparc64_machines[] = { "sun4u", "sun4v", NULL };

    const char *mac_machines[] = { "mac99", "g3beige", NULL };

    const char *arch = qtest_get_arch();

    g_test_init(&argc, &argv, NULL);

    if (!strcmp(arch, "ppc") || !strcmp(arch, "ppc64")) {

        add_tests(mac_machines);

    } else if (!strcmp(arch, "sparc")) {

        add_tests(sparc_machines);

    } else if (!strcmp(arch, "sparc64")) {

        add_tests(sparc64_machines);

    } else {

        g_assert_not_reached();

    }

    return g_test_run();

}


ram_addr_t qemu_ram_alloc(ram_addr_t size)

{

    RAMBlock *new_block;

#ifdef CONFIG_KQEMU

    if (kqemu_phys_ram_base) {

        return kqemu_ram_alloc(size);

    }

#endif

    size = TARGET_PAGE_ALIGN(size);

    new_block = qemu_malloc(sizeof(*new_block));

    new_block->host = qemu_vmalloc(size);

    new_block->offset = last_ram_offset;

    new_block->length = size;

    new_block->next = ram_blocks;

    ram_blocks = new_block;

    phys_ram_dirty = qemu_realloc(phys_ram_dirty,

        (last_ram_offset + size) >> TARGET_PAGE_BITS);

    memset(phys_ram_dirty + (last_ram_offset >> TARGET_PAGE_BITS),

           0xff, size >> TARGET_PAGE_BITS);

    last_ram_offset += size;

    if (kvm_enabled())

        kvm_setup_guest_memory(new_block->host, size);

    return new_block->offset;

}


static void imx_gpt_write(void *opaque, hwaddr offset, uint64_t value,

                          unsigned size)

{

    IMXGPTState *s = IMX_GPT(opaque);

    uint32_t oldreg;

    uint32_t reg = offset >> 2;

    DPRINTF("(%s, value = 0x%08x)\n", imx_gpt_reg_name(reg),

            (uint32_t)value);

    switch (reg) {

    case 0:

        oldreg = s->cr;

        s->cr = value & ~0x7c14;

        if (s->cr & GPT_CR_SWR) { /* force reset */

            /* handle the reset */

            imx_gpt_reset(DEVICE(s));

        } else {

            /* set our freq, as the source might have changed */

            imx_gpt_set_freq(s);

            if ((oldreg ^ s->cr) & GPT_CR_EN) {

                if (s->cr & GPT_CR_EN) {

                    if (s->cr & GPT_CR_ENMOD) {

                        s->next_timeout = TIMER_MAX;

                        ptimer_set_count(s->timer, TIMER_MAX);

                        imx_gpt_compute_next_timeout(s, false);

                    }

                    ptimer_run(s->timer, 1);

                } else {

                    /* stop timer */

                    ptimer_stop(s->timer);

                }

            }

        }

        break;

    case 1: /* Prescaler */

        s->pr = value & 0xfff;

        imx_gpt_set_freq(s);

        break;

    case 2: /* SR */

        s->sr &= ~(value & 0x3f);

        imx_gpt_update_int(s);

        break;

    case 3: /* IR -- interrupt register */

        s->ir = value & 0x3f;

        imx_gpt_update_int(s);

        imx_gpt_compute_next_timeout(s, false);

        break;

    case 4: /* OCR1 -- output compare register */

        s->ocr1 = value;

        /* In non-freerun mode, reset count when this register is written */

        if (!(s->cr & GPT_CR_FRR)) {

            s->next_timeout = TIMER_MAX;

            ptimer_set_limit(s->timer, TIMER_MAX, 1);

        }

        /* compute the new timeout */

        imx_gpt_compute_next_timeout(s, false);

        break;

    case 5: /* OCR2 -- output compare register */

        s->ocr2 = value;

        /* compute the new timeout */

        imx_gpt_compute_next_timeout(s, false);

        break;

    case 6: /* OCR3 -- output compare register */

        s->ocr3 = value;

        /* compute the new timeout */

        imx_gpt_compute_next_timeout(s, false);

        break;

    default:

        IPRINTF("Bad offset %x\n", reg);

        break;

    }

}


void virtio_blk_data_plane_destroy(VirtIOBlockDataPlane *s)

{

    if (!s) {

        return;

    }

    virtio_blk_data_plane_stop(s);

    g_free(s->batch_notify_vqs);

    qemu_bh_delete(s->bh);

    object_unref(OBJECT(s->iothread));

    g_free(s);

}


int qemu_poll_ns(GPollFD *fds, guint nfds, int64_t timeout)

{

#ifdef CONFIG_PPOLL

    if (timeout < 0) {

        return ppoll((struct pollfd *)fds, nfds, NULL, NULL);

    } else {

        struct timespec ts;

        int64_t tvsec = timeout / 1000000000LL;

        /* Avoid possibly overflowing and specifying a negative number of

         * seconds, which would turn a very long timeout into a busy-wait.

         */

        if (tvsec > (int64_t)INT32_MAX) {

            tvsec = INT32_MAX;

        }

        ts.tv_sec = tvsec;

        ts.tv_nsec = timeout % 1000000000LL;

        return ppoll((struct pollfd *)fds, nfds, &ts, NULL);

    }

#else

    return g_poll(fds, nfds, qemu_timeout_ns_to_ms(timeout));

#endif

}


vreader_get_reader_by_name(const char *name)

{

    VReader *reader = NULL;

    VReaderListEntry *current_entry = NULL;

    vreader_list_lock();

    for (current_entry = vreader_list_get_first(vreader_list); current_entry;

            current_entry = vreader_list_get_next(current_entry)) {

        VReader *creader = vreader_list_get_reader(current_entry);

        if (strcmp(creader->name, name) == 0) {

            reader = creader;

            break;

        }

        vreader_free(creader);

    }

    vreader_list_unlock();

    return reader;

}


static BlockDriverState *get_bs_snapshots(void)

{

    BlockDriverState *bs;

    DriveInfo *dinfo;

    if (bs_snapshots)

        return bs_snapshots;

    TAILQ_FOREACH(dinfo, &drives, next) {

        bs = dinfo->bdrv;

        if (bdrv_can_snapshot(bs))

            goto ok;

    }

    return NULL;

 ok:

    bs_snapshots = bs;

    return bs;

}


static void print_report(const char *op, struct timeval *t, int64_t offset,

                         int64_t count, int64_t total, int cnt, int Cflag)

{

    char s1[64], s2[64], ts[64];

    timestr(t, ts, sizeof(ts), Cflag ? VERBOSE_FIXED_TIME : 0);

    if (!Cflag) {

        cvtstr((double)total, s1, sizeof(s1));

        cvtstr(tdiv((double)total, *t), s2, sizeof(s2));

        printf("%s %"PRId64"/%"PRId64" bytes at offset %" PRId64 "\n",

               op, total, count, offset);

        printf("%s, %d ops; %s (%s/sec and %.4f ops/sec)\n",

               s1, cnt, ts, s2, tdiv((double)cnt, *t));

    } else {/* bytes,ops,time,bytes/sec,ops/sec */

        printf("%"PRId64",%d,%s,%.3f,%.3f\n",

            total, cnt, ts,

            tdiv((double)total, *t),

            tdiv((double)cnt, *t));

    }

}


static int tcp_set_msgfds(CharDriverState *chr, int *fds, int num)

{

    TCPCharDriver *s = chr->opaque;

    /* clear old pending fd array */

    if (s->write_msgfds) {

        g_free(s->write_msgfds);

    }

    if (num) {

        s->write_msgfds = g_malloc(num * sizeof(int));

        memcpy(s->write_msgfds, fds, num * sizeof(int));

    }

    s->write_msgfds_num = num;

    return 0;

}


static av_always_inline int normal_limit(uint8_t *p, ptrdiff_t stride, int E, int I)

{

    LOAD_PIXELS

    return simple_limit(p, stride, E)

        && FFABS(p3-p2) <= I && FFABS(p2-p1) <= I && FFABS(p1-p0) <= I

        && FFABS(q3-q2) <= I && FFABS(q2-q1) <= I && FFABS(q1-q0) <= I;

}


static void nvdimm_build_nfit(GSList *device_list, GArray *table_offsets,

                              GArray *table_data, GArray *linker)

{

    GArray *structures = nvdimm_build_device_structure(device_list);

    unsigned int header;

    acpi_add_table(table_offsets, table_data);

    /* NFIT header. */

    header = table_data->len;

    acpi_data_push(table_data, sizeof(NvdimmNfitHeader));

    /* NVDIMM device structures. */

    g_array_append_vals(table_data, structures->data, structures->len);

    build_header(linker, table_data,

                 (void *)(table_data->data + header), "NFIT",

                 sizeof(NvdimmNfitHeader) + structures->len, 1, NULL, NULL);

    g_array_free(structures, true);

}