static int gif_image_write_header(AVIOContext *pb, int width, int height,

                                  int loop_count, uint32_t *palette)

{

    int i;

    avio_write(pb, "GIF", 3);

    avio_write(pb, "89a", 3);

    avio_wl16(pb, width);

    avio_wl16(pb, height);

    if (palette) {

        avio_w8(pb, 0xf7); /* flags: global clut, 256 entries */

        avio_w8(pb, 0x1f); /* background color index */

        avio_w8(pb, 0);    /* aspect ratio */

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

            const uint32_t v = palette[i] & 0xffffff;

            avio_wb24(pb, v);

        }

    } else {

        avio_w8(pb, 0); /* flags */

        avio_w8(pb, 0); /* background color index */

        avio_w8(pb, 0); /* aspect ratio */

    }

    /* "NETSCAPE EXTENSION" for looped animation GIF */

    avio_w8(pb, 0x21); /* GIF Extension code */

    avio_w8(pb, 0xff); /* Application Extension Label */

    avio_w8(pb, 0x0b); /* Length of Application Block */

    avio_write(pb, "NETSCAPE2.0", sizeof("NETSCAPE2.0") - 1);

    avio_w8(pb, 0x03); /* Length of Data Sub-Block */

    avio_w8(pb, 0x01);

    avio_wl16(pb, (uint16_t)loop_count);

    avio_w8(pb, 0x00); /* Data Sub-block Terminator */

    return 0;

}


static av_cold int omx_encode_init(AVCodecContext *avctx)

{

    OMXCodecContext *s = avctx->priv_data;

    int ret = AVERROR_ENCODER_NOT_FOUND;

    const char *role;

    OMX_BUFFERHEADERTYPE *buffer;

    OMX_ERRORTYPE err;

#if CONFIG_OMX_RPI

    s->input_zerocopy = 1;

#endif

    s->omx_context = omx_init(avctx, s->libname, s->libprefix);

    if (!s->omx_context)

        return AVERROR_ENCODER_NOT_FOUND;

    pthread_mutex_init(&s->state_mutex, NULL);

    pthread_cond_init(&s->state_cond, NULL);

    pthread_mutex_init(&s->input_mutex, NULL);

    pthread_cond_init(&s->input_cond, NULL);

    pthread_mutex_init(&s->output_mutex, NULL);

    pthread_cond_init(&s->output_cond, NULL);

    s->mutex_cond_inited = 1;

    s->avctx = avctx;

    s->state = OMX_StateLoaded;

    s->error = OMX_ErrorNone;

    switch (avctx->codec->id) {

    case AV_CODEC_ID_MPEG4:

        role = "video_encoder.mpeg4";

        break;

    case AV_CODEC_ID_H264:

        role = "video_encoder.avc";

        break;

    default:

        return AVERROR(ENOSYS);

    }

    if ((ret = find_component(s->omx_context, avctx, role, s->component_name, sizeof(s->component_name))) < 0)

        goto fail;

    av_log(avctx, AV_LOG_INFO, "Using %s\n", s->component_name);

    if ((ret = omx_component_init(avctx, role)) < 0)

        goto fail;

    if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {

        while (1) {

            buffer = get_buffer(&s->output_mutex, &s->output_cond,

                                &s->num_done_out_buffers, s->done_out_buffers, 1);

            if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {

                if ((ret = av_reallocp(&avctx->extradata, avctx->extradata_size + buffer->nFilledLen + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {

                    avctx->extradata_size = 0;

                    goto fail;

                }

                memcpy(avctx->extradata + avctx->extradata_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);

                avctx->extradata_size += buffer->nFilledLen;

                memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);

            }

            err = OMX_FillThisBuffer(s->handle, buffer);

            if (err != OMX_ErrorNone) {

                append_buffer(&s->output_mutex, &s->output_cond,

                              &s->num_done_out_buffers, s->done_out_buffers, buffer);

                av_log(avctx, AV_LOG_ERROR, "OMX_FillThisBuffer failed: %x\n", err);

                ret = AVERROR_UNKNOWN;

                goto fail;

            }

            if (avctx->codec->id == AV_CODEC_ID_H264) {

                // For H.264, the extradata can be returned in two separate buffers

                // (the videocore encoder on raspberry pi does this);

                // therefore check that we have got both SPS and PPS before continuing.

                int nals[32] = { 0 };

                int i;

                for (i = 0; i + 4 < avctx->extradata_size; i++) {

                     if (!avctx->extradata[i + 0] &&

                         !avctx->extradata[i + 1] &&

                         !avctx->extradata[i + 2] &&

                         avctx->extradata[i + 3] == 1) {

                         nals[avctx->extradata[i + 4] & 0x1f]++;

                     }

                }

                if (nals[NAL_SPS] && nals[NAL_PPS])

                    break;

            } else {

                if (avctx->extradata_size > 0)

                    break;

            }

        }

    }

    return 0;

fail:

    return ret;

}


static int check_pkt(AVFormatContext *s, AVPacket *pkt)
{
    MOVMuxContext *mov = s->priv_data;
    MOVTrack *trk = &mov->tracks[pkt->stream_index];
    int64_t ref;
    uint64_t duration;
    if (trk->entry) {
        ref = trk->cluster[trk->entry - 1].dts;
    } else if (   trk->start_dts != AV_NOPTS_VALUE
               && !trk->frag_discont) {
        ref = trk->start_dts + trk->track_duration;
    } else
        ref = pkt->dts; // Skip tests for the first packet
    duration = pkt->dts - ref;
    if (pkt->dts < ref || duration >= INT_MAX) {
        av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
            duration, pkt->dts
        );
        pkt->dts = ref + 1;
        pkt->pts = AV_NOPTS_VALUE;
    if (pkt->duration < 0 || pkt->duration > INT_MAX) {
        av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
        return AVERROR(EINVAL);
    return 0;


static int vc9_init_common(VC9Context *v)

{

    static int done = 0;

    int i;

    /* Set the bit planes */

    v->mv_type_mb_plane = (struct BitPlane) { NULL, 0, 0, 0 };

    v->direct_mb_plane = (struct BitPlane) { NULL, 0, 0, 0 };

    v->skip_mb_plane = (struct BitPlane) { NULL, 0, 0, 0 };

#if HAS_ADVANCED_PROFILE

    v->ac_pred_plane = v->over_flags_plane = (struct BitPlane) { NULL, 0, 0, 0 };

    v->hrd_rate = v->hrd_buffer = NULL;

#endif

    /* VLC tables */

#if VLC_NORM6_METH0D == 1

#  if 0 // spec -> actual tables converter

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

        int code= (vc9_norm6_spec[i][1] << vc9_norm6_spec[i][4]) + vc9_norm6_spec[i][3];

        av_log(NULL, AV_LOG_DEBUG, "0x%03X, ", code);

        if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n");

    }

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

        int code= vc9_norm6_spec[i][2] + vc9_norm6_spec[i][4];

        av_log(NULL, AV_LOG_DEBUG, "%2d, ", code);

        if(i%16==15) av_log(NULL, AV_LOG_DEBUG, "\n");

    }

#  endif

#endif

    if(!done)

    {

        done = 1;

        INIT_VLC(&vc9_bfraction_vlc, VC9_BFRACTION_VLC_BITS, 23,

                 vc9_bfraction_bits, 1, 1,

                 vc9_bfraction_codes, 1, 1, 1);

        INIT_VLC(&vc9_norm2_vlc, VC9_NORM2_VLC_BITS, 4,

                 vc9_norm2_bits, 1, 1,

                 vc9_norm2_codes, 1, 1, 1);

#if VLC_NORM6_METH0D == 1

        INIT_VLC(&vc9_norm6_vlc, VC9_NORM6_VLC_BITS, 64,

                 vc9_norm6_bits, 1, 1,

                 vc9_norm6_codes, 2, 2, 1);

#endif

#if VLC_NORM6_METH0D == 2

        INIT_VLC(&vc9_norm6_first_vlc, VC9_NORM6_FIRST_BITS, 24,

                 &vc9_norm6_first[0][1], 1, 1,

                 &vc9_norm6_first[0][0], 1, 1, 1);

        INIT_VLC(&vc9_norm6_second_vlc, VC9_NORM6_SECOND_BITS, 22,

                 &vc9_norm6_second[0][1], 1, 1,

                 &vc9_norm6_second[0][0], 1, 1, 1);

#endif

        INIT_VLC(&vc9_imode_vlc, VC9_IMODE_VLC_BITS, 7,

                 vc9_imode_bits, 1, 1,

                 vc9_imode_codes, 1, 1, 1);

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

        {

            INIT_VLC(&vc9_ttmb_vlc[i], VC9_TTMB_VLC_BITS, 16,

                     vc9_ttmb_bits[i], 1, 1,

                     vc9_ttmb_codes[i], 2, 2, 1);

        }

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

        {

            INIT_VLC(&vc9_4mv_block_pattern_vlc[i], VC9_4MV_BLOCK_PATTERN_VLC_BITS, 16,

                     vc9_4mv_block_pattern_bits[i], 1, 1,

                     vc9_4mv_block_pattern_codes[i], 1, 1, 1);

            INIT_VLC(&vc9_cbpcy_p_vlc[i], VC9_CBPCY_P_VLC_BITS, 64,

                     vc9_cbpcy_p_bits[i], 1, 1,

                     vc9_cbpcy_p_codes[i], 2, 2, 1);

            INIT_VLC(&vc9_mv_diff_vlc[i], VC9_MV_DIFF_VLC_BITS, 73,

                     vc9_mv_diff_bits[i], 1, 1,

                     vc9_mv_diff_codes[i], 2, 2, 1);

        }

    }

    /* Other defaults */

    v->pq = -1;

    v->mvrange = 0; /* 7.1.1.18, p80 */

    return 0;

}


int av_packet_unpack_dictionary(const uint8_t *data, int size, AVDictionary **dict)

{

    const uint8_t *end = data + size;

    int ret = 0;

    if (!dict || !data || !size)

        return ret;

    if (size && end[-1])

        return AVERROR_INVALIDDATA;

    while (data < end) {

        const uint8_t *key = data;

        const uint8_t *val = data + strlen(key) + 1;

        if (val >= end)

            return AVERROR_INVALIDDATA;

        ret = av_dict_set(dict, key, val, 0);

        if (ret < 0)

            break;

        data = val + strlen(val) + 1;

    }

    return ret;

}


void cpu_interrupt(CPUState *env, int mask)

{

#if !defined(USE_NPTL)

    TranslationBlock *tb;

    static spinlock_t interrupt_lock = SPIN_LOCK_UNLOCKED;

#endif

    int old_mask;

    old_mask = env->interrupt_request;

    /* FIXME: This is probably not threadsafe.  A different thread could

       be in the middle of a read-modify-write operation.  */

    env->interrupt_request |= mask;

#if defined(USE_NPTL)

    /* FIXME: TB unchaining isn't SMP safe.  For now just ignore the

       problem and hope the cpu will stop of its own accord.  For userspace

       emulation this often isn't actually as bad as it sounds.  Often

       signals are used primarily to interrupt blocking syscalls.  */

#else

    if (use_icount) {

        env->icount_decr.u16.high = 0xffff;

#ifndef CONFIG_USER_ONLY

        /* CPU_INTERRUPT_EXIT isn't a real interrupt.  It just means

           an async event happened and we need to process it.  */

        if (!can_do_io(env)

            && (mask & ~(old_mask | CPU_INTERRUPT_EXIT)) != 0) {

            cpu_abort(env, "Raised interrupt while not in I/O function");

        }

#endif

    } else {

        tb = env->current_tb;

        /* if the cpu is currently executing code, we must unlink it and

           all the potentially executing TB */

        if (tb && !testandset(&interrupt_lock)) {

            env->current_tb = NULL;

            tb_reset_jump_recursive(tb);

            resetlock(&interrupt_lock);

        }

    }

#endif

}


static always_inline int translate_one (DisasContext *ctx, uint32_t insn)

{

    uint32_t palcode;

    int32_t disp21, disp16, disp12;

    uint16_t fn11, fn16;

    uint8_t opc, ra, rb, rc, sbz, fpfn, fn7, fn2, islit;

    uint8_t lit;

    int ret;

    /* Decode all instruction fields */

    opc = insn >> 26;

    ra = (insn >> 21) & 0x1F;

    rb = (insn >> 16) & 0x1F;

    rc = insn & 0x1F;

    sbz = (insn >> 13) & 0x07;

    islit = (insn >> 12) & 1;

    if (rb == 31 && !islit) {

        islit = 1;

        lit = 0;

    } else

        lit = (insn >> 13) & 0xFF;

    palcode = insn & 0x03FFFFFF;

    disp21 = ((int32_t)((insn & 0x001FFFFF) << 11)) >> 11;

    disp16 = (int16_t)(insn & 0x0000FFFF);

    disp12 = (int32_t)((insn & 0x00000FFF) << 20) >> 20;

    fn16 = insn & 0x0000FFFF;

    fn11 = (insn >> 5) & 0x000007FF;

    fpfn = fn11 & 0x3F;

    fn7 = (insn >> 5) & 0x0000007F;

    fn2 = (insn >> 5) & 0x00000003;

    ret = 0;

#if defined ALPHA_DEBUG_DISAS

    if (logfile != NULL) {

        fprintf(logfile, "opc %02x ra %d rb %d rc %d disp16 %04x\n",

                opc, ra, rb, rc, disp16);

    }

#endif

    switch (opc) {

    case 0x00:

        /* CALL_PAL */

        if (palcode >= 0x80 && palcode < 0xC0) {

            /* Unprivileged PAL call */

            gen_excp(ctx, EXCP_CALL_PAL + ((palcode & 0x1F) << 6), 0);

#if !defined (CONFIG_USER_ONLY)

        } else if (palcode < 0x40) {

            /* Privileged PAL code */

            if (ctx->mem_idx & 1)

                goto invalid_opc;

            else

                gen_excp(ctx, EXCP_CALL_PALP + ((palcode & 0x1F) << 6), 0);

#endif

        } else {

            /* Invalid PAL call */

            goto invalid_opc;

        }

        ret = 3;

        break;

    case 0x01:

        /* OPC01 */

        goto invalid_opc;

    case 0x02:

        /* OPC02 */

        goto invalid_opc;

    case 0x03:

        /* OPC03 */

        goto invalid_opc;

    case 0x04:

        /* OPC04 */

        goto invalid_opc;

    case 0x05:

        /* OPC05 */

        goto invalid_opc;

    case 0x06:

        /* OPC06 */

        goto invalid_opc;

    case 0x07:

        /* OPC07 */

        goto invalid_opc;

    case 0x08:

        /* LDA */

        if (likely(ra != 31)) {

            if (rb != 31)

                tcg_gen_addi_i64(cpu_ir[ra], cpu_ir[rb], disp16);

            else

                tcg_gen_movi_i64(cpu_ir[ra], disp16);

        }

        break;

    case 0x09:

        /* LDAH */

        if (likely(ra != 31)) {

            if (rb != 31)

                tcg_gen_addi_i64(cpu_ir[ra], cpu_ir[rb], disp16 << 16);

            else

                tcg_gen_movi_i64(cpu_ir[ra], disp16 << 16);

        }

        break;

    case 0x0A:

        /* LDBU */

        if (!(ctx->amask & AMASK_BWX))

            goto invalid_opc;

        gen_load_mem(ctx, &tcg_gen_qemu_ld8u, ra, rb, disp16, 0, 0);

        break;

    case 0x0B:

        /* LDQ_U */

        gen_load_mem(ctx, &tcg_gen_qemu_ld64, ra, rb, disp16, 0, 1);

        break;

    case 0x0C:

        /* LDWU */

        if (!(ctx->amask & AMASK_BWX))

            goto invalid_opc;

        gen_load_mem(ctx, &tcg_gen_qemu_ld16u, ra, rb, disp16, 0, 1);

        break;

    case 0x0D:

        /* STW */

        gen_store_mem(ctx, &tcg_gen_qemu_st16, ra, rb, disp16, 0, 0);

        break;

    case 0x0E:

        /* STB */

        gen_store_mem(ctx, &tcg_gen_qemu_st8, ra, rb, disp16, 0, 0);

        break;

    case 0x0F:

        /* STQ_U */

        gen_store_mem(ctx, &tcg_gen_qemu_st64, ra, rb, disp16, 0, 1);

        break;

    case 0x10:

        switch (fn7) {

        case 0x00:

            /* ADDL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit) {

                        tcg_gen_addi_i64(cpu_ir[rc], cpu_ir[ra], lit);

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rc]);

                    } else {

                        tcg_gen_add_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rc]);

                    }

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x02:

            /* S4ADDL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 2);

                    if (islit)

                        tcg_gen_addi_i64(tmp, tmp, lit);

                    else

                        tcg_gen_add_i64(tmp, tmp, cpu_ir[rb]);

                    tcg_gen_ext32s_i64(cpu_ir[rc], tmp);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x09:

            /* SUBL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_subi_i64(cpu_ir[rc], cpu_ir[ra], lit);

                    else

                        tcg_gen_sub_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                    tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rc]);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], -lit);

                    else {

                        tcg_gen_neg_i64(cpu_ir[rc], cpu_ir[rb]);

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rc]);

                }

            }

            break;

        case 0x0B:

            /* S4SUBL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 2);

                    if (islit)

                        tcg_gen_subi_i64(tmp, tmp, lit);

                    else

                        tcg_gen_sub_i64(tmp, tmp, cpu_ir[rb]);

                    tcg_gen_ext32s_i64(cpu_ir[rc], tmp);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], -lit);

                    else {

                        tcg_gen_neg_i64(cpu_ir[rc], cpu_ir[rb]);

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rc]);

                    }

                }

            }

            break;

        case 0x0F:

            /* CMPBGE */

            gen_arith3(helper_cmpbge, ra, rb, rc, islit, lit);

            break;

        case 0x12:

            /* S8ADDL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 3);

                    if (islit)

                        tcg_gen_addi_i64(tmp, tmp, lit);

                    else

                        tcg_gen_add_i64(tmp, tmp, cpu_ir[rb]);

                    tcg_gen_ext32s_i64(cpu_ir[rc], tmp);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x1B:

            /* S8SUBL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 3);

                    if (islit)

                        tcg_gen_subi_i64(tmp, tmp, lit);

                    else

                       tcg_gen_sub_i64(tmp, tmp, cpu_ir[rb]);

                    tcg_gen_ext32s_i64(cpu_ir[rc], tmp);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], -lit);

                    else

                        tcg_gen_neg_i64(cpu_ir[rc], cpu_ir[rb]);

                        tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rc]);

                    }

                }

            }

            break;

        case 0x1D:

            /* CMPULT */

            gen_cmp(TCG_COND_LTU, ra, rb, rc, islit, lit);

            break;

        case 0x20:

            /* ADDQ */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_addi_i64(cpu_ir[rc], cpu_ir[ra], lit);

                    else

                        tcg_gen_add_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_mov_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x22:

            /* S4ADDQ */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 2);

                    if (islit)

                        tcg_gen_addi_i64(cpu_ir[rc], tmp, lit);

                    else

                        tcg_gen_add_i64(cpu_ir[rc], tmp, cpu_ir[rb]);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_mov_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x29:

            /* SUBQ */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_subi_i64(cpu_ir[rc], cpu_ir[ra], lit);

                    else

                        tcg_gen_sub_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], -lit);

                    else

                        tcg_gen_neg_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x2B:

            /* S4SUBQ */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 2);

                    if (islit)

                        tcg_gen_subi_i64(cpu_ir[rc], tmp, lit);

                    else

                        tcg_gen_sub_i64(cpu_ir[rc], tmp, cpu_ir[rb]);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], -lit);

                    else

                        tcg_gen_neg_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x2D:

            /* CMPEQ */

            gen_cmp(TCG_COND_EQ, ra, rb, rc, islit, lit);

            break;

        case 0x32:

            /* S8ADDQ */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 3);

                    if (islit)

                        tcg_gen_addi_i64(cpu_ir[rc], tmp, lit);

                    else

                        tcg_gen_add_i64(cpu_ir[rc], tmp, cpu_ir[rb]);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_mov_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x3B:

            /* S8SUBQ */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

                    tcg_gen_shli_i64(tmp, cpu_ir[ra], 3);

                    if (islit)

                        tcg_gen_subi_i64(cpu_ir[rc], tmp, lit);

                    else

                        tcg_gen_sub_i64(cpu_ir[rc], tmp, cpu_ir[rb]);

                    tcg_temp_free(tmp);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], -lit);

                    else

                        tcg_gen_neg_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x3D:

            /* CMPULE */

            gen_cmp(TCG_COND_LEU, ra, rb, rc, islit, lit);

            break;

        case 0x40:

            /* ADDL/V */

            gen_arith3(helper_addlv, ra, rb, rc, islit, lit);

            break;

        case 0x49:

            /* SUBL/V */

            gen_arith3(helper_sublv, ra, rb, rc, islit, lit);

            break;

        case 0x4D:

            /* CMPLT */

            gen_cmp(TCG_COND_LT, ra, rb, rc, islit, lit);

            break;

        case 0x60:

            /* ADDQ/V */

            gen_arith3(helper_addqv, ra, rb, rc, islit, lit);

            break;

        case 0x69:

            /* SUBQ/V */

            gen_arith3(helper_subqv, ra, rb, rc, islit, lit);

            break;

        case 0x6D:

            /* CMPLE */

            gen_cmp(TCG_COND_LE, ra, rb, rc, islit, lit);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x11:

        switch (fn7) {

        case 0x00:

            /* AND */

            if (likely(rc != 31)) {

                if (ra == 31)

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

                else if (islit)

                    tcg_gen_andi_i64(cpu_ir[rc], cpu_ir[ra], lit);

                else

                    tcg_gen_and_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

            }

            break;

        case 0x08:

            /* BIC */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_andi_i64(cpu_ir[rc], cpu_ir[ra], ~lit);

                    else

                        tcg_gen_andc_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                } else

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

            }

            break;

        case 0x14:

            /* CMOVLBS */

            gen_cmov(TCG_COND_EQ, ra, rb, rc, islit, lit, 1);

            break;

        case 0x16:

            /* CMOVLBC */

            gen_cmov(TCG_COND_NE, ra, rb, rc, islit, lit, 1);

            break;

        case 0x20:

            /* BIS */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_ori_i64(cpu_ir[rc], cpu_ir[ra], lit);

                    else

                        tcg_gen_or_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_mov_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x24:

            /* CMOVEQ */

            gen_cmov(TCG_COND_NE, ra, rb, rc, islit, lit, 0);

            break;

        case 0x26:

            /* CMOVNE */

            gen_cmov(TCG_COND_EQ, ra, rb, rc, islit, lit, 0);

            break;

        case 0x28:

            /* ORNOT */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_ori_i64(cpu_ir[rc], cpu_ir[ra], ~lit);

                    else

                        tcg_gen_orc_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], ~lit);

                    else

                        tcg_gen_not_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x40:

            /* XOR */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_xori_i64(cpu_ir[rc], cpu_ir[ra], lit);

                    else

                        tcg_gen_xor_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], lit);

                    else

                        tcg_gen_mov_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x44:

            /* CMOVLT */

            gen_cmov(TCG_COND_GE, ra, rb, rc, islit, lit, 0);

            break;

        case 0x46:

            /* CMOVGE */

            gen_cmov(TCG_COND_LT, ra, rb, rc, islit, lit, 0);

            break;

        case 0x48:

            /* EQV */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_xori_i64(cpu_ir[rc], cpu_ir[ra], ~lit);

                    else

                        tcg_gen_eqv_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                } else {

                    if (islit)

                        tcg_gen_movi_i64(cpu_ir[rc], ~lit);

                    else

                        tcg_gen_not_i64(cpu_ir[rc], cpu_ir[rb]);

                }

            }

            break;

        case 0x61:

            /* AMASK */

            if (likely(rc != 31)) {

                if (islit)

                    tcg_gen_movi_i64(cpu_ir[rc], helper_amask(lit));

                else

                    tcg_gen_helper_1_1(helper_amask, cpu_ir[rc], cpu_ir[rb]);

            }

            break;

        case 0x64:

            /* CMOVLE */

            gen_cmov(TCG_COND_GT, ra, rb, rc, islit, lit, 0);

            break;

        case 0x66:

            /* CMOVGT */

            gen_cmov(TCG_COND_LE, ra, rb, rc, islit, lit, 0);

            break;

        case 0x6C:

            /* IMPLVER */

            if (rc != 31)

                tcg_gen_helper_1_0(helper_load_implver, cpu_ir[rc]);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x12:

        switch (fn7) {

        case 0x02:

            /* MSKBL */

            gen_arith3(helper_mskbl, ra, rb, rc, islit, lit);

            break;

        case 0x06:

            /* EXTBL */

            gen_ext_l(&tcg_gen_ext8u_i64, ra, rb, rc, islit, lit);

            break;

        case 0x0B:

            /* INSBL */

            gen_arith3(helper_insbl, ra, rb, rc, islit, lit);

            break;

        case 0x12:

            /* MSKWL */

            gen_arith3(helper_mskwl, ra, rb, rc, islit, lit);

            break;

        case 0x16:

            /* EXTWL */

            gen_ext_l(&tcg_gen_ext16u_i64, ra, rb, rc, islit, lit);

            break;

        case 0x1B:

            /* INSWL */

            gen_arith3(helper_inswl, ra, rb, rc, islit, lit);

            break;

        case 0x22:

            /* MSKLL */

            gen_arith3(helper_mskll, ra, rb, rc, islit, lit);

            break;

        case 0x26:

            /* EXTLL */

            gen_ext_l(&tcg_gen_ext32u_i64, ra, rb, rc, islit, lit);

            break;

        case 0x2B:

            /* INSLL */

            gen_arith3(helper_insll, ra, rb, rc, islit, lit);

            break;

        case 0x30:

            /* ZAP */

            gen_arith3(helper_zap, ra, rb, rc, islit, lit);

            break;

        case 0x31:

            /* ZAPNOT */

            gen_arith3(helper_zapnot, ra, rb, rc, islit, lit);

            break;

        case 0x32:

            /* MSKQL */

            gen_arith3(helper_mskql, ra, rb, rc, islit, lit);

            break;

        case 0x34:

            /* SRL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_shri_i64(cpu_ir[rc], cpu_ir[ra], lit & 0x3f);

                    else {

                        TCGv shift = tcg_temp_new(TCG_TYPE_I64);

                        tcg_gen_andi_i64(shift, cpu_ir[rb], 0x3f);

                        tcg_gen_shr_i64(cpu_ir[rc], cpu_ir[ra], shift);

                        tcg_temp_free(shift);

                    }

                } else

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

            }

            break;

        case 0x36:

            /* EXTQL */

            gen_ext_l(NULL, ra, rb, rc, islit, lit);

            break;

        case 0x39:

            /* SLL */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_shli_i64(cpu_ir[rc], cpu_ir[ra], lit & 0x3f);

                    else {

                        TCGv shift = tcg_temp_new(TCG_TYPE_I64);

                        tcg_gen_andi_i64(shift, cpu_ir[rb], 0x3f);

                        tcg_gen_shl_i64(cpu_ir[rc], cpu_ir[ra], shift);

                        tcg_temp_free(shift);

                    }

                } else

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

            }

            break;

        case 0x3B:

            /* INSQL */

            gen_arith3(helper_insql, ra, rb, rc, islit, lit);

            break;

        case 0x3C:

            /* SRA */

            if (likely(rc != 31)) {

                if (ra != 31) {

                    if (islit)

                        tcg_gen_sari_i64(cpu_ir[rc], cpu_ir[ra], lit & 0x3f);

                    else {

                        TCGv shift = tcg_temp_new(TCG_TYPE_I64);

                        tcg_gen_andi_i64(shift, cpu_ir[rb], 0x3f);

                        tcg_gen_sar_i64(cpu_ir[rc], cpu_ir[ra], shift);

                        tcg_temp_free(shift);

                    }

                } else

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

            }

            break;

        case 0x52:

            /* MSKWH */

            gen_arith3(helper_mskwh, ra, rb, rc, islit, lit);

            break;

        case 0x57:

            /* INSWH */

            gen_arith3(helper_inswh, ra, rb, rc, islit, lit);

            break;

        case 0x5A:

            /* EXTWH */

            gen_ext_h(&tcg_gen_ext16u_i64, ra, rb, rc, islit, lit);

            break;

        case 0x62:

            /* MSKLH */

            gen_arith3(helper_msklh, ra, rb, rc, islit, lit);

            break;

        case 0x67:

            /* INSLH */

            gen_arith3(helper_inslh, ra, rb, rc, islit, lit);

            break;

        case 0x6A:

            /* EXTLH */

            gen_ext_h(&tcg_gen_ext16u_i64, ra, rb, rc, islit, lit);

            break;

        case 0x72:

            /* MSKQH */

            gen_arith3(helper_mskqh, ra, rb, rc, islit, lit);

            break;

        case 0x77:

            /* INSQH */

            gen_arith3(helper_insqh, ra, rb, rc, islit, lit);

            break;

        case 0x7A:

            /* EXTQH */

            gen_ext_h(NULL, ra, rb, rc, islit, lit);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x13:

        switch (fn7) {

        case 0x00:

            /* MULL */

            if (likely(rc != 31)) {

                if (ra == 31)

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

                else {

                    if (islit)

                        tcg_gen_muli_i64(cpu_ir[rc], cpu_ir[ra], lit);

                    else

                        tcg_gen_mul_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

                    tcg_gen_ext32s_i64(cpu_ir[rc], cpu_ir[rc]);

                }

            }

            break;

        case 0x20:

            /* MULQ */

            if (likely(rc != 31)) {

                if (ra == 31)

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

                else if (islit)

                    tcg_gen_muli_i64(cpu_ir[rc], cpu_ir[ra], lit);

                else

                    tcg_gen_mul_i64(cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

            }

            break;

        case 0x30:

            /* UMULH */

            gen_arith3(helper_umulh, ra, rb, rc, islit, lit);

            break;

        case 0x40:

            /* MULL/V */

            gen_arith3(helper_mullv, ra, rb, rc, islit, lit);

            break;

        case 0x60:

            /* MULQ/V */

            gen_arith3(helper_mulqv, ra, rb, rc, islit, lit);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x14:

        switch (fpfn) { /* f11 & 0x3F */

        case 0x04:

            /* ITOFS */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I32);

                    tcg_gen_trunc_i64_i32(tmp, cpu_ir[ra]);

                    tcg_gen_helper_1_1(helper_memory_to_s, cpu_fir[rc], tmp);

                    tcg_temp_free(tmp);

                } else

                    tcg_gen_movi_i64(cpu_fir[rc], 0);

            }

            break;

        case 0x0A:

            /* SQRTF */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            gen_farith2(&helper_sqrtf, rb, rc);

            break;

        case 0x0B:

            /* SQRTS */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            gen_farith2(&helper_sqrts, rb, rc);

            break;

        case 0x14:

            /* ITOFF */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (ra != 31) {

                    TCGv tmp = tcg_temp_new(TCG_TYPE_I32);

                    tcg_gen_trunc_i64_i32(tmp, cpu_ir[ra]);

                    tcg_gen_helper_1_1(helper_memory_to_f, cpu_fir[rc], tmp);

                    tcg_temp_free(tmp);

                } else

                    tcg_gen_movi_i64(cpu_fir[rc], 0);

            }

            break;

        case 0x24:

            /* ITOFT */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (ra != 31)

                    tcg_gen_mov_i64(cpu_fir[rc], cpu_ir[ra]);

                else

                    tcg_gen_movi_i64(cpu_fir[rc], 0);

            }

            break;

        case 0x2A:

            /* SQRTG */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            gen_farith2(&helper_sqrtg, rb, rc);

            break;

        case 0x02B:

            /* SQRTT */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            gen_farith2(&helper_sqrtt, rb, rc);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x15:

        /* VAX floating point */

        /* XXX: rounding mode and trap are ignored (!) */

        switch (fpfn) { /* f11 & 0x3F */

        case 0x00:

            /* ADDF */

            gen_farith3(&helper_addf, ra, rb, rc);

            break;

        case 0x01:

            /* SUBF */

            gen_farith3(&helper_subf, ra, rb, rc);

            break;

        case 0x02:

            /* MULF */

            gen_farith3(&helper_mulf, ra, rb, rc);

            break;

        case 0x03:

            /* DIVF */

            gen_farith3(&helper_divf, ra, rb, rc);

            break;

        case 0x1E:

            /* CVTDG */

#if 0 // TODO

            gen_farith2(&helper_cvtdg, rb, rc);

#else

            goto invalid_opc;

#endif

            break;

        case 0x20:

            /* ADDG */

            gen_farith3(&helper_addg, ra, rb, rc);

            break;

        case 0x21:

            /* SUBG */

            gen_farith3(&helper_subg, ra, rb, rc);

            break;

        case 0x22:

            /* MULG */

            gen_farith3(&helper_mulg, ra, rb, rc);

            break;

        case 0x23:

            /* DIVG */

            gen_farith3(&helper_divg, ra, rb, rc);

            break;

        case 0x25:

            /* CMPGEQ */

            gen_farith3(&helper_cmpgeq, ra, rb, rc);

            break;

        case 0x26:

            /* CMPGLT */

            gen_farith3(&helper_cmpglt, ra, rb, rc);

            break;

        case 0x27:

            /* CMPGLE */

            gen_farith3(&helper_cmpgle, ra, rb, rc);

            break;

        case 0x2C:

            /* CVTGF */

            gen_farith2(&helper_cvtgf, rb, rc);

            break;

        case 0x2D:

            /* CVTGD */

#if 0 // TODO

            gen_farith2(ctx, &helper_cvtgd, rb, rc);

#else

            goto invalid_opc;

#endif

            break;

        case 0x2F:

            /* CVTGQ */

            gen_farith2(&helper_cvtgq, rb, rc);

            break;

        case 0x3C:

            /* CVTQF */

            gen_farith2(&helper_cvtqf, rb, rc);

            break;

        case 0x3E:

            /* CVTQG */

            gen_farith2(&helper_cvtqg, rb, rc);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x16:

        /* IEEE floating-point */

        /* XXX: rounding mode and traps are ignored (!) */

        switch (fpfn) { /* f11 & 0x3F */

        case 0x00:

            /* ADDS */

            gen_farith3(&helper_adds, ra, rb, rc);

            break;

        case 0x01:

            /* SUBS */

            gen_farith3(&helper_subs, ra, rb, rc);

            break;

        case 0x02:

            /* MULS */

            gen_farith3(&helper_muls, ra, rb, rc);

            break;

        case 0x03:

            /* DIVS */

            gen_farith3(&helper_divs, ra, rb, rc);

            break;

        case 0x20:

            /* ADDT */

            gen_farith3(&helper_addt, ra, rb, rc);

            break;

        case 0x21:

            /* SUBT */

            gen_farith3(&helper_subt, ra, rb, rc);

            break;

        case 0x22:

            /* MULT */

            gen_farith3(&helper_mult, ra, rb, rc);

            break;

        case 0x23:

            /* DIVT */

            gen_farith3(&helper_divt, ra, rb, rc);

            break;

        case 0x24:

            /* CMPTUN */

            gen_farith3(&helper_cmptun, ra, rb, rc);

            break;

        case 0x25:

            /* CMPTEQ */

            gen_farith3(&helper_cmpteq, ra, rb, rc);

            break;

        case 0x26:

            /* CMPTLT */

            gen_farith3(&helper_cmptlt, ra, rb, rc);

            break;

        case 0x27:

            /* CMPTLE */

            gen_farith3(&helper_cmptle, ra, rb, rc);

            break;

        case 0x2C:

            /* XXX: incorrect */

            if (fn11 == 0x2AC) {

                /* CVTST */

                gen_farith2(&helper_cvtst, rb, rc);

            } else {

                /* CVTTS */

                gen_farith2(&helper_cvtts, rb, rc);

            }

            break;

        case 0x2F:

            /* CVTTQ */

            gen_farith2(&helper_cvttq, rb, rc);

            break;

        case 0x3C:

            /* CVTQS */

            gen_farith2(&helper_cvtqs, rb, rc);

            break;

        case 0x3E:

            /* CVTQT */

            gen_farith2(&helper_cvtqt, rb, rc);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x17:

        switch (fn11) {

        case 0x010:

            /* CVTLQ */

            gen_farith2(&helper_cvtlq, rb, rc);

            break;

        case 0x020:

            if (likely(rc != 31)) {

                if (ra == rb)

                    /* FMOV */

                    tcg_gen_mov_i64(cpu_fir[rc], cpu_fir[ra]);

                else

                    /* CPYS */

                    gen_farith3(&helper_cpys, ra, rb, rc);

            }

            break;

        case 0x021:

            /* CPYSN */

            gen_farith3(&helper_cpysn, ra, rb, rc);

            break;

        case 0x022:

            /* CPYSE */

            gen_farith3(&helper_cpyse, ra, rb, rc);

            break;

        case 0x024:

            /* MT_FPCR */

            if (likely(ra != 31))

                tcg_gen_helper_0_1(helper_store_fpcr, cpu_fir[ra]);

            else {

                TCGv tmp = tcg_const_i64(0);

                tcg_gen_helper_0_1(helper_store_fpcr, tmp);

                tcg_temp_free(tmp);

            }

            break;

        case 0x025:

            /* MF_FPCR */

            if (likely(ra != 31))

                tcg_gen_helper_1_0(helper_load_fpcr, cpu_fir[ra]);

            break;

        case 0x02A:

            /* FCMOVEQ */

            gen_fcmov(&helper_cmpfeq, ra, rb, rc);

            break;

        case 0x02B:

            /* FCMOVNE */

            gen_fcmov(&helper_cmpfne, ra, rb, rc);

            break;

        case 0x02C:

            /* FCMOVLT */

            gen_fcmov(&helper_cmpflt, ra, rb, rc);

            break;

        case 0x02D:

            /* FCMOVGE */

            gen_fcmov(&helper_cmpfge, ra, rb, rc);

            break;

        case 0x02E:

            /* FCMOVLE */

            gen_fcmov(&helper_cmpfle, ra, rb, rc);

            break;

        case 0x02F:

            /* FCMOVGT */

            gen_fcmov(&helper_cmpfgt, ra, rb, rc);

            break;

        case 0x030:

            /* CVTQL */

            gen_farith2(&helper_cvtql, rb, rc);

            break;

        case 0x130:

            /* CVTQL/V */

            gen_farith2(&helper_cvtqlv, rb, rc);

            break;

        case 0x530:

            /* CVTQL/SV */

            gen_farith2(&helper_cvtqlsv, rb, rc);

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x18:

        switch ((uint16_t)disp16) {

        case 0x0000:

            /* TRAPB */

            /* No-op. Just exit from the current tb */

            ret = 2;

            break;

        case 0x0400:

            /* EXCB */

            /* No-op. Just exit from the current tb */

            ret = 2;

            break;

        case 0x4000:

            /* MB */

            /* No-op */

            break;

        case 0x4400:

            /* WMB */

            /* No-op */

            break;

        case 0x8000:

            /* FETCH */

            /* No-op */

            break;

        case 0xA000:

            /* FETCH_M */

            /* No-op */

            break;

        case 0xC000:

            /* RPCC */

            if (ra != 31)

                tcg_gen_helper_1_0(helper_load_pcc, cpu_ir[ra]);

            break;

        case 0xE000:

            /* RC */

            if (ra != 31)

                tcg_gen_helper_1_0(helper_rc, cpu_ir[ra]);

            break;

        case 0xE800:

            /* ECB */

            /* XXX: TODO: evict tb cache at address rb */

#if 0

            ret = 2;

#else

            goto invalid_opc;

#endif

            break;

        case 0xF000:

            /* RS */

            if (ra != 31)

                tcg_gen_helper_1_0(helper_rs, cpu_ir[ra]);

            break;

        case 0xF800:

            /* WH64 */

            /* No-op */

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x19:

        /* HW_MFPR (PALcode) */

#if defined (CONFIG_USER_ONLY)

        goto invalid_opc;

#else

        if (!ctx->pal_mode)

            goto invalid_opc;

        if (ra != 31) {

            TCGv tmp = tcg_const_i32(insn & 0xFF);

            tcg_gen_helper_1_2(helper_mfpr, cpu_ir[ra], tmp, cpu_ir[ra]);

            tcg_temp_free(tmp);

        }

        break;

#endif

    case 0x1A:

        if (ra != 31)

            tcg_gen_movi_i64(cpu_ir[ra], ctx->pc);

        if (rb != 31)

            tcg_gen_andi_i64(cpu_pc, cpu_ir[rb], ~3);

        else

            tcg_gen_movi_i64(cpu_pc, 0);

        /* Those four jumps only differ by the branch prediction hint */

        switch (fn2) {

        case 0x0:

            /* JMP */

            break;

        case 0x1:

            /* JSR */

            break;

        case 0x2:

            /* RET */

            break;

        case 0x3:

            /* JSR_COROUTINE */

            break;

        }

        ret = 1;

        break;

    case 0x1B:

        /* HW_LD (PALcode) */

#if defined (CONFIG_USER_ONLY)

        goto invalid_opc;

#else

        if (!ctx->pal_mode)

            goto invalid_opc;

        if (ra != 31) {

            TCGv addr = tcg_temp_new(TCG_TYPE_I64);

            if (rb != 31)

                tcg_gen_addi_i64(addr, cpu_ir[rb], disp12);

            else

                tcg_gen_movi_i64(addr, disp12);

            switch ((insn >> 12) & 0xF) {

            case 0x0:

                /* Longword physical access */

                tcg_gen_helper_0_2(helper_ldl_raw, cpu_ir[ra], addr);

                break;

            case 0x1:

                /* Quadword physical access */

                tcg_gen_helper_0_2(helper_ldq_raw, cpu_ir[ra], addr);

                break;

            case 0x2:

                /* Longword physical access with lock */

                tcg_gen_helper_0_2(helper_ldl_l_raw, cpu_ir[ra], addr);

                break;

            case 0x3:

                /* Quadword physical access with lock */

                tcg_gen_helper_0_2(helper_ldq_l_raw, cpu_ir[ra], addr);

                break;

            case 0x4:

                /* Longword virtual PTE fetch */

                tcg_gen_helper_0_2(helper_ldl_kernel, cpu_ir[ra], addr);

                break;

            case 0x5:

                /* Quadword virtual PTE fetch */

                tcg_gen_helper_0_2(helper_ldq_kernel, cpu_ir[ra], addr);

                break;

            case 0x6:

                /* Incpu_ir[ra]id */

                goto incpu_ir[ra]id_opc;

            case 0x7:

                /* Incpu_ir[ra]id */

                goto incpu_ir[ra]id_opc;

            case 0x8:

                /* Longword virtual access */

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_ldl_raw, cpu_ir[ra], addr);

                break;

            case 0x9:

                /* Quadword virtual access */

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_ldq_raw, cpu_ir[ra], addr);

                break;

            case 0xA:

                /* Longword virtual access with protection check */

                tcg_gen_qemu_ld32s(cpu_ir[ra], addr, ctx->flags);

                break;

            case 0xB:

                /* Quadword virtual access with protection check */

                tcg_gen_qemu_ld64(cpu_ir[ra], addr, ctx->flags);

                break;

            case 0xC:

                /* Longword virtual access with altenate access mode */

                tcg_gen_helper_0_0(helper_set_alt_mode);

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_ldl_raw, cpu_ir[ra], addr);

                tcg_gen_helper_0_0(helper_restore_mode);

                break;

            case 0xD:

                /* Quadword virtual access with altenate access mode */

                tcg_gen_helper_0_0(helper_set_alt_mode);

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_ldq_raw, cpu_ir[ra], addr);

                tcg_gen_helper_0_0(helper_restore_mode);

                break;

            case 0xE:

                /* Longword virtual access with alternate access mode and

                 * protection checks

                 */

                tcg_gen_helper_0_0(helper_set_alt_mode);

                tcg_gen_helper_0_2(helper_ldl_data, cpu_ir[ra], addr);

                tcg_gen_helper_0_0(helper_restore_mode);

                break;

            case 0xF:

                /* Quadword virtual access with alternate access mode and

                 * protection checks

                 */

                tcg_gen_helper_0_0(helper_set_alt_mode);

                tcg_gen_helper_0_2(helper_ldq_data, cpu_ir[ra], addr);

                tcg_gen_helper_0_0(helper_restore_mode);

                break;

            }

            tcg_temp_free(addr);

        }

        break;

#endif

    case 0x1C:

        switch (fn7) {

        case 0x00:

            /* SEXTB */

            if (!(ctx->amask & AMASK_BWX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (islit)

                    tcg_gen_movi_i64(cpu_ir[rc], (int64_t)((int8_t)lit));

                else

                    tcg_gen_ext8s_i64(cpu_ir[rc], cpu_ir[rb]);

            }

            break;

        case 0x01:

            /* SEXTW */

            if (!(ctx->amask & AMASK_BWX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (islit)

                    tcg_gen_movi_i64(cpu_ir[rc], (int64_t)((int16_t)lit));

                else

                    tcg_gen_ext16s_i64(cpu_ir[rc], cpu_ir[rb]);

            }

            break;

        case 0x30:

            /* CTPOP */

            if (!(ctx->amask & AMASK_CIX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (islit)

                    tcg_gen_movi_i64(cpu_ir[rc], ctpop64(lit));

                else

                    tcg_gen_helper_1_1(helper_ctpop, cpu_ir[rc], cpu_ir[rb]);

            }

            break;

        case 0x31:

            /* PERR */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x32:

            /* CTLZ */

            if (!(ctx->amask & AMASK_CIX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (islit)

                    tcg_gen_movi_i64(cpu_ir[rc], clz64(lit));

                else

                    tcg_gen_helper_1_1(helper_ctlz, cpu_ir[rc], cpu_ir[rb]);

            }

            break;

        case 0x33:

            /* CTTZ */

            if (!(ctx->amask & AMASK_CIX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (islit)

                    tcg_gen_movi_i64(cpu_ir[rc], ctz64(lit));

                else

                    tcg_gen_helper_1_1(helper_cttz, cpu_ir[rc], cpu_ir[rb]);

            }

            break;

        case 0x34:

            /* UNPKBW */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x35:

            /* UNPKWL */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x36:

            /* PKWB */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x37:

            /* PKLB */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x38:

            /* MINSB8 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x39:

            /* MINSW4 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x3A:

            /* MINUB8 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x3B:

            /* MINUW4 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x3C:

            /* MAXUB8 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x3D:

            /* MAXUW4 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x3E:

            /* MAXSB8 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x3F:

            /* MAXSW4 */

            if (!(ctx->amask & AMASK_MVI))

                goto invalid_opc;

            /* XXX: TODO */

            goto invalid_opc;

            break;

        case 0x70:

            /* FTOIT */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            if (likely(rc != 31)) {

                if (ra != 31)

                    tcg_gen_mov_i64(cpu_ir[rc], cpu_fir[ra]);

                else

                    tcg_gen_movi_i64(cpu_ir[rc], 0);

            }

            break;

        case 0x78:

            /* FTOIS */

            if (!(ctx->amask & AMASK_FIX))

                goto invalid_opc;

            if (rc != 31) {

                TCGv tmp1 = tcg_temp_new(TCG_TYPE_I32);

                if (ra != 31)

                    tcg_gen_helper_1_1(helper_s_to_memory, tmp1, cpu_fir[ra]);

                else {

                    TCGv tmp2 = tcg_const_i64(0);

                    tcg_gen_helper_1_1(helper_s_to_memory, tmp1, tmp2);

                    tcg_temp_free(tmp2);

                }

                tcg_gen_ext_i32_i64(cpu_ir[rc], tmp1);

                tcg_temp_free(tmp1);

            }

            break;

        default:

            goto invalid_opc;

        }

        break;

    case 0x1D:

        /* HW_MTPR (PALcode) */

#if defined (CONFIG_USER_ONLY)

        goto invalid_opc;

#else

        if (!ctx->pal_mode)

            goto invalid_opc;

        else {

            TCGv tmp1 = tcg_const_i32(insn & 0xFF);

            if (ra != 31)

                tcg_gen_helper(helper_mtpr, tmp1, cpu_ir[ra]);

            else {

                TCGv tmp2 = tcg_const_i64(0);

                tcg_gen_helper(helper_mtpr, tmp1, tmp2);

                tcg_temp_free(tmp2);

            }

            tcg_temp_free(tmp1);

            ret = 2;

        }

        break;

#endif

    case 0x1E:

        /* HW_REI (PALcode) */

#if defined (CONFIG_USER_ONLY)

        goto invalid_opc;

#else

        if (!ctx->pal_mode)

            goto invalid_opc;

        if (rb == 31) {

            /* "Old" alpha */

            tcg_gen_helper_0_0(helper_hw_rei);

        } else {

            TCGv tmp;

            if (ra != 31) {

                tmp = tcg_temp_new(TCG_TYPE_I64);

                tcg_gen_addi_i64(tmp, cpu_ir[rb], (((int64_t)insn << 51) >> 51));

            } else

                tmp = tcg_const_i64(((int64_t)insn << 51) >> 51);

            tcg_gen_helper_0_1(helper_hw_ret, tmp);

            tcg_temp_free(tmp);

        }

        ret = 2;

        break;

#endif

    case 0x1F:

        /* HW_ST (PALcode) */

#if defined (CONFIG_USER_ONLY)

        goto invalid_opc;

#else

        if (!ctx->pal_mode)

            goto invalid_opc;

        else {

            TCGv addr, val;

            addr = tcg_temp_new(TCG_TYPE_I64);

            if (rb != 31)

                tcg_gen_addi_i64(addr, cpu_ir[rb], disp12);

            else

                tcg_gen_movi_i64(addr, disp12);

            if (ra != 31)

                val = cpu_ir[ra];

            else {

                val = tcg_temp_new(TCG_TYPE_I64);

                tcg_gen_movi_i64(val, 0);

            }

            switch ((insn >> 12) & 0xF) {

            case 0x0:

                /* Longword physical access */

                tcg_gen_helper_0_2(helper_stl_raw, val, addr);

                break;

            case 0x1:

                /* Quadword physical access */

                tcg_gen_helper_0_2(helper_stq_raw, val, addr);

                break;

            case 0x2:

                /* Longword physical access with lock */

                tcg_gen_helper_1_2(helper_stl_c_raw, val, val, addr);

                break;

            case 0x3:

                /* Quadword physical access with lock */

                tcg_gen_helper_1_2(helper_stq_c_raw, val, val, addr);

                break;

            case 0x4:

                /* Longword virtual access */

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_stl_raw, val, addr);

                break;

            case 0x5:

                /* Quadword virtual access */

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_stq_raw, val, addr);

                break;

            case 0x6:

                /* Invalid */

                goto invalid_opc;

            case 0x7:

                /* Invalid */

                goto invalid_opc;

            case 0x8:

                /* Invalid */

                goto invalid_opc;

            case 0x9:

                /* Invalid */

                goto invalid_opc;

            case 0xA:

                /* Invalid */

                goto invalid_opc;

            case 0xB:

                /* Invalid */

                goto invalid_opc;

            case 0xC:

                /* Longword virtual access with alternate access mode */

                tcg_gen_helper_0_0(helper_set_alt_mode);

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_stl_raw, val, addr);

                tcg_gen_helper_0_0(helper_restore_mode);

                break;

            case 0xD:

                /* Quadword virtual access with alternate access mode */

                tcg_gen_helper_0_0(helper_set_alt_mode);

                tcg_gen_helper_1_1(helper_st_virt_to_phys, addr, addr);

                tcg_gen_helper_0_2(helper_stl_raw, val, addr);

                tcg_gen_helper_0_0(helper_restore_mode);

                break;

            case 0xE:

                /* Invalid */

                goto invalid_opc;

            case 0xF:

                /* Invalid */

                goto invalid_opc;

            }

            if (ra != 31)

                tcg_temp_free(val);

            tcg_temp_free(addr);

        }

        ret = 2;

        break;

#endif

    case 0x20:

        /* LDF */

        gen_load_mem(ctx, &gen_qemu_ldf, ra, rb, disp16, 1, 0);

        break;

    case 0x21:

        /* LDG */

        gen_load_mem(ctx, &gen_qemu_ldg, ra, rb, disp16, 1, 0);

        break;

    case 0x22:

        /* LDS */

        gen_load_mem(ctx, &gen_qemu_lds, ra, rb, disp16, 1, 0);

        break;

    case 0x23:

        /* LDT */

        gen_load_mem(ctx, &tcg_gen_qemu_ld64, ra, rb, disp16, 1, 0);

        break;

    case 0x24:

        /* STF */

        gen_store_mem(ctx, &gen_qemu_stf, ra, rb, disp16, 1, 0);

        break;

    case 0x25:

        /* STG */

        gen_store_mem(ctx, &gen_qemu_stg, ra, rb, disp16, 1, 0);

        break;

    case 0x26:

        /* STS */

        gen_store_mem(ctx, &gen_qemu_sts, ra, rb, disp16, 1, 0);

        break;

    case 0x27:

        /* STT */

        gen_store_mem(ctx, &tcg_gen_qemu_st64, ra, rb, disp16, 1, 0);

        break;

    case 0x28:

        /* LDL */

        gen_load_mem(ctx, &tcg_gen_qemu_ld32s, ra, rb, disp16, 0, 0);

        break;

    case 0x29:

        /* LDQ */

        gen_load_mem(ctx, &tcg_gen_qemu_ld64, ra, rb, disp16, 0, 0);

        break;

    case 0x2A:

        /* LDL_L */

        gen_load_mem(ctx, &gen_qemu_ldl_l, ra, rb, disp16, 0, 0);

        break;

    case 0x2B:

        /* LDQ_L */

        gen_load_mem(ctx, &gen_qemu_ldq_l, ra, rb, disp16, 0, 0);

        break;

    case 0x2C:

        /* STL */

        gen_store_mem(ctx, &tcg_gen_qemu_st32, ra, rb, disp16, 0, 0);

        break;

    case 0x2D:

        /* STQ */

        gen_store_mem(ctx, &tcg_gen_qemu_st64, ra, rb, disp16, 0, 0);

        break;

    case 0x2E:

        /* STL_C */

        gen_store_mem(ctx, &gen_qemu_stl_c, ra, rb, disp16, 0, 0);

        break;

    case 0x2F:

        /* STQ_C */

        gen_store_mem(ctx, &gen_qemu_stq_c, ra, rb, disp16, 0, 0);

        break;

    case 0x30:

        /* BR */

        if (ra != 31)

            tcg_gen_movi_i64(cpu_ir[ra], ctx->pc);

        tcg_gen_movi_i64(cpu_pc, ctx->pc + (int64_t)(disp21 << 2));

        ret = 1;

        break;

    case 0x31:

        /* FBEQ */

        gen_fbcond(ctx, &helper_cmpfeq, ra, disp16);

        ret = 1;

        break;

    case 0x32:

        /* FBLT */

        gen_fbcond(ctx, &helper_cmpflt, ra, disp16);

        ret = 1;

        break;

    case 0x33:

        /* FBLE */

        gen_fbcond(ctx, &helper_cmpfle, ra, disp16);

        ret = 1;

        break;

    case 0x34:

        /* BSR */

        if (ra != 31)

            tcg_gen_movi_i64(cpu_ir[ra], ctx->pc);

        tcg_gen_movi_i64(cpu_pc, ctx->pc + (int64_t)(disp21 << 2));

        ret = 1;

        break;

    case 0x35:

        /* FBNE */

        gen_fbcond(ctx, &helper_cmpfne, ra, disp16);

        ret = 1;

        break;

    case 0x36:

        /* FBGE */

        gen_fbcond(ctx, &helper_cmpfge, ra, disp16);

        ret = 1;

        break;

    case 0x37:

        /* FBGT */

        gen_fbcond(ctx, &helper_cmpfgt, ra, disp16);

        ret = 1;

        break;

    case 0x38:

        /* BLBC */

        gen_bcond(ctx, TCG_COND_EQ, ra, disp16, 1);

        ret = 1;

        break;

    case 0x39:

        /* BEQ */

        gen_bcond(ctx, TCG_COND_EQ, ra, disp16, 0);

        ret = 1;

        break;

    case 0x3A:

        /* BLT */

        gen_bcond(ctx, TCG_COND_LT, ra, disp16, 0);

        ret = 1;

        break;

    case 0x3B:

        /* BLE */

        gen_bcond(ctx, TCG_COND_LE, ra, disp16, 0);

        ret = 1;

        break;

    case 0x3C:

        /* BLBS */

        gen_bcond(ctx, TCG_COND_NE, ra, disp16, 1);

        ret = 1;

        break;

    case 0x3D:

        /* BNE */

        gen_bcond(ctx, TCG_COND_NE, ra, disp16, 0);

        ret = 1;

        break;

    case 0x3E:

        /* BGE */

        gen_bcond(ctx, TCG_COND_GE, ra, disp16, 0);

        ret = 1;

        break;

    case 0x3F:

        /* BGT */

        gen_bcond(ctx, TCG_COND_GT, ra, disp16, 0);

        ret = 1;

        break;

    invalid_opc:

        gen_invalid(ctx);

        ret = 3;

        break;

    }

    return ret;

}


void ff_aac_search_for_is(AACEncContext *s, AVCodecContext *avctx, ChannelElement *cpe)

{

    SingleChannelElement *sce0 = &cpe->ch[0];

    SingleChannelElement *sce1 = &cpe->ch[1];

    int start = 0, count = 0, w, w2, g, i;

    const float freq_mult = avctx->sample_rate/(1024.0f/sce0->ics.num_windows)/2.0f;

    if (!cpe->common_window)

        return;

    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {

        start = 0;

        for (g = 0;  g < sce0->ics.num_swb; g++) {

            if (start*freq_mult > INT_STEREO_LOW_LIMIT*(s->lambda/170.0f) &&

                cpe->ch[0].band_type[w*16+g] != NOISE_BT && !cpe->ch[0].zeroes[w*16+g] &&

                cpe->ch[1].band_type[w*16+g] != NOISE_BT && !cpe->ch[1].zeroes[w*16+g]) {

                float ener0 = 0.0f, ener1 = 0.0f, ener01 = 0.0f;

                struct AACISError ph_err1, ph_err2, *erf;

                if (sce0->band_type[w*16+g] == NOISE_BT ||

                    sce1->band_type[w*16+g] == NOISE_BT) {

                    start += sce0->ics.swb_sizes[g];

                    continue;

                }

                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {

                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {

                        float coef0 = fabsf(sce0->pcoeffs[start+(w+w2)*128+i]);

                        float coef1 = fabsf(sce1->pcoeffs[start+(w+w2)*128+i]);

                        ener0  += coef0*coef0;

                        ener1  += coef1*coef1;

                        ener01 += (coef0 + coef1)*(coef0 + coef1);

                    }

                }

                ph_err1 = ff_aac_is_encoding_err(s, cpe, start, w, g,

                                                 ener0, ener1, ener01, 0, -1);

                ph_err2 = ff_aac_is_encoding_err(s, cpe, start, w, g,

                                                 ener0, ener1, ener01, 0, +1);

                erf = ph_err1.error < ph_err2.error ? &ph_err1 : &ph_err2;

                if (erf->pass) {

                    cpe->is_mask[w*16+g] = 1;

                    cpe->ch[0].is_ener[w*16+g] = sqrt(ener0/ener01);

                    cpe->ch[1].is_ener[w*16+g] = ener0/ener1;

                    cpe->ch[1].band_type[w*16+g] = erf->phase ? INTENSITY_BT : INTENSITY_BT2;

                    count++;

                }

            }

            start += sce0->ics.swb_sizes[g];

        }

    }

    cpe->is_mode = !!count;

}


static int yuv4_write_header(AVFormatContext *s)
{
    int* first_pkt = s->priv_data;
    if (s->nb_streams != 1)
        return AVERROR(EIO);
    if (s->streams[0]->codec->pix_fmt == PIX_FMT_YUV411P) {
        av_log(s, AV_LOG_ERROR, "Warning: generating rarely used 4:1:1 YUV stream, some mjpegtools might not work.\n");
    else if ((s->streams[0]->codec->pix_fmt != PIX_FMT_YUV420P) &&
             (s->streams[0]->codec->pix_fmt != PIX_FMT_YUV422P) &&
             (s->streams[0]->codec->pix_fmt != PIX_FMT_GRAY8) &&
             (s->streams[0]->codec->pix_fmt != PIX_FMT_YUV444P)) {
        av_log(s, AV_LOG_ERROR, "ERROR: yuv4mpeg only handles yuv444p, yuv422p, yuv420p, yuv411p and gray pixel formats. Use -pix_fmt to select one.\n");
        return AVERROR(EIO);
    *first_pkt = 1;
    return 0;


static void vmmouse_class_initfn(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = vmmouse_realizefn;

    dc->no_user = 1;

    dc->reset = vmmouse_reset;

    dc->vmsd = &vmstate_vmmouse;

    dc->props = vmmouse_properties;

}


static inline void array_free(array_t* array)

{

    if(array->pointer)

        free(array->pointer);

    array->size=array->next=0;

}


int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx, target_ulong eaddr,

                         int rw, int access_type)

{

    int ret;

#if 0

    qemu_log("%s\n", __func__);

#endif

    if ((access_type == ACCESS_CODE && msr_ir == 0) ||

        (access_type != ACCESS_CODE && msr_dr == 0)) {

        if (env->mmu_model == POWERPC_MMU_BOOKE) {

            /* The BookE MMU always performs address translation. The

               IS and DS bits only affect the address space.  */

            ret = mmubooke_get_physical_address(env, ctx, eaddr,

                                                rw, access_type);

        } else if (env->mmu_model == POWERPC_MMU_BOOKE206) {

            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,

                                                   access_type);

        } else {

            /* No address translation.  */

            ret = check_physical(env, ctx, eaddr, rw);

        }

    } else {

        ret = -1;

        switch (env->mmu_model) {

        case POWERPC_MMU_32B:

        case POWERPC_MMU_601:

        case POWERPC_MMU_SOFT_6xx:

        case POWERPC_MMU_SOFT_74xx:

            /* Try to find a BAT */

            if (env->nb_BATs != 0) {

                ret = get_bat(env, ctx, eaddr, rw, access_type);

            }

#if defined(TARGET_PPC64)

        case POWERPC_MMU_620:

        case POWERPC_MMU_64B:

        case POWERPC_MMU_2_06:

#endif

            if (ret < 0) {

                /* We didn't match any BAT entry or don't have BATs */

                ret = get_segment(env, ctx, eaddr, rw, access_type);

            }

            break;

        case POWERPC_MMU_SOFT_4xx:

        case POWERPC_MMU_SOFT_4xx_Z:

            ret = mmu40x_get_physical_address(env, ctx, eaddr,

                                              rw, access_type);

            break;

        case POWERPC_MMU_BOOKE:

            ret = mmubooke_get_physical_address(env, ctx, eaddr,

                                                rw, access_type);

            break;

        case POWERPC_MMU_BOOKE206:

            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,

                                               access_type);

            break;

        case POWERPC_MMU_MPC8xx:

            /* XXX: TODO */

            cpu_abort(env, "MPC8xx MMU model is not implemented\n");

            break;

        case POWERPC_MMU_REAL:

            cpu_abort(env, "PowerPC in real mode do not do any translation\n");

            return -1;

        default:

            cpu_abort(env, "Unknown or invalid MMU model\n");

            return -1;

        }

    }

#if 0

    qemu_log("%s address " TARGET_FMT_lx " => %d " TARGET_FMT_plx "\n",

             __func__, eaddr, ret, ctx->raddr);

#endif

    return ret;

}


static int vaapi_mpeg4_start_frame(AVCodecContext *avctx, av_unused const uint8_t *buffer, av_unused uint32_t size)

{

    Mpeg4DecContext *ctx = avctx->priv_data;

    MpegEncContext * const s = &ctx->m;

    struct vaapi_context * const vactx = avctx->hwaccel_context;

    VAPictureParameterBufferMPEG4 *pic_param;

    VAIQMatrixBufferMPEG4 *iq_matrix;

    int i;

    av_dlog(avctx, "vaapi_mpeg4_start_frame()\n");

    vactx->slice_param_size = sizeof(VASliceParameterBufferMPEG4);

    /* Fill in VAPictureParameterBufferMPEG4 */

    pic_param = ff_vaapi_alloc_pic_param(vactx, sizeof(VAPictureParameterBufferMPEG4));

    if (!pic_param)

        return -1;

    pic_param->vop_width                                = s->width;

    pic_param->vop_height                               = s->height;

    pic_param->forward_reference_picture                = VA_INVALID_ID;

    pic_param->backward_reference_picture               = VA_INVALID_ID;

    pic_param->vol_fields.value                         = 0; /* reset all bits */

    pic_param->vol_fields.bits.short_video_header       = avctx->codec->id == AV_CODEC_ID_H263;

    pic_param->vol_fields.bits.chroma_format            = CHROMA_420;

    pic_param->vol_fields.bits.interlaced               = !s->progressive_sequence;

    pic_param->vol_fields.bits.obmc_disable             = 1;

    pic_param->vol_fields.bits.sprite_enable            = ctx->vol_sprite_usage;

    pic_param->vol_fields.bits.sprite_warping_accuracy  = s->sprite_warping_accuracy;

    pic_param->vol_fields.bits.quant_type               = s->mpeg_quant;

    pic_param->vol_fields.bits.quarter_sample           = s->quarter_sample;

    pic_param->vol_fields.bits.data_partitioned         = s->data_partitioning;

    pic_param->vol_fields.bits.reversible_vlc           = ctx->rvlc;

    pic_param->vol_fields.bits.resync_marker_disable    = !ctx->resync_marker;

    pic_param->no_of_sprite_warping_points              = ctx->num_sprite_warping_points;

    for (i = 0; i < ctx->num_sprite_warping_points && i < 3; i++) {

        pic_param->sprite_trajectory_du[i]              = ctx->sprite_traj[i][0];

        pic_param->sprite_trajectory_dv[i]              = ctx->sprite_traj[i][1];

    }

    pic_param->quant_precision                          = s->quant_precision;

    pic_param->vop_fields.value                         = 0; /* reset all bits */

    pic_param->vop_fields.bits.vop_coding_type          = s->pict_type - AV_PICTURE_TYPE_I;

    pic_param->vop_fields.bits.backward_reference_vop_coding_type = s->pict_type == AV_PICTURE_TYPE_B ? s->next_picture.f.pict_type - AV_PICTURE_TYPE_I : 0;

    pic_param->vop_fields.bits.vop_rounding_type        = s->no_rounding;

    pic_param->vop_fields.bits.intra_dc_vlc_thr         = mpeg4_get_intra_dc_vlc_thr(ctx);

    pic_param->vop_fields.bits.top_field_first          = s->top_field_first;

    pic_param->vop_fields.bits.alternate_vertical_scan_flag = s->alternate_scan;

    pic_param->vop_fcode_forward                        = s->f_code;

    pic_param->vop_fcode_backward                       = s->b_code;

    pic_param->vop_time_increment_resolution            = avctx->time_base.den;

    pic_param->num_macroblocks_in_gob                   = s->mb_width * ff_h263_get_gob_height(s);

    pic_param->num_gobs_in_vop                          = (s->mb_width * s->mb_height) / pic_param->num_macroblocks_in_gob;

    pic_param->TRB                                      = s->pb_time;

    pic_param->TRD                                      = s->pp_time;

    if (s->pict_type == AV_PICTURE_TYPE_B)

        pic_param->backward_reference_picture = ff_vaapi_get_surface_id(&s->next_picture.f);

    if (s->pict_type != AV_PICTURE_TYPE_I)

        pic_param->forward_reference_picture  = ff_vaapi_get_surface_id(&s->last_picture.f);

    /* Fill in VAIQMatrixBufferMPEG4 */

    /* Only the first inverse quantisation method uses the weighting matrices */

    if (pic_param->vol_fields.bits.quant_type) {

        iq_matrix = ff_vaapi_alloc_iq_matrix(vactx, sizeof(VAIQMatrixBufferMPEG4));

        if (!iq_matrix)

            return -1;

        iq_matrix->load_intra_quant_mat         = 1;

        iq_matrix->load_non_intra_quant_mat     = 1;

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

            int n = s->dsp.idct_permutation[ff_zigzag_direct[i]];

            iq_matrix->intra_quant_mat[i]       = s->intra_matrix[n];

            iq_matrix->non_intra_quant_mat[i]   = s->inter_matrix[n];

        }

    }

    return 0;

}


static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, int16_t *block, int n)

{

    int level, dc, diff, j, run;

    int component;

    RLTable *rl;

    uint8_t * scantable = s->intra_scantable.permutated;

    const uint16_t *quant_matrix;

    const int qscale = s->qscale;

    /* DC coefficient */

    if (n < 4) {

        quant_matrix = s->intra_matrix;

        component = 0;

    } else {

        quant_matrix = s->chroma_intra_matrix;

        component = (n & 1) + 1;

    }

    diff = decode_dc(&s->gb, component);

    if (diff >= 0xffff)

        return -1;

    dc = s->last_dc[component];

    dc += diff;

    s->last_dc[component] = dc;

    block[0] = dc << (3 - s->intra_dc_precision);

    if (s->intra_vlc_format)

        rl = &ff_rl_mpeg2;

    else

        rl = &ff_rl_mpeg1;

    {

        OPEN_READER(re, &s->gb);

        /* now quantify & encode AC coefficients */

        for (;;) {

            UPDATE_CACHE(re, &s->gb);

            GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);

            if (level == 127) {

                break;

            } else if (level != 0) {

                scantable += run;

                j = *scantable;

                level = (level * qscale * quant_matrix[j]) >> 4;

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

            } else {

                /* escape */

                run = SHOW_UBITS(re, &s->gb, 6) + 1; LAST_SKIP_BITS(re, &s->gb, 6);

                UPDATE_CACHE(re, &s->gb);

                level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);

                scantable += run;

                j = *scantable;

                if (level < 0) {

                    level = (-level * qscale * quant_matrix[j]) >> 4;

                    level = -level;

                } else {

                    level = (level * qscale * quant_matrix[j]) >> 4;

                }

            }

            block[j] = level;

        }

        CLOSE_READER(re, &s->gb);

    }

    s->block_last_index[n] = scantable - s->intra_scantable.permutated;

    return 0;

}


target_phys_addr_t cpu_get_phys_page_debug (CPUState *env, target_ulong addr)

{

    mmu_ctx_t ctx;

    if (unlikely(get_physical_address(env, &ctx, addr, 0, ACCESS_INT, 1) != 0))

        return -1;

    return ctx.raddr & TARGET_PAGE_MASK;

}


static unsigned tget_long(const uint8_t **p, int le)

{

    unsigned v = le ? AV_RL32(*p) : AV_RB32(*p);

    *p += 4;

    return v;

}


static unsigned int dec_move_r(DisasContext *dc)

{

	int size = memsize_zz(dc);

	DIS(fprintf (logfile, "move.%c $r%u, $r%u\n",

		    memsize_char(size), dc->op1, dc->op2));

	cris_cc_mask(dc, CC_MASK_NZ);

	if (size == 4) {

		dec_prep_move_r(dc, dc->op1, dc->op2, size, 0, cpu_R[dc->op2]);

		cris_cc_mask(dc, CC_MASK_NZ);

		cris_update_cc_op(dc, CC_OP_MOVE, 4);

		cris_update_cc_x(dc);

		cris_update_result(dc, cpu_R[dc->op2]);

	}

	else {

		TCGv t0;

		t0 = tcg_temp_new(TCG_TYPE_TL);

		dec_prep_move_r(dc, dc->op1, dc->op2, size, 0, t0);

		cris_alu(dc, CC_OP_MOVE,

			 cpu_R[dc->op2],

			 cpu_R[dc->op2], t0, size);

		tcg_temp_free(t0);

	}

	return 2;

}


static void gen_neon_zip_u16(TCGv t0, TCGv t1)

{

    TCGv tmp, tmp2;

    tmp = new_tmp();

    tmp2 = new_tmp();

    tcg_gen_andi_i32(tmp, t0, 0xffff);

    tcg_gen_shli_i32(tmp2, t1, 16);

    tcg_gen_or_i32(tmp, tmp, tmp2);

    tcg_gen_andi_i32(t1, t1, 0xffff0000);

    tcg_gen_shri_i32(tmp2, t0, 16);

    tcg_gen_or_i32(t1, t1, tmp2);

    tcg_gen_mov_i32(t0, tmp);

    dead_tmp(tmp2);

    dead_tmp(tmp);

}


static int spapr_create_pci_child_dt(sPAPRPHBState *phb, PCIDevice *dev,

                                     int drc_index, const char *drc_name,

                                     void *fdt, int node_offset)

{

    int offset, ret;

    int slot = PCI_SLOT(dev->devfn);

    int func = PCI_FUNC(dev->devfn);

    char nodename[FDT_NAME_MAX];

    if (func != 0) {

        snprintf(nodename, FDT_NAME_MAX, "pci@%x,%x", slot, func);

    } else {

        snprintf(nodename, FDT_NAME_MAX, "pci@%x", slot);

    }

    offset = fdt_add_subnode(fdt, node_offset, nodename);

    ret = spapr_populate_pci_child_dt(dev, fdt, offset, phb->index, drc_index,

                                      phb);

    g_assert(!ret);

    if (ret) {

        return 0;

    }

    return offset;

}


void shpc_cleanup(PCIDevice *d, MemoryRegion *bar)

{

    SHPCDevice *shpc = d->shpc;

    d->cap_present &= ~QEMU_PCI_CAP_SHPC;

    memory_region_del_subregion(bar, &shpc->mmio);

    object_unparent(OBJECT(&shpc->mmio));

    /* TODO: cleanup config space changes? */

    g_free(shpc->config);

    g_free(shpc->cmask);

    g_free(shpc->wmask);

    g_free(shpc->w1cmask);

    g_free(shpc);

}


static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)

{

    int flags, in = -1, out = -1;

    flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;

    out = qmp_chardev_open_file_source(file->out, flags, errp);

    if (error_is_set(errp)) {

        return NULL;

    }

    if (file->in) {

        flags = O_RDONLY;

        in = qmp_chardev_open_file_source(file->in, flags, errp);

        if (error_is_set(errp)) {

            qemu_close(out);

            return NULL;

        }

    }

    return qemu_chr_open_fd(in, out);

}


static unsigned int dec_bound_r(DisasContext *dc)

{

	TCGv l0;

	int size = memsize_zz(dc);

	DIS(fprintf (logfile, "bound.%c $r%u, $r%u\n",

		    memsize_char(size), dc->op1, dc->op2));

	cris_cc_mask(dc, CC_MASK_NZ);

	l0 = tcg_temp_local_new(TCG_TYPE_TL);

	dec_prep_move_r(dc, dc->op1, dc->op2, size, 0, l0);

	cris_alu(dc, CC_OP_BOUND, cpu_R[dc->op2], cpu_R[dc->op2], l0, 4);

	tcg_temp_free(l0);

	return 2;

}


static int usb_wacom_handle_control(USBDevice *dev, int request, int value,

                                    int index, int length, uint8_t *data)

{

    USBWacomState *s = (USBWacomState *) dev;

    int ret;

    ret = usb_desc_handle_control(dev, request, value, index, length, data);

    if (ret >= 0) {

        return ret;

    }

    ret = 0;

    switch (request) {

    case DeviceRequest | USB_REQ_GET_STATUS:

        data[0] = (1 << USB_DEVICE_SELF_POWERED) |

            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);

        data[1] = 0x00;

        ret = 2;

        break;

    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 0;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case DeviceOutRequest | USB_REQ_SET_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 1;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_CONFIGURATION:

        data[0] = 1;

        ret = 1;

        break;

    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_INTERFACE:

        data[0] = 0;

        ret = 1;

        break;

    case DeviceOutRequest | USB_REQ_SET_INTERFACE:

        ret = 0;

        break;

    case WACOM_SET_REPORT:

        if (s->mouse_grabbed) {

            qemu_remove_mouse_event_handler(s->eh_entry);

            s->mouse_grabbed = 0;

        }

        s->mode = data[0];

        ret = 0;

        break;

    case WACOM_GET_REPORT:

        data[0] = 0;

        data[1] = s->mode;

        ret = 2;

        break;

    /* USB HID requests */

    case HID_GET_REPORT:

        if (s->mode == WACOM_MODE_HID)

            ret = usb_mouse_poll(s, data, length);

        else if (s->mode == WACOM_MODE_WACOM)

            ret = usb_wacom_poll(s, data, length);

        break;

    case HID_GET_IDLE:

        ret = 1;

        data[0] = s->idle;

        break;

    case HID_SET_IDLE:

        s->idle = (uint8_t) (value >> 8);

        ret = 0;

        break;

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


static void gen_store_fpr32h(TCGv_i32 t, int reg)

{

    TCGv_i64 t64 = tcg_temp_new_i64();

    tcg_gen_extu_i32_i64(t64, t);

    tcg_gen_deposit_i64(fpu_f64[reg], fpu_f64[reg], t64, 32, 32);

    tcg_temp_free_i64(t64);

}


static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    if((uint64_t)atom.size > (1<<30))

        return -1;

    // currently SVQ3 decoder expect full STSD header - so let's fake it

    // this should be fixed and just SMI header should be passed

    av_free(st->codec->extradata);

    st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!st->codec->extradata)

        return AVERROR(ENOMEM);

    st->codec->extradata_size = 0x5a + atom.size;

    memcpy(st->codec->extradata, "SVQ3", 4); // fake

    get_buffer(pb, st->codec->extradata + 0x5a, atom.size);

    dprintf(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);

    return 0;

}


static inline void ne2000_mem_writel(NE2000State *s, uint32_t addr,

                                     uint32_t val)

{

    addr &= ~1; /* XXX: check exact behaviour if not even */

    if (addr < 32 ||

        (addr >= NE2000_PMEM_START && addr < NE2000_MEM_SIZE)) {

        stl_le_p(s->mem + addr, val);

    }

}


static void nvdimm_build_fit_buffer(NvdimmFitBuffer *fit_buf)

{

    qemu_mutex_lock(&fit_buf->lock);

    g_array_free(fit_buf->fit, true);

    fit_buf->fit = nvdimm_build_device_structure();

    fit_buf->dirty = true;

    qemu_mutex_unlock(&fit_buf->lock);

}


static void vnc_debug_gnutls_log(int level, const char* str) {

    VNC_DEBUG("%d %s", level, str);

}


static uint64_t subpage_read(void *opaque, target_phys_addr_t addr,

                             unsigned len)

{

    subpage_t *mmio = opaque;

    unsigned int idx = SUBPAGE_IDX(addr);

    MemoryRegionSection *section;

#if defined(DEBUG_SUBPAGE)

    printf("%s: subpage %p len %d addr " TARGET_FMT_plx " idx %d\n", __func__,

           mmio, len, addr, idx);

#endif

    section = &phys_sections[mmio->sub_section[idx]];

    addr += mmio->base;

    addr -= section->offset_within_address_space;

    addr += section->offset_within_region;

    return io_mem_read(section->mr, addr, len);

}


int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,

                   const uint8_t *key, size_t nkey,

                   const uint8_t *salt, size_t nsalt,

                   unsigned int iterations,

                   uint8_t *out, size_t nout,

                   Error **errp)

{

    static const int hash_map[QCRYPTO_HASH_ALG__MAX] = {

        [QCRYPTO_HASH_ALG_MD5] = GCRY_MD_MD5,

        [QCRYPTO_HASH_ALG_SHA1] = GCRY_MD_SHA1,

        [QCRYPTO_HASH_ALG_SHA256] = GCRY_MD_SHA256,

    };

    int ret;

    if (hash >= G_N_ELEMENTS(hash_map) ||

        hash_map[hash] == GCRY_MD_NONE) {

        error_setg(errp, "Unexpected hash algorithm %d", hash);

        return -1;

    }

    ret = gcry_kdf_derive(key, nkey, GCRY_KDF_PBKDF2,

                          hash_map[hash],

                          salt, nsalt, iterations,

                          nout, out);

    if (ret != 0) {

        error_setg(errp, "Cannot derive password: %s",

                   gcry_strerror(ret));

        return -1;

    }

    return 0;

}


uint32_t helper_efdctui (uint64_t val)

{

    CPU_DoubleU u;

    u.ll = val;

    /* NaN are not treated the same way IEEE 754 does */

    if (unlikely(float64_is_nan(u.d)))

        return 0;

    return float64_to_uint32(u.d, &env->vec_status);

}


Aml *init_aml_allocator(void)

{

    Aml *var;

    assert(!alloc_list);

    alloc_list = g_ptr_array_new();

    var = aml_alloc();

    return var;

}


static void dca_downmix(float **samples, int srcfmt, int lfe_present,

                        float coef[DCA_PRIM_CHANNELS_MAX + 1][2],

                        const int8_t *channel_mapping)

{

    int c, l, r, sl, sr, s;

    int i;

    float t, u, v;

    switch (srcfmt) {

    case DCA_MONO:

    case DCA_CHANNEL:

    case DCA_STEREO_TOTAL:

    case DCA_STEREO_SUMDIFF:

    case DCA_4F2R:

        av_log(NULL, 0, "Not implemented!\n");

        break;

    case DCA_STEREO:

        break;

    case DCA_3F:

        c = channel_mapping[0];

        l = channel_mapping[1];

        r = channel_mapping[2];

        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );

        break;

    case DCA_2F1R:

        s = channel_mapping[2];

        DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), );

        break;

    case DCA_3F1R:

        c = channel_mapping[0];

        l = channel_mapping[1];

        r = channel_mapping[2];

        s = channel_mapping[3];

        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),

                          MIX_REAR1(samples, s, 3, coef));

        break;

    case DCA_2F2R:

        sl = channel_mapping[2];

        sr = channel_mapping[3];

        DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), );

        break;

    case DCA_3F2R:

        c  = channel_mapping[0];

        l  = channel_mapping[1];

        r  = channel_mapping[2];

        sl = channel_mapping[3];

        sr = channel_mapping[4];

        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),

                          MIX_REAR2(samples, sl, sr, 3, coef));

        break;

    }

    if (lfe_present) {

        int lf_buf = dca_lfe_index[srcfmt];

        int lf_idx = dca_channels [srcfmt];

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

            samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0];

            samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1];

        }

    }

}


void spapr_tce_free(sPAPRTCETable *tcet)

{

    QLIST_REMOVE(tcet, list);

    if (!kvm_enabled() ||

        (kvmppc_remove_spapr_tce(tcet->table, tcet->fd,

                                 tcet->window_size) != 0)) {

        g_free(tcet->table);

    }

    g_free(tcet);

}


static void sysctl_write(void *opaque, target_phys_addr_t addr, uint64_t value,

                         unsigned size)

{

    MilkymistSysctlState *s = opaque;

    trace_milkymist_sysctl_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_GPIO_OUT:

    case R_GPIO_INTEN:

    case R_TIMER0_COUNTER:

    case R_TIMER1_COUNTER:

    case R_DBG_SCRATCHPAD:

        s->regs[addr] = value;

        break;

    case R_TIMER0_COMPARE:

        ptimer_set_limit(s->ptimer0, value, 0);

        s->regs[addr] = value;

        break;

    case R_TIMER1_COMPARE:

        ptimer_set_limit(s->ptimer1, value, 0);

        s->regs[addr] = value;

        break;

    case R_TIMER0_CONTROL:

        s->regs[addr] = value;

        if (s->regs[R_TIMER0_CONTROL] & CTRL_ENABLE) {

            trace_milkymist_sysctl_start_timer0();

            ptimer_set_count(s->ptimer0,

                    s->regs[R_TIMER0_COMPARE] - s->regs[R_TIMER0_COUNTER]);

            ptimer_run(s->ptimer0, 0);

        } else {

            trace_milkymist_sysctl_stop_timer0();

            ptimer_stop(s->ptimer0);

        }

        break;

    case R_TIMER1_CONTROL:

        s->regs[addr] = value;

        if (s->regs[R_TIMER1_CONTROL] & CTRL_ENABLE) {

            trace_milkymist_sysctl_start_timer1();

            ptimer_set_count(s->ptimer1,

                    s->regs[R_TIMER1_COMPARE] - s->regs[R_TIMER1_COUNTER]);

            ptimer_run(s->ptimer1, 0);

        } else {

            trace_milkymist_sysctl_stop_timer1();

            ptimer_stop(s->ptimer1);

        }

        break;

    case R_ICAP:

        sysctl_icap_write(s, value);

        break;

    case R_DBG_WRITE_LOCK:

        s->regs[addr] = 1;

        break;

    case R_SYSTEM_ID:

        qemu_system_reset_request();

        break;

    case R_GPIO_IN:

    case R_CLK_FREQUENCY:

    case R_CAPABILITIES:

        error_report("milkymist_sysctl: write to read-only register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    default:

        error_report("milkymist_sysctl: write access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

}


static void parallels_close(BlockDriverState *bs)

{

    BDRVParallelsState *s = bs->opaque;

    g_free(s->catalog_bitmap);

}


static int img_resize(int argc, char **argv)

{

    Error *err = NULL;

    int c, ret, relative;

    const char *filename, *fmt, *size;

    int64_t n, total_size;

    bool quiet = false;

    BlockBackend *blk = NULL;

    QemuOpts *param;

    static QemuOptsList resize_options = {

        .name = "resize_options",

        .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),

        .desc = {

            {

                .name = BLOCK_OPT_SIZE,

                .type = QEMU_OPT_SIZE,

                .help = "Virtual disk size"

            }, {

                /* end of list */

            }

        },

    };

    bool image_opts = false;

    /* Remove size from argv manually so that negative numbers are not treated

     * as options by getopt. */

    if (argc < 3) {

        error_exit("Not enough arguments");

        return 1;

    }

    size = argv[--argc];

    /* Parse getopt arguments */

    fmt = NULL;

    for(;;) {

        static const struct option long_options[] = {

            {"help", no_argument, 0, 'h'},

            {"object", required_argument, 0, OPTION_OBJECT},

            {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},

            {0, 0, 0, 0}

        };

        c = getopt_long(argc, argv, "f:hq",

                        long_options, NULL);

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            break;

        case 'f':

            fmt = optarg;

            break;

        case 'q':

            quiet = true;

            break;

        case OPTION_OBJECT: {

            QemuOpts *opts;

            opts = qemu_opts_parse_noisily(&qemu_object_opts,

                                           optarg, true);

            if (!opts) {

                return 1;

            }

        }   break;

        case OPTION_IMAGE_OPTS:

            image_opts = true;

            break;

        }

    }

    if (optind != argc - 1) {

        error_exit("Expecting one image file name");

    }

    filename = argv[optind++];

    if (qemu_opts_foreach(&qemu_object_opts,

                          user_creatable_add_opts_foreach,

                          NULL, NULL)) {

        return 1;

    }

    /* Choose grow, shrink, or absolute resize mode */

    switch (size[0]) {

    case '+':

        relative = 1;

        size++;

        break;

    case '-':

        relative = -1;

        size++;

        break;

    default:

        relative = 0;

        break;

    }

    /* Parse size */

    param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);

    qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);

    if (err) {

        error_report_err(err);

        ret = -1;

        qemu_opts_del(param);

        goto out;

    }

    n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);

    qemu_opts_del(param);

    blk = img_open(image_opts, filename, fmt,

                   BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet);

    if (!blk) {

        ret = -1;

        goto out;

    }

    if (relative) {

        total_size = blk_getlength(blk) + n * relative;

    } else {

        total_size = n;

    }

    if (total_size <= 0) {

        error_report("New image size must be positive");

        ret = -1;

        goto out;

    }

    ret = blk_truncate(blk, total_size);

    switch (ret) {

    case 0:

        qprintf(quiet, "Image resized.\n");

        break;

    case -ENOTSUP:

        error_report("This image does not support resize");

        break;

    case -EACCES:

        error_report("Image is read-only");

        break;

    default:

        error_report("Error resizing image: %s", strerror(-ret));

        break;

    }

out:

    blk_unref(blk);

    if (ret) {

        return 1;

    }

    return 0;

}


static void qtrle_decode_24bpp(QtrleContext *s, int stream_ptr, int row_ptr, int lines_to_change)

{

    int rle_code;

    int pixel_ptr;

    int row_inc = s->frame.linesize[0];

    unsigned char r, g, b;

    unsigned char *rgb = s->frame.data[0];

    int pixel_limit = s->frame.linesize[0] * s->avctx->height;

    while (lines_to_change--) {

        CHECK_STREAM_PTR(2);

        pixel_ptr = row_ptr + (s->buf[stream_ptr++] - 1) * 3;

        while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {

            if (rle_code == 0) {

                /* there's another skip code in the stream */

                CHECK_STREAM_PTR(1);

                pixel_ptr += (s->buf[stream_ptr++] - 1) * 3;

            } else if (rle_code < 0) {

                /* decode the run length code */

                rle_code = -rle_code;

                CHECK_STREAM_PTR(3);

                r = s->buf[stream_ptr++];

                g = s->buf[stream_ptr++];

                b = s->buf[stream_ptr++];

                CHECK_PIXEL_PTR(rle_code * 3);

                while (rle_code--) {

                    rgb[pixel_ptr++] = r;

                    rgb[pixel_ptr++] = g;

                    rgb[pixel_ptr++] = b;

                }

            } else {

                CHECK_STREAM_PTR(rle_code * 3);

                CHECK_PIXEL_PTR(rle_code * 3);

                /* copy pixels directly to output */

                while (rle_code--) {

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                }

            }

        }

        row_ptr += row_inc;

    }

}