static void gen_loongson_multimedia(DisasContext *ctx, int rd, int rs, int rt)

{

    const char *opn = "loongson_cp2";

    uint32_t opc, shift_max;

    TCGv_i64 t0, t1;

    opc = MASK_LMI(ctx->opcode);

    switch (opc) {

    case OPC_ADD_CP2:

    case OPC_SUB_CP2:

    case OPC_DADD_CP2:

    case OPC_DSUB_CP2:

        t0 = tcg_temp_local_new_i64();

        t1 = tcg_temp_local_new_i64();

        break;

    default:

        t0 = tcg_temp_new_i64();

        t1 = tcg_temp_new_i64();

        break;

    }

    gen_load_fpr64(ctx, t0, rs);

    gen_load_fpr64(ctx, t1, rt);

#define LMI_HELPER(UP, LO) \

    case OPC_##UP: gen_helper_##LO(t0, t0, t1); opn = #LO; break

#define LMI_HELPER_1(UP, LO) \

    case OPC_##UP: gen_helper_##LO(t0, t0); opn = #LO; break

#define LMI_DIRECT(UP, LO, OP) \

    case OPC_##UP: tcg_gen_##OP##_i64(t0, t0, t1); opn = #LO; break

    switch (opc) {

    LMI_HELPER(PADDSH, paddsh);

    LMI_HELPER(PADDUSH, paddush);

    LMI_HELPER(PADDH, paddh);

    LMI_HELPER(PADDW, paddw);

    LMI_HELPER(PADDSB, paddsb);

    LMI_HELPER(PADDUSB, paddusb);

    LMI_HELPER(PADDB, paddb);

    LMI_HELPER(PSUBSH, psubsh);

    LMI_HELPER(PSUBUSH, psubush);

    LMI_HELPER(PSUBH, psubh);

    LMI_HELPER(PSUBW, psubw);

    LMI_HELPER(PSUBSB, psubsb);

    LMI_HELPER(PSUBUSB, psubusb);

    LMI_HELPER(PSUBB, psubb);

    LMI_HELPER(PSHUFH, pshufh);

    LMI_HELPER(PACKSSWH, packsswh);

    LMI_HELPER(PACKSSHB, packsshb);

    LMI_HELPER(PACKUSHB, packushb);

    LMI_HELPER(PUNPCKLHW, punpcklhw);

    LMI_HELPER(PUNPCKHHW, punpckhhw);

    LMI_HELPER(PUNPCKLBH, punpcklbh);

    LMI_HELPER(PUNPCKHBH, punpckhbh);

    LMI_HELPER(PUNPCKLWD, punpcklwd);

    LMI_HELPER(PUNPCKHWD, punpckhwd);

    LMI_HELPER(PAVGH, pavgh);

    LMI_HELPER(PAVGB, pavgb);

    LMI_HELPER(PMAXSH, pmaxsh);

    LMI_HELPER(PMINSH, pminsh);

    LMI_HELPER(PMAXUB, pmaxub);

    LMI_HELPER(PMINUB, pminub);

    LMI_HELPER(PCMPEQW, pcmpeqw);

    LMI_HELPER(PCMPGTW, pcmpgtw);

    LMI_HELPER(PCMPEQH, pcmpeqh);

    LMI_HELPER(PCMPGTH, pcmpgth);

    LMI_HELPER(PCMPEQB, pcmpeqb);

    LMI_HELPER(PCMPGTB, pcmpgtb);

    LMI_HELPER(PSLLW, psllw);

    LMI_HELPER(PSLLH, psllh);

    LMI_HELPER(PSRLW, psrlw);

    LMI_HELPER(PSRLH, psrlh);

    LMI_HELPER(PSRAW, psraw);

    LMI_HELPER(PSRAH, psrah);

    LMI_HELPER(PMULLH, pmullh);

    LMI_HELPER(PMULHH, pmulhh);

    LMI_HELPER(PMULHUH, pmulhuh);

    LMI_HELPER(PMADDHW, pmaddhw);

    LMI_HELPER(PASUBUB, pasubub);

    LMI_HELPER_1(BIADD, biadd);

    LMI_HELPER_1(PMOVMSKB, pmovmskb);

    LMI_DIRECT(PADDD, paddd, add);

    LMI_DIRECT(PSUBD, psubd, sub);

    LMI_DIRECT(XOR_CP2, xor, xor);

    LMI_DIRECT(NOR_CP2, nor, nor);

    LMI_DIRECT(AND_CP2, and, and);

    LMI_DIRECT(PANDN, pandn, andc);

    LMI_DIRECT(OR, or, or);

    case OPC_PINSRH_0:

        tcg_gen_deposit_i64(t0, t0, t1, 0, 16);

        opn = "pinsrh_0";

        break;

    case OPC_PINSRH_1:

        tcg_gen_deposit_i64(t0, t0, t1, 16, 16);

        opn = "pinsrh_1";

        break;

    case OPC_PINSRH_2:

        tcg_gen_deposit_i64(t0, t0, t1, 32, 16);

        opn = "pinsrh_2";

        break;

    case OPC_PINSRH_3:

        tcg_gen_deposit_i64(t0, t0, t1, 48, 16);

        opn = "pinsrh_3";

        break;

    case OPC_PEXTRH:

        tcg_gen_andi_i64(t1, t1, 3);

        tcg_gen_shli_i64(t1, t1, 4);

        tcg_gen_shr_i64(t0, t0, t1);

        tcg_gen_ext16u_i64(t0, t0);

        opn = "pextrh";

        break;

    case OPC_ADDU_CP2:

        tcg_gen_add_i64(t0, t0, t1);

        tcg_gen_ext32s_i64(t0, t0);

        opn = "addu";

        break;

    case OPC_SUBU_CP2:

        tcg_gen_sub_i64(t0, t0, t1);

        tcg_gen_ext32s_i64(t0, t0);

        opn = "addu";

        break;

    case OPC_SLL_CP2:

        opn = "sll";

        shift_max = 32;

        goto do_shift;

    case OPC_SRL_CP2:

        opn = "srl";

        shift_max = 32;

        goto do_shift;

    case OPC_SRA_CP2:

        opn = "sra";

        shift_max = 32;

        goto do_shift;

    case OPC_DSLL_CP2:

        opn = "dsll";

        shift_max = 64;

        goto do_shift;

    case OPC_DSRL_CP2:

        opn = "dsrl";

        shift_max = 64;

        goto do_shift;

    case OPC_DSRA_CP2:

        opn = "dsra";

        shift_max = 64;

        goto do_shift;

    do_shift:

        /* Make sure shift count isn't TCG undefined behaviour.  */

        tcg_gen_andi_i64(t1, t1, shift_max - 1);

        switch (opc) {

        case OPC_SLL_CP2:

        case OPC_DSLL_CP2:

            tcg_gen_shl_i64(t0, t0, t1);

            break;

        case OPC_SRA_CP2:

        case OPC_DSRA_CP2:

            /* Since SRA is UndefinedResult without sign-extended inputs,

               we can treat SRA and DSRA the same.  */

            tcg_gen_sar_i64(t0, t0, t1);

            break;

        case OPC_SRL_CP2:

            /* We want to shift in zeros for SRL; zero-extend first.  */

            tcg_gen_ext32u_i64(t0, t0);

            /* FALLTHRU */

        case OPC_DSRL_CP2:

            tcg_gen_shr_i64(t0, t0, t1);

            break;

        }

        if (shift_max == 32) {

            tcg_gen_ext32s_i64(t0, t0);

        }

        /* Shifts larger than MAX produce zero.  */

        tcg_gen_setcondi_i64(TCG_COND_LTU, t1, t1, shift_max);

        tcg_gen_neg_i64(t1, t1);

        tcg_gen_and_i64(t0, t0, t1);

        break;

    case OPC_ADD_CP2:

    case OPC_DADD_CP2:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            int lab = gen_new_label();

            tcg_gen_mov_i64(t2, t0);

            tcg_gen_add_i64(t0, t1, t2);

            if (opc == OPC_ADD_CP2) {

                tcg_gen_ext32s_i64(t0, t0);

            }

            tcg_gen_xor_i64(t1, t1, t2);

            tcg_gen_xor_i64(t2, t2, t0);

            tcg_gen_andc_i64(t1, t2, t1);

            tcg_temp_free_i64(t2);

            tcg_gen_brcondi_i64(TCG_COND_GE, t1, 0, lab);

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(lab);

            opn = (opc == OPC_ADD_CP2 ? "add" : "dadd");

            break;

        }

    case OPC_SUB_CP2:

    case OPC_DSUB_CP2:

        {

            TCGv_i64 t2 = tcg_temp_new_i64();

            int lab = gen_new_label();

            tcg_gen_mov_i64(t2, t0);

            tcg_gen_sub_i64(t0, t1, t2);

            if (opc == OPC_SUB_CP2) {

                tcg_gen_ext32s_i64(t0, t0);

            }

            tcg_gen_xor_i64(t1, t1, t2);

            tcg_gen_xor_i64(t2, t2, t0);

            tcg_gen_and_i64(t1, t1, t2);

            tcg_temp_free_i64(t2);

            tcg_gen_brcondi_i64(TCG_COND_GE, t1, 0, lab);

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(lab);

            opn = (opc == OPC_SUB_CP2 ? "sub" : "dsub");

            break;

        }

    case OPC_PMULUW:

        tcg_gen_ext32u_i64(t0, t0);

        tcg_gen_ext32u_i64(t1, t1);

        tcg_gen_mul_i64(t0, t0, t1);

        opn = "pmuluw";

        break;

    case OPC_SEQU_CP2:

    case OPC_SEQ_CP2:

    case OPC_SLTU_CP2:

    case OPC_SLT_CP2:

    case OPC_SLEU_CP2:

    case OPC_SLE_CP2:

        /* ??? Document is unclear: Set FCC[CC].  Does that mean the

           FD field is the CC field?  */

    default:

        MIPS_INVAL(opn);

        generate_exception(ctx, EXCP_RI);

        return;

    }

#undef LMI_HELPER

#undef LMI_DIRECT

    gen_store_fpr64(ctx, t0, rd);

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

    MIPS_DEBUG("%s %s, %s, %s", opn,

               fregnames[rd], fregnames[rs], fregnames[rt]);

    tcg_temp_free_i64(t0);

    tcg_temp_free_i64(t1);

}


static void v9fs_stat(void *opaque)

{

    int32_t fid;

    V9fsStat v9stat;

    ssize_t err = 0;

    size_t offset = 7;

    struct stat stbuf;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "d", &fid);

    trace_v9fs_stat(pdu->tag, pdu->id, fid);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

    if (err < 0) {

        goto out;

    }

    err = stat_to_v9stat(pdu, &fidp->path, &stbuf, &v9stat);

    if (err < 0) {

        goto out;

    }

    offset += pdu_marshal(pdu, offset, "wS", 0, &v9stat);

    err = offset;

    trace_v9fs_stat_return(pdu->tag, pdu->id, v9stat.mode,

                           v9stat.atime, v9stat.mtime, v9stat.length);

    v9fs_stat_free(&v9stat);

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}


uint64_t helper_addlv (uint64_t op1, uint64_t op2)

{

    uint64_t tmp = op1;

    op1 = (uint32_t)(op1 + op2);

    if (unlikely((tmp ^ op2 ^ (-1UL)) & (tmp ^ op1) & (1UL << 31))) {

        arith_excp(env, GETPC(), EXC_M_IOV, 0);

    }

    return op1;

}


static int of_dpa_cmd_add_l2_flood(OfDpa *of_dpa, OfDpaGroup *group,

                                   RockerTlv **group_tlvs)

{

    OfDpaGroup *l2_group;

    RockerTlv **tlvs;

    int err;

    int i;

    if (!group_tlvs[ROCKER_TLV_OF_DPA_GROUP_COUNT] ||

        !group_tlvs[ROCKER_TLV_OF_DPA_GROUP_IDS]) {

        return -ROCKER_EINVAL;

    }

    group->l2_flood.group_count =

        rocker_tlv_get_le16(group_tlvs[ROCKER_TLV_OF_DPA_GROUP_COUNT]);

    tlvs = g_malloc0((group->l2_flood.group_count + 1) *

                     sizeof(RockerTlv *));

    if (!tlvs) {

        return -ROCKER_ENOMEM;

    }

    g_free(group->l2_flood.group_ids);

    group->l2_flood.group_ids =

        g_malloc0(group->l2_flood.group_count * sizeof(uint32_t));

    if (!group->l2_flood.group_ids) {

        err = -ROCKER_ENOMEM;

        goto err_out;

    }

    rocker_tlv_parse_nested(tlvs, group->l2_flood.group_count,

                            group_tlvs[ROCKER_TLV_OF_DPA_GROUP_IDS]);

    for (i = 0; i < group->l2_flood.group_count; i++) {

        group->l2_flood.group_ids[i] = rocker_tlv_get_le32(tlvs[i + 1]);

    }

    /* All of the L2 interface groups referenced by the L2 flood

     * must have same VLAN

     */

    for (i = 0; i < group->l2_flood.group_count; i++) {

        l2_group = of_dpa_group_find(of_dpa, group->l2_flood.group_ids[i]);

        if (!l2_group) {

            continue;

        }

        if ((ROCKER_GROUP_TYPE_GET(l2_group->id) ==

             ROCKER_OF_DPA_GROUP_TYPE_L2_INTERFACE) &&

            (ROCKER_GROUP_VLAN_GET(l2_group->id) !=

             ROCKER_GROUP_VLAN_GET(group->id))) {

            DPRINTF("l2 interface group 0x%08x VLAN doesn't match l2 "

                    "flood group 0x%08x\n",

                    group->l2_flood.group_ids[i], group->id);

            err = -ROCKER_EINVAL;

            goto err_out;

        }

    }

    g_free(tlvs);

    return ROCKER_OK;

err_out:

    group->l2_flood.group_count = 0;

    g_free(group->l2_flood.group_ids);

    g_free(tlvs);

    return err;

}


int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {

    const uint64_t fuzz_tag = FUZZ_TAG;

    FuzzDataBuffer buffer;

    const uint8_t *last = data;

    const uint8_t *end = data + size;

    uint32_t it = 0;

    if (!c)

        c = AVCodecInitialize(FFMPEG_CODEC);  // Done once.

    AVCodecContext* ctx = avcodec_alloc_context3(NULL);

    if (!ctx)

        error("Failed memory allocation");

    ctx->max_pixels = 4096 * 4096; //To reduce false positive OOM and hangs

    int res = avcodec_open2(ctx, c, NULL);

    if (res < 0)

        return res;

    FDBCreate(&buffer);

    int got_frame;

    AVFrame *frame = av_frame_alloc();

    if (!frame)

        error("Failed memory allocation");

    // Read very simple container

    AVPacket avpkt;

    while (data < end && it < maxiteration) {

        // Search for the TAG

        while (data + sizeof(fuzz_tag) < end) {

            if (data[0] == (fuzz_tag & 0xFF) && *(const uint64_t *)(data) == fuzz_tag)

                break;

            data++;

        }

        if (data + sizeof(fuzz_tag) > end)

            data = end;

        FDBPrepare(&buffer, &avpkt, last, data - last);

        data += sizeof(fuzz_tag);

        last = data;

        // Iterate through all data

        while (avpkt.size > 0 && it++ < maxiteration) {

            av_frame_unref(frame);

            int ret = decode_handler(ctx, frame, &got_frame, &avpkt);

            if (it > 20)

                ctx->error_concealment = 0;

            if (ret <= 0 || ret > avpkt.size)

               break;

            avpkt.data += ret;

            avpkt.size -= ret;

        }

    }

    av_init_packet(&avpkt);

    avpkt.data = NULL;

    avpkt.size = 0;

    do {

        got_frame = 0;

        decode_handler(ctx, frame, &got_frame, &avpkt);

    } while (got_frame == 1 && it++ < maxiteration);

    av_frame_free(&frame);

    avcodec_free_context(&ctx);

    av_freep(&ctx);

    FDBDesroy(&buffer);

    return 0;

}


void op_cp1_64bitmode(void)

{

    if (!(env->CP0_Status & (1 << CP0St_FR))) {

        CALL_FROM_TB1(do_raise_exception, EXCP_RI);

    }

    RETURN();

}


void disas_a64_insn(CPUARMState *env, DisasContext *s)

{

    uint32_t insn;

    insn = arm_ldl_code(env, s->pc, s->bswap_code);

    s->insn = insn;

    s->pc += 4;

    switch ((insn >> 24) & 0x1f) {

    default:

        unallocated_encoding(s);

        break;

    }

    if (unlikely(s->singlestep_enabled) && (s->is_jmp == DISAS_TB_JUMP)) {

        /* go through the main loop for single step */

        s->is_jmp = DISAS_JUMP;

    }

}


static inline void gen_op_mov_v_reg(int ot, TCGv t0, int reg)

{

    switch(ot) {

    case OT_BYTE:

        if (reg < 4 X86_64_DEF( || reg >= 8 || x86_64_hregs)) {

            goto std_case;

        } else {

            tcg_gen_shri_tl(t0, cpu_regs[reg - 4], 8);

            tcg_gen_ext8u_tl(t0, t0);

        }

        break;

    default:

    std_case:

        tcg_gen_mov_tl(t0, cpu_regs[reg]);

        break;

    }

}


static int hdev_open(BlockDriverState *bs, const char *filename, int flags)

{

    BDRVRawState *s = bs->opaque;

    int access_flags, create_flags;

    DWORD overlapped;

    char device_name[64];

    if (strstart(filename, "/dev/cdrom", NULL)) {

        if (find_cdrom(device_name, sizeof(device_name)) < 0)

            return -ENOENT;

        filename = device_name;

    } else {

        /* transform drive letters into device name */

        if (((filename[0] >= 'a' && filename[0] <= 'z') ||

             (filename[0] >= 'A' && filename[0] <= 'Z')) &&

            filename[1] == ':' && filename[2] == '\0') {

            snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);

            filename = device_name;

        }

    }

    s->type = find_device_type(bs, filename);

    if ((flags & BDRV_O_ACCESS) == O_RDWR) {

        access_flags = GENERIC_READ | GENERIC_WRITE;

    } else {

        access_flags = GENERIC_READ;

    }

    create_flags = OPEN_EXISTING;

#ifdef QEMU_TOOL

    overlapped = FILE_ATTRIBUTE_NORMAL;

#else

    overlapped = FILE_FLAG_OVERLAPPED;

#endif

    s->hfile = CreateFile(filename, access_flags,

                          FILE_SHARE_READ, NULL,

                          create_flags, overlapped, NULL);

    if (s->hfile == INVALID_HANDLE_VALUE)

        return -1;

    return 0;

}


static void sigp_store_adtl_status(CPUState *cs, run_on_cpu_data arg)

{

    S390CPU *cpu = S390_CPU(cs);

    SigpInfo *si = arg.host_ptr;

    if (!s390_has_feat(S390_FEAT_VECTOR)) {

        set_sigp_status(si, SIGP_STAT_INVALID_ORDER);

        return;

    }

    /* cpu has to be stopped */

    if (s390_cpu_get_state(cpu) != CPU_STATE_STOPPED) {

        set_sigp_status(si, SIGP_STAT_INCORRECT_STATE);

        return;

    }

    /* parameter must be aligned to 1024-byte boundary */

    if (si->param & 0x3ff) {

        set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);

        return;

    }

    cpu_synchronize_state(cs);

    if (kvm_s390_store_adtl_status(cpu, si->param)) {

        set_sigp_status(si, SIGP_STAT_INVALID_PARAMETER);

        return;

    }

    si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;

}


static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)

{

    target_ulong tmp;

    tmp = ldtul_p(mem_buf);

    if (n < 32) {

        env->active_tc.gpr[n] = tmp;

        return sizeof(target_ulong);

    }

    if (env->CP0_Config1 & (1 << CP0C1_FP)

            && n >= 38 && n < 73) {

        if (n < 70) {

            if (env->CP0_Status & (1 << CP0St_FR))

              env->active_fpu.fpr[n - 38].d = tmp;

            else

              env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX] = tmp;

        }

        switch (n) {

        case 70:

            env->active_fpu.fcr31 = tmp & 0xFF83FFFF;

            /* set rounding mode */

            RESTORE_ROUNDING_MODE;

#ifndef CONFIG_SOFTFLOAT

            /* no floating point exception for native float */

            SET_FP_ENABLE(env->active_fpu.fcr31, 0);

#endif

            break;

        case 71: env->active_fpu.fcr0 = tmp; break;

        }

        return sizeof(target_ulong);

    }

    switch (n) {

    case 32: env->CP0_Status = tmp; break;

    case 33: env->active_tc.LO[0] = tmp; break;

    case 34: env->active_tc.HI[0] = tmp; break;

    case 35: env->CP0_BadVAddr = tmp; break;

    case 36: env->CP0_Cause = tmp; break;

    case 37: env->active_tc.PC = tmp; break;

    case 72: /* fp, ignored */ break;

    default:

	if (n > 89)

	    return 0;

	/* Other registers are readonly.  Ignore writes.  */

	break;

    }

    return sizeof(target_ulong);

}


QEMUBH *aio_bh_new(AioContext *ctx, QEMUBHFunc *cb, void *opaque)

{

    QEMUBH *bh;

    bh = g_malloc0(sizeof(QEMUBH));

    bh->ctx = ctx;

    bh->cb = cb;

    bh->opaque = opaque;

    qemu_mutex_lock(&ctx->bh_lock);

    bh->next = ctx->first_bh;

    /* Make sure that the members are ready before putting bh into list */

    smp_wmb();

    ctx->first_bh = bh;

    qemu_mutex_unlock(&ctx->bh_lock);

    return bh;

}


static void audiogen(void *data, enum AVSampleFormat sample_fmt,

                     int channels, int sample_rate, int nb_samples)

{

    int i, ch, k;

    double v, f, a, ampa;

    double tabf1[SWR_CH_MAX];

    double tabf2[SWR_CH_MAX];

    double taba[SWR_CH_MAX];

    unsigned static rnd;

#define PUT_SAMPLE set(data, ch, k, channels, sample_fmt, v);

#define uint_rand(x) (x = x * 1664525 + 1013904223)

#define dbl_rand(x) (uint_rand(x)*2.0 / (double)UINT_MAX - 1)

    k = 0;

    /* 1 second of single freq sinus at 1000 Hz */

    a = 0;

    for (i = 0; i < 1 * sample_rate && k < nb_samples; i++, k++) {

        v = sin(a) * 0.30;

        for (ch = 0; ch < channels; ch++)

            PUT_SAMPLE

        a += M_PI * 1000.0 * 2.0 / sample_rate;

    }

    /* 1 second of varying frequency between 100 and 10000 Hz */

    a = 0;

    for (i = 0; i < 1 * sample_rate && k < nb_samples; i++, k++) {

        v = sin(a) * 0.30;

        for (ch = 0; ch < channels; ch++)

            PUT_SAMPLE

        f  = 100.0 + (((10000.0 - 100.0) * i) / sample_rate);

        a += M_PI * f * 2.0 / sample_rate;

    }

    /* 0.5 second of low amplitude white noise */

    for (i = 0; i < sample_rate / 2 && k < nb_samples; i++, k++) {

        v = dbl_rand(rnd) * 0.30;

        for (ch = 0; ch < channels; ch++)

            PUT_SAMPLE

    }

    /* 0.5 second of high amplitude white noise */

    for (i = 0; i < sample_rate / 2 && k < nb_samples; i++, k++) {

        v = dbl_rand(rnd);

        for (ch = 0; ch < channels; ch++)

            PUT_SAMPLE

    }

    /* 1 second of unrelated ramps for each channel */

    for (ch = 0; ch < channels; ch++) {

        taba[ch]  = 0;

        tabf1[ch] = 100 + uint_rand(rnd) % 5000;

        tabf2[ch] = 100 + uint_rand(rnd) % 5000;

    }

    for (i = 0; i < 1 * sample_rate && k < nb_samples; i++, k++) {

        for (ch = 0; ch < channels; ch++) {

            v = sin(taba[ch]) * 0.30;

            PUT_SAMPLE

            f = tabf1[ch] + (((tabf2[ch] - tabf1[ch]) * i) / sample_rate);

            taba[ch] += M_PI * f * 2.0 / sample_rate;

        }

    }

    /* 2 seconds of 500 Hz with varying volume */

    a    = 0;

    ampa = 0;

    for (i = 0; i < 2 * sample_rate && k < nb_samples; i++, k++) {

        for (ch = 0; ch < channels; ch++) {

            double amp = (1.0 + sin(ampa)) * 0.15;

            if (ch & 1)

                amp = 0.30 - amp;

            v = sin(a) * amp;

            PUT_SAMPLE

            a    += M_PI * 500.0 * 2.0 / sample_rate;

            ampa += M_PI *  2.0 / sample_rate;

        }

    }

}


static void paint_mouse_pointer(AVFormatContext *s1, struct gdigrab *gdigrab)

{

    CURSORINFO ci = {0};

#define CURSOR_ERROR(str)                 \

    if (!gdigrab->cursor_error_printed) {       \

        WIN32_API_ERROR(str);             \

        gdigrab->cursor_error_printed = 1;      \

    }

    ci.cbSize = sizeof(ci);

    if (GetCursorInfo(&ci)) {

        HCURSOR icon = CopyCursor(ci.hCursor);

        ICONINFO info;

        POINT pos;

        RECT clip_rect = gdigrab->clip_rect;

        HWND hwnd = gdigrab->hwnd;

        info.hbmMask = NULL;

        info.hbmColor = NULL;

        if (ci.flags != CURSOR_SHOWING)

            return;

        if (!icon) {

            /* Use the standard arrow cursor as a fallback.

             * You'll probably only hit this in Wine, which can't fetch

             * the current system cursor. */

            icon = CopyCursor(LoadCursor(NULL, IDC_ARROW));

        }

        if (!GetIconInfo(icon, &info)) {

            CURSOR_ERROR("Could not get icon info");

            goto icon_error;

        }

        pos.x = ci.ptScreenPos.x - clip_rect.left - info.xHotspot;

        pos.y = ci.ptScreenPos.y - clip_rect.top - info.yHotspot;

        if (hwnd) {

            RECT rect;

            if (GetWindowRect(hwnd, &rect)) {

                pos.x -= rect.left;

                pos.y -= rect.top;

            } else {

                CURSOR_ERROR("Couldn't get window rectangle");

                goto icon_error;

            }

        }

        av_log(s1, AV_LOG_DEBUG, "Cursor pos (%li,%li) -> (%li,%li)\n",

                ci.ptScreenPos.x, ci.ptScreenPos.y, pos.x, pos.y);

        if (pos.x >= 0 && pos.x <= clip_rect.right - clip_rect.left &&

                pos.y >= 0 && pos.y <= clip_rect.bottom - clip_rect.top) {

            if (!DrawIcon(gdigrab->dest_hdc, pos.x, pos.y, icon))

                CURSOR_ERROR("Couldn't draw icon");

        }

icon_error:

        if (icon)

            DestroyCursor(icon);

    } else {

        CURSOR_ERROR("Couldn't get cursor info");

    }

}


static void machine_initfn(Object *obj)

{

    MachineState *ms = MACHINE(obj);

    ms->kernel_irqchip_allowed = true;

    ms->kvm_shadow_mem = -1;

    ms->dump_guest_core = true;

    object_property_add_str(obj, "accel",

                            machine_get_accel, machine_set_accel, NULL);

    object_property_set_description(obj, "accel",

                                    "Accelerator list",

                                    NULL);

    object_property_add_bool(obj, "kernel-irqchip",

                             NULL,

                             machine_set_kernel_irqchip,

                             NULL);

    object_property_set_description(obj, "kernel-irqchip",

                                    "Use KVM in-kernel irqchip",

                                    NULL);

    object_property_add(obj, "kvm-shadow-mem", "int",

                        machine_get_kvm_shadow_mem,

                        machine_set_kvm_shadow_mem,

                        NULL, NULL, NULL);

    object_property_set_description(obj, "kvm-shadow-mem",

                                    "KVM shadow MMU size",

                                    NULL);

    object_property_add_str(obj, "kernel",

                            machine_get_kernel, machine_set_kernel, NULL);

    object_property_set_description(obj, "kernel",

                                    "Linux kernel image file",

                                    NULL);

    object_property_add_str(obj, "initrd",

                            machine_get_initrd, machine_set_initrd, NULL);

    object_property_set_description(obj, "initrd",

                                    "Linux initial ramdisk file",

                                    NULL);

    object_property_add_str(obj, "append",

                            machine_get_append, machine_set_append, NULL);

    object_property_set_description(obj, "append",

                                    "Linux kernel command line",

                                    NULL);

    object_property_add_str(obj, "dtb",

                            machine_get_dtb, machine_set_dtb, NULL);

    object_property_set_description(obj, "dtb",

                                    "Linux kernel device tree file",

                                    NULL);

    object_property_add_str(obj, "dumpdtb",

                            machine_get_dumpdtb, machine_set_dumpdtb, NULL);

    object_property_set_description(obj, "dumpdtb",

                                    "Dump current dtb to a file and quit",

                                    NULL);

    object_property_add(obj, "phandle-start", "int",

                        machine_get_phandle_start,

                        machine_set_phandle_start,

                        NULL, NULL, NULL);

    object_property_set_description(obj, "phandle-start",

                                    "The first phandle ID we may generate dynamically",

                                    NULL);

    object_property_add_str(obj, "dt-compatible",

                            machine_get_dt_compatible,

                            machine_set_dt_compatible,

                            NULL);

    object_property_set_description(obj, "dt-compatible",

                                    "Overrides the \"compatible\" property of the dt root node",

                                    NULL);

    object_property_add_bool(obj, "dump-guest-core",

                             machine_get_dump_guest_core,

                             machine_set_dump_guest_core,

                             NULL);

    object_property_set_description(obj, "dump-guest-core",

                                    "Include guest memory in  a core dump",

                                    NULL);

    object_property_add_bool(obj, "mem-merge",

                             machine_get_mem_merge,

                             machine_set_mem_merge, NULL);

    object_property_set_description(obj, "mem-merge",

                                    "Enable/disable memory merge support",

                                    NULL);

    object_property_add_bool(obj, "usb",

                             machine_get_usb,

                             machine_set_usb, NULL);

    object_property_set_description(obj, "usb",

                                    "Set on/off to enable/disable usb",

                                    NULL);

    object_property_add_str(obj, "firmware",

                            machine_get_firmware,

                            machine_set_firmware, NULL);

    object_property_set_description(obj, "firmware",

                                    "Firmware image",

                                    NULL);

    object_property_add_bool(obj, "iommu",

                             machine_get_iommu,

                             machine_set_iommu, NULL);

    object_property_set_description(obj, "iommu",

                                    "Set on/off to enable/disable Intel IOMMU (VT-d)",

                                    NULL);

    /* Register notifier when init is done for sysbus sanity checks */

    ms->sysbus_notifier.notify = machine_init_notify;

    qemu_add_machine_init_done_notifier(&ms->sysbus_notifier);

}


void bdrv_delete(BlockDriverState *bs)

{

    assert(!bs->peer);

    /* remove from list, if necessary */

    if (bs->device_name[0] != '\0') {

        QTAILQ_REMOVE(&bdrv_states, bs, list);

    }

    bdrv_close(bs);

    if (bs->file != NULL) {

        bdrv_delete(bs->file);

    }

    assert(bs != bs_snapshots);

    qemu_free(bs);

}


static void hmp_migrate_status_cb(void *opaque)

{

    MigrationStatus *status = opaque;

    MigrationInfo *info;

    info = qmp_query_migrate(NULL);

    if (!info->has_status || strcmp(info->status, "active") == 0) {

        if (info->has_disk) {

            int progress;

            if (info->disk->remaining) {

                progress = info->disk->transferred * 100 / info->disk->total;

            } else {

                progress = 100;

            }

            monitor_printf(status->mon, "Completed %d %%\r", progress);

            monitor_flush(status->mon);

        }

        timer_mod(status->timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 1000);

    } else {

        if (status->is_block_migration) {

            monitor_printf(status->mon, "\n");

        }

        monitor_resume(status->mon);

        timer_del(status->timer);

        g_free(status);

    }

    qapi_free_MigrationInfo(info);

}


int kvm_arch_on_sigbus(int code, void *addr)

{

#ifdef KVM_CAP_MCE

    if ((first_cpu->mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {

        void *vaddr;

        ram_addr_t ram_addr;

        target_phys_addr_t paddr;

        /* Hope we are lucky for AO MCE */

        vaddr = addr;

        if (qemu_ram_addr_from_host(vaddr, &ram_addr) ||

            !kvm_physical_memory_addr_from_ram(first_cpu->kvm_state, ram_addr,

                                               &paddr)) {

            fprintf(stderr, "Hardware memory error for memory used by "

                    "QEMU itself instead of guest system!: %p\n", addr);

            return 0;

        }

        kvm_mce_inj_srao_memscrub2(first_cpu, paddr);

    } else

#endif /* KVM_CAP_MCE */

    {

        if (code == BUS_MCEERR_AO) {

            return 0;

        } else if (code == BUS_MCEERR_AR) {

            hardware_memory_error();

        } else {

            return 1;

        }

    }

    return 0;

}


coroutine_fn iscsi_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)

{

    IscsiLun *iscsilun = bs->opaque;

    struct IscsiTask iTask;

    struct unmap_list list;

    int r = 0;

    if (!is_byte_request_lun_aligned(offset, bytes, iscsilun)) {

        return -ENOTSUP;

    }

    if (!iscsilun->lbp.lbpu) {

        /* UNMAP is not supported by the target */

        return 0;

    }

    list.lba = offset / iscsilun->block_size;

    list.num = bytes / iscsilun->block_size;

    iscsi_co_init_iscsitask(iscsilun, &iTask);

    qemu_mutex_lock(&iscsilun->mutex);

retry:

    if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,

                         iscsi_co_generic_cb, &iTask) == NULL) {

        r = -ENOMEM;

        goto out_unlock;

    }

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_mutex_unlock(&iscsilun->mutex);

        qemu_coroutine_yield();

        qemu_mutex_lock(&iscsilun->mutex);

    }

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

        iTask.task = NULL;

    }

    if (iTask.do_retry) {

        iTask.complete = 0;

        goto retry;

    }

    if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {

        /* the target might fail with a check condition if it

           is not happy with the alignment of the UNMAP request

           we silently fail in this case */

        goto out_unlock;

    }

    if (iTask.status != SCSI_STATUS_GOOD) {

        r = iTask.err_code;

        goto out_unlock;

    }

    iscsi_allocmap_set_invalid(iscsilun, offset >> BDRV_SECTOR_BITS,

                               bytes >> BDRV_SECTOR_BITS);

out_unlock:

    qemu_mutex_unlock(&iscsilun->mutex);

    return r;

}


int mips_cpu_handle_mmu_fault(CPUState *cs, vaddr address, int rw,

                              int mmu_idx)

{

    MIPSCPU *cpu = MIPS_CPU(cs);

    CPUMIPSState *env = &cpu->env;

#if !defined(CONFIG_USER_ONLY)

    hwaddr physical;

    int prot;

    int access_type;

#endif

    int ret = 0;

#if 0

    log_cpu_state(cs, 0);

#endif

    qemu_log_mask(CPU_LOG_MMU,

              "%s pc " TARGET_FMT_lx " ad %" VADDR_PRIx " rw %d mmu_idx %d\n",

              __func__, env->active_tc.PC, address, rw, mmu_idx);

    /* data access */

#if !defined(CONFIG_USER_ONLY)

    /* XXX: put correct access by using cpu_restore_state()

       correctly */

    access_type = ACCESS_INT;

    ret = get_physical_address(env, &physical, &prot,

                               address, rw, access_type);

    qemu_log_mask(CPU_LOG_MMU,

             "%s address=%" VADDR_PRIx " ret %d physical " TARGET_FMT_plx

             " prot %d\n",

             __func__, address, ret, physical, prot);

    if (ret == TLBRET_MATCH) {

        tlb_set_page(cs, address & TARGET_PAGE_MASK,

                     physical & TARGET_PAGE_MASK, prot | PAGE_EXEC,

                     mmu_idx, TARGET_PAGE_SIZE);

        ret = 0;

    } else if (ret < 0)

#endif

    {

        raise_mmu_exception(env, address, rw, ret);

        ret = 1;

    }

    return ret;

}


static ModuleTypeList *find_type(module_init_type type)

{

    ModuleTypeList *l;

    init_types();

    l = &init_type_list[type];

    return l;

}


static int qemu_suspend_requested(void)

{

    int r = suspend_requested;

    suspend_requested = 0;

    return r;

}


int opt_cpuflags(const char *opt, const char *arg)

{

#define CPUFLAG_MMX2     (AV_CPU_FLAG_MMX      | AV_CPU_FLAG_MMX2)

#define CPUFLAG_3DNOW    (AV_CPU_FLAG_3DNOW    | AV_CPU_FLAG_MMX)

#define CPUFLAG_3DNOWEXT (AV_CPU_FLAG_3DNOWEXT | CPUFLAG_3DNOW)

#define CPUFLAG_SSE      (AV_CPU_FLAG_SSE      | CPUFLAG_MMX2)

#define CPUFLAG_SSE2     (AV_CPU_FLAG_SSE2     | CPUFLAG_SSE)

#define CPUFLAG_SSE2SLOW (AV_CPU_FLAG_SSE2SLOW | CPUFLAG_SSE2)

#define CPUFLAG_SSE3     (AV_CPU_FLAG_SSE3     | CPUFLAG_SSE2)

#define CPUFLAG_SSE3SLOW (AV_CPU_FLAG_SSE3SLOW | CPUFLAG_SSE3)

#define CPUFLAG_SSSE3    (AV_CPU_FLAG_SSSE3    | CPUFLAG_SSE3)

#define CPUFLAG_SSE4     (AV_CPU_FLAG_SSE4     | CPUFLAG_SSSE3)

#define CPUFLAG_SSE42    (AV_CPU_FLAG_SSE42    | CPUFLAG_SSE4)

#define CPUFLAG_AVX      (AV_CPU_FLAG_AVX      | CPUFLAG_SSE42)

#define CPUFLAG_XOP      (AV_CPU_FLAG_XOP      | CPUFLAG_AVX)

#define CPUFLAG_FMA4     (AV_CPU_FLAG_FMA4     | CPUFLAG_AVX)

    static const AVOption cpuflags_opts[] = {

        { "flags"   , NULL, 0, AV_OPT_TYPE_FLAGS, { 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },

        { "altivec" , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_ALTIVEC  },    .unit = "flags" },

        { "mmx"     , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_MMX      },    .unit = "flags" },

        { "mmx2"    , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_MMX2         },    .unit = "flags" },

        { "sse"     , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSE          },    .unit = "flags" },

        { "sse2"    , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSE2         },    .unit = "flags" },

        { "sse2slow", NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSE2SLOW     },    .unit = "flags" },

        { "sse3"    , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSE3         },    .unit = "flags" },

        { "sse3slow", NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSE3SLOW     },    .unit = "flags" },

        { "ssse3"   , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSSE3        },    .unit = "flags" },

        { "atom"    , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_ATOM     },    .unit = "flags" },

        { "sse4.1"  , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSE4         },    .unit = "flags" },

        { "sse4.2"  , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_SSE42        },    .unit = "flags" },

        { "avx"     , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_AVX          },    .unit = "flags" },

        { "xop"     , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_XOP          },    .unit = "flags" },

        { "fma4"    , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_FMA4         },    .unit = "flags" },

        { "3dnow"   , NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_3DNOW        },    .unit = "flags" },

        { "3dnowext", NULL, 0, AV_OPT_TYPE_CONST, { CPUFLAG_3DNOWEXT     },    .unit = "flags" },

        { NULL },

    };

    static const AVClass class = {

        .class_name = "cpuflags",

        .item_name  = av_default_item_name,

        .option     = cpuflags_opts,

        .version    = LIBAVUTIL_VERSION_INT,

    };

    int flags = av_get_cpu_flags();

    int ret;

    const AVClass *pclass = &class;

    if ((ret = av_opt_eval_flags(&pclass, &cpuflags_opts[0], arg, &flags)) < 0)

        return ret;

    av_force_cpu_flags(flags);

    return 0;

}


void ff_put_h264_qpel8_mc21_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_midv_qrt_8w_msa(src - (2 * stride) - 2, stride, dst, stride, 8, 0);

}


static void serial_tx_done(void *opaque)

{

    SerialState *s = opaque;

    if (s->tx_burst < 0) {

        uint16_t divider;

        if (s->divider)

          divider = s->divider;

        else

          divider = 1;

        /* We assume 10 bits/char, OK for this purpose. */

        s->tx_burst = THROTTLE_TX_INTERVAL * 1000 /

            (1000000 * 10 / (s->baudbase / divider));

    }

    s->thr_ipending = 1;

    s->lsr |= UART_LSR_THRE;

    s->lsr |= UART_LSR_TEMT;

    serial_update_irq(s);

}


void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)

{

    QXLDevSurfaceCreate surface;

    memset(&surface, 0, sizeof(surface));

    dprint(1, "%s/%d: %dx%d\n", __func__, ssd->qxl.id,

           surface_width(ssd->ds), surface_height(ssd->ds));

    surface.format     = SPICE_SURFACE_FMT_32_xRGB;

    surface.width      = surface_width(ssd->ds);

    surface.height     = surface_height(ssd->ds);

    surface.stride     = -surface.width * 4;

    surface.mouse_mode = true;

    surface.flags      = 0;

    surface.type       = 0;

    surface.mem        = (uintptr_t)ssd->buf;

    surface.group_id   = MEMSLOT_GROUP_HOST;

    qemu_spice_create_primary_surface(ssd, 0, &surface, QXL_SYNC);

}


static void init_proc_750fx (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* XXX : not implemented */

    spr_register(env, SPR_L2CR, "L2CR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, NULL,

                 0x00000000);

    /* Time base */

    gen_tbl(env);

    /* Thermal management */

    gen_spr_thrm(env);

    /* XXX : not implemented */

    spr_register(env, SPR_750_THRM4, "THRM4",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_750FX_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Memory management */

    gen_low_BATs(env);

    /* PowerPC 750fx & 750gx has 8 DBATs and 8 IBATs */

    gen_high_BATs(env);

    init_excp_7x0(env);

    env->dcache_line_size = 32;

    env->icache_line_size = 32;

    /* Allocate hardware IRQ controller */

    ppc6xx_irq_init(env);

}


void st_print_trace_file_status(FILE *stream, int (*stream_printf)(FILE *stream, const char *fmt, ...))

{

    stream_printf(stream, "Trace file \"%s\" %s.\n",

                  trace_file_name, trace_file_enabled ? "on" : "off");

}


static int mkv_write_header(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    AVIOContext *pb = s->pb;

    ebml_master ebml_header;

    AVDictionaryEntry *tag;

    int ret, i, version = 2;

    int64_t creation_time;

    if (!strcmp(s->oformat->name, "webm"))

        mkv->mode = MODE_WEBM;

    else

        mkv->mode = MODE_MATROSKAv2;

    if (mkv->mode != MODE_WEBM ||

        av_dict_get(s->metadata, "stereo_mode", NULL, 0) ||

        av_dict_get(s->metadata, "alpha_mode", NULL, 0))

        version = 4;

    if (s->nb_streams > MAX_TRACKS) {

        av_log(s, AV_LOG_ERROR,

               "At most %d streams are supported for muxing in Matroska\n",

               MAX_TRACKS);

        return AVERROR(EINVAL);

    }

    for (i = 0; i < s->nb_streams; i++) {

        if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_ATRAC3 ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_COOK ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RA_288 ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_SIPR ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV10 ||

            s->streams[i]->codecpar->codec_id == AV_CODEC_ID_RV20) {

            av_log(s, AV_LOG_ERROR,

                   "The Matroska muxer does not yet support muxing %s\n",

                   avcodec_get_name(s->streams[i]->codecpar->codec_id));

            return AVERROR_PATCHWELCOME;

        }

        if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||

            av_dict_get(s->streams[i]->metadata, "stereo_mode", NULL, 0) ||

            av_dict_get(s->streams[i]->metadata, "alpha_mode", NULL, 0))

            version = 4;

    }

    mkv->tracks = av_mallocz_array(s->nb_streams, sizeof(*mkv->tracks));

    if (!mkv->tracks) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    ebml_header = start_ebml_master(pb, EBML_ID_HEADER, 0);

    put_ebml_uint   (pb, EBML_ID_EBMLVERSION        ,           1);

    put_ebml_uint   (pb, EBML_ID_EBMLREADVERSION    ,           1);

    put_ebml_uint   (pb, EBML_ID_EBMLMAXIDLENGTH    ,           4);

    put_ebml_uint   (pb, EBML_ID_EBMLMAXSIZELENGTH  ,           8);

    put_ebml_string (pb, EBML_ID_DOCTYPE            , s->oformat->name);

    put_ebml_uint   (pb, EBML_ID_DOCTYPEVERSION     ,     version);

    put_ebml_uint   (pb, EBML_ID_DOCTYPEREADVERSION ,           2);

    end_ebml_master(pb, ebml_header);

    mkv->segment = start_ebml_master(pb, MATROSKA_ID_SEGMENT, 0);

    mkv->segment_offset = avio_tell(pb);

    // we write 2 seek heads - one at the end of the file to point to each

    // cluster, and one at the beginning to point to all other level one

    // elements (including the seek head at the end of the file), which

    // isn't more than 10 elements if we only write one of each other

    // currently defined level 1 element

    mkv->main_seekhead    = mkv_start_seekhead(pb, mkv->segment_offset, 10);

    if (!mkv->main_seekhead) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_INFO, avio_tell(pb));

    if (ret < 0) goto fail;

    ret = start_ebml_master_crc32(pb, &mkv->info_bc, mkv, &mkv->info, MATROSKA_ID_INFO, 0);

    if (ret < 0)

        return ret;

    pb = mkv->info_bc;

    put_ebml_uint(pb, MATROSKA_ID_TIMECODESCALE, 1000000);

    if ((tag = av_dict_get(s->metadata, "title", NULL, 0)))

        put_ebml_string(pb, MATROSKA_ID_TITLE, tag->value);

    if (!(s->flags & AVFMT_FLAG_BITEXACT)) {

        put_ebml_string(pb, MATROSKA_ID_MUXINGAPP, LIBAVFORMAT_IDENT);

        if ((tag = av_dict_get(s->metadata, "encoding_tool", NULL, 0)))

            put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, tag->value);

        else

            put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, LIBAVFORMAT_IDENT);

        if (mkv->mode != MODE_WEBM) {

            uint32_t segment_uid[4];

            AVLFG lfg;

            av_lfg_init(&lfg, av_get_random_seed());

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

                segment_uid[i] = av_lfg_get(&lfg);

            put_ebml_binary(pb, MATROSKA_ID_SEGMENTUID, segment_uid, 16);

        }

    } else {

        const char *ident = "Lavf";

        put_ebml_string(pb, MATROSKA_ID_MUXINGAPP , ident);

        put_ebml_string(pb, MATROSKA_ID_WRITINGAPP, ident);

    }

    if (ff_parse_creation_time_metadata(s, &creation_time, 0) > 0) {

        // Adjust time so it's relative to 2001-01-01 and convert to nanoseconds.

        int64_t date_utc = (creation_time - 978307200000000LL) * 1000;

        uint8_t date_utc_buf[8];

        AV_WB64(date_utc_buf, date_utc);

        put_ebml_binary(pb, MATROSKA_ID_DATEUTC, date_utc_buf, 8);

    }

    // reserve space for the duration

    mkv->duration = 0;

    mkv->duration_offset = avio_tell(pb);

    if (!mkv->is_live) {

        int64_t metadata_duration = get_metadata_duration(s);

        if (s->duration > 0) {

            int64_t scaledDuration = av_rescale(s->duration, 1000, AV_TIME_BASE);

            put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);

            av_log(s, AV_LOG_DEBUG, "Write early duration from recording time = %" PRIu64 "\n", scaledDuration);

        } else if (metadata_duration > 0) {

            int64_t scaledDuration = av_rescale(metadata_duration, 1000, AV_TIME_BASE);

            put_ebml_float(pb, MATROSKA_ID_DURATION, scaledDuration);

            av_log(s, AV_LOG_DEBUG, "Write early duration from metadata = %" PRIu64 "\n", scaledDuration);

        } else {

            put_ebml_void(pb, 11);              // assumes double-precision float to be written

        }

    }

    if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)

        end_ebml_master_crc32_preliminary(s->pb, &mkv->info_bc, mkv, mkv->info);

    else

        end_ebml_master_crc32(s->pb, &mkv->info_bc, mkv, mkv->info);

    pb = s->pb;

    // initialize stream_duration fields

    mkv->stream_durations = av_mallocz(s->nb_streams * sizeof(int64_t));

    mkv->stream_duration_offsets = av_mallocz(s->nb_streams * sizeof(int64_t));

    ret = mkv_write_tracks(s);

    if (ret < 0)

        goto fail;

    for (i = 0; i < s->nb_chapters; i++)

        mkv->chapter_id_offset = FFMAX(mkv->chapter_id_offset, 1LL - s->chapters[i]->id);

    ret = mkv_write_chapters(s);

    if (ret < 0)

        goto fail;

    if (mkv->mode != MODE_WEBM) {

        ret = mkv_write_attachments(s);

        if (ret < 0)

            goto fail;

    }

    ret = mkv_write_tags(s);

    if (ret < 0)

        goto fail;

    if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && !mkv->is_live)

        mkv_write_seekhead(pb, mkv);

    mkv->cues = mkv_start_cues(mkv->segment_offset);

    if (!mkv->cues) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mkv->reserve_cues_space) {

        mkv->cues_pos = avio_tell(pb);

        put_ebml_void(pb, mkv->reserve_cues_space);

    }

    av_init_packet(&mkv->cur_audio_pkt);

    mkv->cur_audio_pkt.size = 0;

    mkv->cluster_pos = -1;

    avio_flush(pb);

    // start a new cluster every 5 MB or 5 sec, or 32k / 1 sec for streaming or

    // after 4k and on a keyframe

    if (pb->seekable & AVIO_SEEKABLE_NORMAL) {

        if (mkv->cluster_time_limit < 0)

            mkv->cluster_time_limit = 5000;

        if (mkv->cluster_size_limit < 0)

            mkv->cluster_size_limit = 5 * 1024 * 1024;

    } else {

        if (mkv->cluster_time_limit < 0)

            mkv->cluster_time_limit = 1000;

        if (mkv->cluster_size_limit < 0)

            mkv->cluster_size_limit = 32 * 1024;

    }

    return 0;

fail:

    mkv_free(mkv);

    return ret;

}


e1000_can_receive(void *opaque)

{

    E1000State *s = opaque;

    return (!(s->mac_reg[RCTL] & E1000_RCTL_EN) ||

            s->mac_reg[RDH] != s->mac_reg[RDT]);

}


av_cold void ff_sws_init_swScale_mmx(SwsContext *c)

{

    int cpu_flags = av_get_cpu_flags();

#if HAVE_INLINE_ASM

    if (cpu_flags & AV_CPU_FLAG_MMX)

        sws_init_swScale_MMX(c);

#if HAVE_MMXEXT_INLINE

    if (cpu_flags & AV_CPU_FLAG_MMXEXT)

        sws_init_swScale_MMX2(c);

#endif

#endif /* HAVE_INLINE_ASM */

#if HAVE_YASM

#define ASSIGN_SCALE_FUNC2(hscalefn, filtersize, opt1, opt2) do { \

    if (c->srcBpc == 8) { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale8to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale8to19_ ## filtersize ## _ ## opt1; \

    } else if (c->srcBpc == 9) { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale9to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale9to19_ ## filtersize ## _ ## opt1; \

    } else if (c->srcBpc == 10) { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale10to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale10to19_ ## filtersize ## _ ## opt1; \

    } else /* c->srcBpc == 16 */ { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale16to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale16to19_ ## filtersize ## _ ## opt1; \

    } \

} while (0)

#define ASSIGN_MMX_SCALE_FUNC(hscalefn, filtersize, opt1, opt2) \

    switch (filtersize) { \

    case 4:  ASSIGN_SCALE_FUNC2(hscalefn, 4, opt1, opt2); break; \

    case 8:  ASSIGN_SCALE_FUNC2(hscalefn, 8, opt1, opt2); break; \

    default: ASSIGN_SCALE_FUNC2(hscalefn, X, opt1, opt2); break; \

    }

#define ASSIGN_VSCALEX_FUNC(vscalefn, opt, do_16_case, condition_8bit) \

switch(c->dstBpc){ \

    case 16:                          do_16_case;                          break; \

    case 10: if (!isBE(c->dstFormat)) vscalefn = ff_yuv2planeX_10_ ## opt; break; \

    case 9:  if (!isBE(c->dstFormat)) vscalefn = ff_yuv2planeX_9_  ## opt; break; \

    default: if (condition_8bit)      vscalefn = ff_yuv2planeX_8_  ## opt; break; \

    }

#define ASSIGN_VSCALE_FUNC(vscalefn, opt1, opt2, opt2chk) \

    switch(c->dstBpc){ \

    case 16: if (!isBE(c->dstFormat))            vscalefn = ff_yuv2plane1_16_ ## opt1; break; \

    case 10: if (!isBE(c->dstFormat) && opt2chk) vscalefn = ff_yuv2plane1_10_ ## opt2; break; \

    case 9:  if (!isBE(c->dstFormat) && opt2chk) vscalefn = ff_yuv2plane1_9_  ## opt2;  break; \

    default:                                     vscalefn = ff_yuv2plane1_8_  ## opt1;  break; \

    }

#define case_rgb(x, X, opt) \

        case PIX_FMT_ ## X: \

            c->lumToYV12 = ff_ ## x ## ToY_ ## opt; \

            if (!c->chrSrcHSubSample) \

                c->chrToYV12 = ff_ ## x ## ToUV_ ## opt; \

            break

#if ARCH_X86_32

    if (cpu_flags & AV_CPU_FLAG_MMX) {

        ASSIGN_MMX_SCALE_FUNC(c->hyScale, c->hLumFilterSize, mmx, mmx);

        ASSIGN_MMX_SCALE_FUNC(c->hcScale, c->hChrFilterSize, mmx, mmx);

        ASSIGN_VSCALE_FUNC(c->yuv2plane1, mmx, mmx2, cpu_flags & AV_CPU_FLAG_MMXEXT);

        switch (c->srcFormat) {

        case PIX_FMT_Y400A:

            c->lumToYV12 = ff_yuyvToY_mmx;

            if (c->alpPixBuf)

                c->alpToYV12 = ff_uyvyToY_mmx;

            break;

        case PIX_FMT_YUYV422:

            c->lumToYV12 = ff_yuyvToY_mmx;

            c->chrToYV12 = ff_yuyvToUV_mmx;

            break;

        case PIX_FMT_UYVY422:

            c->lumToYV12 = ff_uyvyToY_mmx;

            c->chrToYV12 = ff_uyvyToUV_mmx;

            break;

        case PIX_FMT_NV12:

            c->chrToYV12 = ff_nv12ToUV_mmx;

            break;

        case PIX_FMT_NV21:

            c->chrToYV12 = ff_nv21ToUV_mmx;

            break;

        case_rgb(rgb24, RGB24, mmx);

        case_rgb(bgr24, BGR24, mmx);

        case_rgb(bgra,  BGRA,  mmx);

        case_rgb(rgba,  RGBA,  mmx);

        case_rgb(abgr,  ABGR,  mmx);

        case_rgb(argb,  ARGB,  mmx);

        default:

            break;

        }

    }

    if (cpu_flags & AV_CPU_FLAG_MMXEXT) {

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, mmx2, , 1);

    }

#endif /* ARCH_X86_32 */

#define ASSIGN_SSE_SCALE_FUNC(hscalefn, filtersize, opt1, opt2) \

    switch (filtersize) { \

    case 4:  ASSIGN_SCALE_FUNC2(hscalefn, 4, opt1, opt2); break; \

    case 8:  ASSIGN_SCALE_FUNC2(hscalefn, 8, opt1, opt2); break; \

    default: if (filtersize & 4) ASSIGN_SCALE_FUNC2(hscalefn, X4, opt1, opt2); \

             else                ASSIGN_SCALE_FUNC2(hscalefn, X8, opt1, opt2); \

             break; \

    }

    if (cpu_flags & AV_CPU_FLAG_SSE2) {

        ASSIGN_SSE_SCALE_FUNC(c->hyScale, c->hLumFilterSize, sse2, sse2);

        ASSIGN_SSE_SCALE_FUNC(c->hcScale, c->hChrFilterSize, sse2, sse2);

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, sse2, ,

                            HAVE_ALIGNED_STACK || ARCH_X86_64);

        ASSIGN_VSCALE_FUNC(c->yuv2plane1, sse2, sse2, 1);

        switch (c->srcFormat) {

        case PIX_FMT_Y400A:

            c->lumToYV12 = ff_yuyvToY_sse2;

            if (c->alpPixBuf)

                c->alpToYV12 = ff_uyvyToY_sse2;

            break;

        case PIX_FMT_YUYV422:

            c->lumToYV12 = ff_yuyvToY_sse2;

            c->chrToYV12 = ff_yuyvToUV_sse2;

            break;

        case PIX_FMT_UYVY422:

            c->lumToYV12 = ff_uyvyToY_sse2;

            c->chrToYV12 = ff_uyvyToUV_sse2;

            break;

        case PIX_FMT_NV12:

            c->chrToYV12 = ff_nv12ToUV_sse2;

            break;

        case PIX_FMT_NV21:

            c->chrToYV12 = ff_nv21ToUV_sse2;

            break;

        case_rgb(rgb24, RGB24, sse2);

        case_rgb(bgr24, BGR24, sse2);

        case_rgb(bgra,  BGRA,  sse2);

        case_rgb(rgba,  RGBA,  sse2);

        case_rgb(abgr,  ABGR,  sse2);

        case_rgb(argb,  ARGB,  sse2);

        default:

            break;

        }

    }

    if (cpu_flags & AV_CPU_FLAG_SSSE3) {

        ASSIGN_SSE_SCALE_FUNC(c->hyScale, c->hLumFilterSize, ssse3, ssse3);

        ASSIGN_SSE_SCALE_FUNC(c->hcScale, c->hChrFilterSize, ssse3, ssse3);

        switch (c->srcFormat) {

        case_rgb(rgb24, RGB24, ssse3);

        case_rgb(bgr24, BGR24, ssse3);

        default:

            break;

        }

    }

    if (cpu_flags & AV_CPU_FLAG_SSE4) {

        /* Xto15 don't need special sse4 functions */

        ASSIGN_SSE_SCALE_FUNC(c->hyScale, c->hLumFilterSize, sse4, ssse3);

        ASSIGN_SSE_SCALE_FUNC(c->hcScale, c->hChrFilterSize, sse4, ssse3);

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, sse4,

                            if (!isBE(c->dstFormat)) c->yuv2planeX = ff_yuv2planeX_16_sse4,

                            HAVE_ALIGNED_STACK || ARCH_X86_64);

        if (c->dstBpc == 16 && !isBE(c->dstFormat))

            c->yuv2plane1 = ff_yuv2plane1_16_sse4;

    }

    if (cpu_flags & AV_CPU_FLAG_AVX) {

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, avx, ,

                            HAVE_ALIGNED_STACK || ARCH_X86_64);

        ASSIGN_VSCALE_FUNC(c->yuv2plane1, avx, avx, 1);

        switch (c->srcFormat) {

        case PIX_FMT_YUYV422:

            c->chrToYV12 = ff_yuyvToUV_avx;

            break;

        case PIX_FMT_UYVY422:

            c->chrToYV12 = ff_uyvyToUV_avx;

            break;

        case PIX_FMT_NV12:

            c->chrToYV12 = ff_nv12ToUV_avx;

            break;

        case PIX_FMT_NV21:

            c->chrToYV12 = ff_nv21ToUV_avx;

            break;

        case_rgb(rgb24, RGB24, avx);

        case_rgb(bgr24, BGR24, avx);

        case_rgb(bgra,  BGRA,  avx);

        case_rgb(rgba,  RGBA,  avx);

        case_rgb(abgr,  ABGR,  avx);

        case_rgb(argb,  ARGB,  avx);

        default:

            break;

        }

    }

#endif

}


static unsigned tget(const uint8_t **p, int type, int le)

{

    switch (type) {

    case TIFF_BYTE:

        return *(*p)++;

    case TIFF_SHORT:

        return tget_short(p, le);

    case TIFF_LONG:

        return tget_long(p, le);

    default:

        return UINT_MAX;

    }

}


static int decode_hq_slice(AVCodecContext *avctx, void *arg)

{

    int i, quant, level, orientation, quant_idx;

    uint8_t quants[MAX_DWT_LEVELS][4];

    DiracContext *s = avctx->priv_data;

    DiracSlice *slice = arg;

    GetBitContext *gb = &slice->gb;

    skip_bits_long(gb, 8*s->highquality.prefix_bytes);

    quant_idx = get_bits(gb, 8);

    /* Slice quantization (slice_quantizers() in the specs) */

    for (level = 0; level < s->wavelet_depth; level++) {

        for (orientation = !!level; orientation < 4; orientation++) {

            quant = FFMAX(quant_idx - s->lowdelay.quant[level][orientation], 0);

            quants[level][orientation] = quant;

        }

    }

    /* Luma + 2 Chroma planes */

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

        int64_t length = s->highquality.size_scaler * get_bits(gb, 8);

        int64_t bits_left = 8 * length;

        int64_t bits_end = get_bits_count(gb) + bits_left;

        if (bits_end >= INT_MAX) {

            av_log(s->avctx, AV_LOG_ERROR, "end too far away\n");

            return AVERROR_INVALIDDATA;

        }

        for (level = 0; level < s->wavelet_depth; level++) {

            for (orientation = !!level; orientation < 4; orientation++) {

                decode_subband(s, gb, quants[level][orientation], slice->slice_x, slice->slice_y, bits_end,

                               &s->plane[i].band[level][orientation], NULL);

            }

        }

        skip_bits_long(gb, bits_end - get_bits_count(gb));

    }

    return 0;

}


static av_cold int amr_wb_encode_init(AVCodecContext *avctx)

{

    AMRWBContext *s = avctx->priv_data;

    if (avctx->sample_rate != 16000) {

        av_log(avctx, AV_LOG_ERROR, "Only 16000Hz sample rate supported\n");

        return AVERROR(ENOSYS);

    }

    if (avctx->channels != 1) {

        av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");

        return AVERROR(ENOSYS);

    }

    s->mode            = get_wb_bitrate_mode(avctx->bit_rate, avctx);

    s->last_bitrate    = avctx->bit_rate;

    avctx->frame_size  = 320;

    avctx->coded_frame = avcodec_alloc_frame();

    s->state     = E_IF_init();

    return 0;

}


uint32_t div32(uint32_t *q_ptr, uint64_t num, uint32_t den)

{

    *q_ptr = num / den;

    return num % den;

}


void ff_fetch_timestamp(AVCodecParserContext *s, int off, int remove)

{

    int i;

    s->dts    =

    s->pts    = AV_NOPTS_VALUE;

    s->pos    = -1;

    s->offset = 0;

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

        if (s->cur_offset + off >= s->cur_frame_offset[i] &&

            (s->frame_offset < s->cur_frame_offset[i] ||

             (!s->frame_offset && !s->next_frame_offset)) && // first field/frame

            // check disabled since MPEG-TS does not send complete PES packets

            /*s->next_frame_offset + off <*/  s->cur_frame_end[i]){

            s->dts    = s->cur_frame_dts[i];

            s->pts    = s->cur_frame_pts[i];

            s->pos    = s->cur_frame_pos[i];

            s->offset = s->next_frame_offset - s->cur_frame_offset[i];

            if (remove)

                s->cur_frame_offset[i] = INT64_MAX;

            if (s->cur_offset + off < s->cur_frame_end[i])

                break;

        }

    }

}


static void simple_whitespace(void)

{

    int i;

    struct {

        const char *encoded;

        LiteralQObject decoded;

    } test_cases[] = {

        {

            .encoded = " [ 43 , 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = " [ 43 , { 'h' : 'b' }, [ ], 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    { "h", QLIT_QSTR("b") },

                                    { }})),

                        QLIT_QLIST(((LiteralQObject[]){

                                    { }})),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = " [ 43 , { 'h' : 'b' , 'a' : 32 }, [ ], 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    { "h", QLIT_QSTR("b") },

                                    { "a", QLIT_QINT(32) },

                                    { }})),

                        QLIT_QLIST(((LiteralQObject[]){

                                    { }})),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        { }

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded, NULL);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        str = qobject_to_json(obj);

        qobject_decref(obj);

        obj = qobject_from_json(qstring_get_str(str), NULL);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        qobject_decref(obj);

        QDECREF(str);

    }

}


static void gen_check_sr(DisasContext *dc, uint32_t sr, unsigned access)

{

    if (!xtensa_option_bits_enabled(dc->config, sregnames[sr].opt_bits)) {

        if (sregnames[sr].name) {

            qemu_log("SR %s is not configured\n", sregnames[sr].name);

        } else {

            qemu_log("SR %d is not implemented\n", sr);

        }

        gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE);

    } else if (!(sregnames[sr].access & access)) {

        static const char * const access_text[] = {

            [SR_R] = "rsr",

            [SR_W] = "wsr",

            [SR_X] = "xsr",

        };

        assert(access < ARRAY_SIZE(access_text) && access_text[access]);

        qemu_log("SR %s is not available for %s\n", sregnames[sr].name,

                access_text[access]);

        gen_exception_cause(dc, ILLEGAL_INSTRUCTION_CAUSE);

    }

}


static void gen_lswi(DisasContext *ctx)

{

    TCGv t0;

    TCGv_i32 t1, t2;

    int nb = NB(ctx->opcode);

    int start = rD(ctx->opcode);

    int ra = rA(ctx->opcode);

    int nr;

    if (nb == 0)

        nb = 32;

    nr = (nb + 3) / 4;

    if (unlikely(lsw_reg_in_range(start, nr, ra))) {

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_LSWX);

        return;

    }

    gen_set_access_type(ctx, ACCESS_INT);

    /* NIP cannot be restored if the memory exception comes from an helper */

    gen_update_nip(ctx, ctx->nip - 4);

    t0 = tcg_temp_new();

    gen_addr_register(ctx, t0);

    t1 = tcg_const_i32(nb);

    t2 = tcg_const_i32(start);

    gen_helper_lsw(cpu_env, t0, t1, t2);

    tcg_temp_free(t0);

    tcg_temp_free_i32(t1);

    tcg_temp_free_i32(t2);

}


static int decode_frame(AVCodecContext *avctx, const uint8_t *databuf,

                        float **out_samples)

{

    ATRAC3Context *q = avctx->priv_data;

    int ret, i;

    uint8_t *ptr1;

    if (q->coding_mode == JOINT_STEREO) {

        /* channel coupling mode */

        /* decode Sound Unit 1 */

        init_get_bits(&q->gb, databuf, avctx->block_align * 8);

        ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,

                                        JOINT_STEREO);

        if (ret != 0)

            return ret;

        /* Framedata of the su2 in the joint-stereo mode is encoded in

         * reverse byte order so we need to swap it first. */

        if (databuf == q->decoded_bytes_buffer) {

            uint8_t *ptr2 = q->decoded_bytes_buffer + avctx->block_align - 1;

            ptr1          = q->decoded_bytes_buffer;

            for (i = 0; i < avctx->block_align / 2; i++, ptr1++, ptr2--)

                FFSWAP(uint8_t, *ptr1, *ptr2);

        } else {

            const uint8_t *ptr2 = databuf + avctx->block_align - 1;

            for (i = 0; i < avctx->block_align; i++)

                q->decoded_bytes_buffer[i] = *ptr2--;

        }

        /* Skip the sync codes (0xF8). */

        ptr1 = q->decoded_bytes_buffer;

        for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {

            if (i >= avctx->block_align)

                return AVERROR_INVALIDDATA;

        }

        /* set the bitstream reader at the start of the second Sound Unit*/

        init_get_bits8(&q->gb, ptr1, q->decoded_bytes_buffer + avctx->block_align - ptr1);

        /* Fill the Weighting coeffs delay buffer */

        memmove(q->weighting_delay, &q->weighting_delay[2],

                4 * sizeof(*q->weighting_delay));

        q->weighting_delay[4] = get_bits1(&q->gb);

        q->weighting_delay[5] = get_bits(&q->gb, 3);

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

            q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];

            q->matrix_coeff_index_now[i]  = q->matrix_coeff_index_next[i];

            q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);

        }

        /* Decode Sound Unit 2. */

        ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],

                                        out_samples[1], 1, JOINT_STEREO);

        if (ret != 0)

            return ret;

        /* Reconstruct the channel coefficients. */

        reverse_matrixing(out_samples[0], out_samples[1],

                          q->matrix_coeff_index_prev,

                          q->matrix_coeff_index_now);

        channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);

    } else {

        /* single channels */

        /* Decode the channel sound units. */

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

            /* Set the bitstream reader at the start of a channel sound unit. */

            init_get_bits(&q->gb,

                          databuf + i * avctx->block_align / avctx->channels,

                          avctx->block_align * 8 / avctx->channels);

            ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],

                                            out_samples[i], i, q->coding_mode);

            if (ret != 0)

                return ret;

        }

    }

    /* Apply the iQMF synthesis filter. */

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

        float *p1 = out_samples[i];

        float *p2 = p1 + 256;

        float *p3 = p2 + 256;

        float *p4 = p3 + 256;

        ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);

        ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);

        ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);

    }

    return 0;

}


uint32_t HELPER(shr_cc)(CPUM68KState *env, uint32_t val, uint32_t shift)

{

    uint64_t temp;

    uint32_t result;

    shift &= 63;

    temp = (uint64_t)val << 32 >> shift;

    result = temp >> 32;

    env->cc_c = (temp >> 31) & 1;

    env->cc_n = result;

    env->cc_z = result;

    env->cc_v = 0;

    env->cc_x = shift ? env->cc_c : env->cc_x;

    return result;

}


static void term_down_char(void)

{

    if (term_hist_entry == TERM_MAX_CMDS - 1 || term_hist_entry == -1)

	return;

    if (term_history[++term_hist_entry] != NULL) {

	strcpy(term_cmd_buf, term_history[term_hist_entry]);

    } else {

	term_hist_entry = -1;

    }

    term_printf("\n");

    term_print_cmdline(term_cmd_buf);

    term_cmd_buf_index = term_cmd_buf_size = strlen(term_cmd_buf);

}


static int decode_cabac_mb_cbp_luma( H264Context *h) {

    int cbp_b, cbp_a, ctx, cbp = 0;

    cbp_a = h->slice_table[h->left_mb_xy[0]] == h->slice_num ? h->left_cbp : -1;

    cbp_b = h->slice_table[h->top_mb_xy]     == h->slice_num ? h->top_cbp  : -1;

    ctx = !(cbp_a & 0x02) + 2 * !(cbp_b & 0x04);

    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]);

    ctx = !(cbp   & 0x01) + 2 * !(cbp_b & 0x08);

    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 1;

    ctx = !(cbp_a & 0x08) + 2 * !(cbp   & 0x01);

    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 2;

    ctx = !(cbp   & 0x04) + 2 * !(cbp   & 0x02);

    cbp |= get_cabac_noinline(&h->cabac, &h->cabac_state[73 + ctx]) << 3;

    return cbp;

}


void ff_qsv_decode_reset(AVCodecContext *avctx, QSVContext *q)

{

    QSVFrame *cur;

    AVPacket pkt;

    int ret = 0;

    mfxVideoParam param = { { 0 } };

    if (q->reinit_pending) {

        close_decoder(q);

    } else if (q->engine_ready) {

        ret = MFXVideoDECODE_GetVideoParam(q->session, &param);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "MFX decode get param error %d\n", ret);

        }

        ret = MFXVideoDECODE_Reset(q->session, &param);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "MFX decode reset error %d\n", ret);

        }

        /* Free all frames*/

        cur = q->work_frames;

        while (cur) {

            q->work_frames = cur->next;

            av_frame_free(&cur->frame);

            av_freep(&cur);

            cur = q->work_frames;

        }

    }

    /* Reset output surfaces */

    av_fifo_reset(q->async_fifo);

    /* Reset input packets fifo */

    while (av_fifo_size(q->pkt_fifo)) {

        av_fifo_generic_read(q->pkt_fifo, &pkt, sizeof(pkt), NULL);

        av_packet_unref(&pkt);

    }

    /* Reset input bitstream fifo */

    av_fifo_reset(q->input_fifo);

}


target_ulong helper_sdiv(target_ulong a, target_ulong b)

{

    int64_t x0;

    int32_t x1;

    x0 = (a & 0xffffffff) | ((int64_t) (env->y) << 32);

    x1 = (b & 0xffffffff);

    if (x1 == 0) {

        raise_exception(TT_DIV_ZERO);

    }

    x0 = x0 / x1;

    if ((int32_t) x0 != x0) {

        env->cc_src2 = 1;

        return x0 < 0? 0x80000000: 0x7fffffff;

    } else {

        env->cc_src2 = 0;

        return x0;

    }

}


static void xhci_reset(DeviceState *dev)

{

    XHCIState *xhci = XHCI(dev);

    int i;

    trace_usb_xhci_reset();

    if (!(xhci->usbsts & USBSTS_HCH)) {

        DPRINTF("xhci: reset while running!\n");

    }

    xhci->usbcmd = 0;

    xhci->usbsts = USBSTS_HCH;

    xhci->dnctrl = 0;

    xhci->crcr_low = 0;

    xhci->crcr_high = 0;

    xhci->dcbaap_low = 0;

    xhci->dcbaap_high = 0;

    xhci->config = 0;

    for (i = 0; i < xhci->numslots; i++) {

        xhci_disable_slot(xhci, i+1);

    }

    for (i = 0; i < xhci->numports; i++) {

        xhci_port_update(xhci->ports + i, 0);

    }

    for (i = 0; i < xhci->numintrs; i++) {

        xhci->intr[i].iman = 0;

        xhci->intr[i].imod = 0;

        xhci->intr[i].erstsz = 0;

        xhci->intr[i].erstba_low = 0;

        xhci->intr[i].erstba_high = 0;

        xhci->intr[i].erdp_low = 0;

        xhci->intr[i].erdp_high = 0;

        xhci->intr[i].msix_used = 0;

        xhci->intr[i].er_ep_idx = 0;

        xhci->intr[i].er_pcs = 1;

        xhci->intr[i].er_full = 0;

        xhci->intr[i].ev_buffer_put = 0;

        xhci->intr[i].ev_buffer_get = 0;

    }

    xhci->mfindex_start = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    xhci_mfwrap_update(xhci);

}


int ppc_find_by_pvr (uint32_t pvr, ppc_def_t **def)

{

    int i, ret;

    ret = -1;

    *def = NULL;

    for (i = 0; ppc_defs[i].name != NULL; i++) {

        if ((pvr & ppc_defs[i].pvr_mask) ==

            (ppc_defs[i].pvr & ppc_defs[i].pvr_mask)) {

            *def = &ppc_defs[i];

            ret = 0;

            break;

        }

    }

    return ret;

}


void helper_tlb_update(uint32_t T0)

{

#if !defined(CONFIG_USER_ONLY)

	uint32_t vaddr;

	uint32_t srs = env->pregs[PR_SRS];

	if (srs != 1 && srs != 2)

		return;

	vaddr = cris_mmu_tlb_latest_update(env, T0);

	D(printf("flush old_vaddr=%x vaddr=%x T0=%x\n", vaddr,

		 env->sregs[SFR_R_MM_CAUSE] & TARGET_PAGE_MASK, T0));

	tlb_flush_page(env, vaddr);

#endif

}


static void patch_pcihp(int slot, uint8_t *ssdt_ptr, uint32_t eject)

{

    ssdt_ptr[ACPI_PCIHP_OFFSET_HEX] = acpi_get_hex(slot >> 4);

    ssdt_ptr[ACPI_PCIHP_OFFSET_HEX + 1] = acpi_get_hex(slot);

    ssdt_ptr[ACPI_PCIHP_OFFSET_ID] = slot;

    ssdt_ptr[ACPI_PCIHP_OFFSET_ADR + 2] = slot;

    /* Runtime patching of ACPI_EJ0: to disable hotplug for a slot,

     * replace the method name: _EJ0 by ACPI_EJ0_.

     */

    /* Sanity check */

    assert(!memcmp(ssdt_ptr + ACPI_PCIHP_OFFSET_EJ0, "_EJ0", 4));

    if (!eject) {

        memcpy(ssdt_ptr + ACPI_PCIHP_OFFSET_EJ0, "EJ0_", 4);

    }

}


static float ssim_plane(uint8_t *main, int main_stride,

                        uint8_t *ref, int ref_stride,

                        int width, int height, void *temp)

{

    int z = 0;

    int x, y;

    float ssim = 0.0;

    int (*sum0)[4] = temp;

    int (*sum1)[4] = sum0 + (width >> 2) + 3;

    width >>= 2;

    height >>= 2;

    for (y = 1; y < height; y++) {

        for (; z <= y; z++) {

            FFSWAP(void*, sum0, sum1);

            for (x = 0; x < width; x+=2)

                ssim_4x4x2_core(&main[4 * (x + z * main_stride)], main_stride,

                                &ref[4 * (x + z * ref_stride)], ref_stride,

                                &sum0[x]);

        }

        ssim += ssim_endn(sum0, sum1, width - 1);

    }

    return ssim / ((height - 1) * (width - 1));

}


static void nvme_instance_init(Object *obj)

{

    object_property_add(obj, "bootindex", "int32",

                        nvme_get_bootindex,

                        nvme_set_bootindex, NULL, NULL, NULL);

    object_property_set_int(obj, -1, "bootindex", NULL);

}


static int blkverify_open(BlockDriverState *bs, QDict *options, int flags,

                          Error **errp)

{

    BDRVBlkverifyState *s = bs->opaque;

    QemuOpts *opts;

    Error *local_err = NULL;

    int ret;

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    /* Open the raw file */

    bs->file = bdrv_open_child(qemu_opt_get(opts, "x-raw"), options, "raw",

                               bs, &child_file, false, &local_err);

    if (local_err) {

        ret = -EINVAL;

        error_propagate(errp, local_err);

        goto fail;

    /* Open the test file */

    s->test_file = bdrv_open_child(qemu_opt_get(opts, "x-image"), options,

                                   "test", bs, &child_format, false,

                                   &local_err);

    if (local_err) {

        ret = -EINVAL;

        error_propagate(errp, local_err);

        goto fail;

    ret = 0;

fail:

    qemu_opts_del(opts);

    return ret;


static void tcg_out_tlb_read(TCGContext *s, TCGReg addrlo, TCGReg addrhi,

                             int s_bits, int tlb_offset)

{

    TCGReg base = TCG_AREG0;

    /* Should generate something like the following:

     * pre-v7:

     *   shr    tmp, addr_reg, #TARGET_PAGE_BITS                  (1)

     *   add    r2, env, #off & 0xff00

     *   and    r0, tmp, #(CPU_TLB_SIZE - 1)                      (2)

     *   add    r2, r2, r0, lsl #CPU_TLB_ENTRY_BITS               (3)

     *   ldr    r0, [r2, #off & 0xff]!                            (4)

     *   tst    addr_reg, #s_mask

     *   cmpeq  r0, tmp, lsl #TARGET_PAGE_BITS                    (5)

     *

     * v7 (not implemented yet):

     *   ubfx   r2, addr_reg, #TARGET_PAGE_BITS, #CPU_TLB_BITS    (1)

     *   movw   tmp, #~TARGET_PAGE_MASK & ~s_mask

     *   movw   r0, #off

     *   add    r2, env, r2, lsl #CPU_TLB_ENTRY_BITS              (2)

     *   bic    tmp, addr_reg, tmp

     *   ldr    r0, [r2, r0]!                                     (3)

     *   cmp    r0, tmp                                           (4)

     */

#  if CPU_TLB_BITS > 8

#   error

#  endif

    tcg_out_dat_reg(s, COND_AL, ARITH_MOV, TCG_REG_TMP,

                    0, addrlo, SHIFT_IMM_LSR(TARGET_PAGE_BITS));

    /* We assume that the offset is contained within 16 bits.  */

    assert((tlb_offset & ~0xffff) == 0);

    if (tlb_offset > 0xff) {

        tcg_out_dat_imm(s, COND_AL, ARITH_ADD, TCG_REG_R2, base,

                        (24 << 7) | (tlb_offset >> 8));

        tlb_offset &= 0xff;

        base = TCG_REG_R2;

    }

    tcg_out_dat_imm(s, COND_AL, ARITH_AND,

                    TCG_REG_R0, TCG_REG_TMP, CPU_TLB_SIZE - 1);

    tcg_out_dat_reg(s, COND_AL, ARITH_ADD, TCG_REG_R2, base,

                    TCG_REG_R0, SHIFT_IMM_LSL(CPU_TLB_ENTRY_BITS));

    /* Load the tlb comparator.  Use ldrd if needed and available,

       but due to how the pointer needs setting up, ldm isn't useful.

       Base arm5 doesn't have ldrd, but armv5te does.  */

    if (use_armv6_instructions && TARGET_LONG_BITS == 64) {

        tcg_out_memop_8(s, COND_AL, INSN_LDRD_IMM, TCG_REG_R0,

                        TCG_REG_R2, tlb_offset, 1, 1);

    } else {

        tcg_out_memop_12(s, COND_AL, INSN_LDR_IMM, TCG_REG_R0,

                         TCG_REG_R2, tlb_offset, 1, 1);

        if (TARGET_LONG_BITS == 64) {

            tcg_out_memop_12(s, COND_AL, INSN_LDR_IMM, TCG_REG_R1,

                             TCG_REG_R2, 4, 1, 0);

        }

    }

    /* Check alignment.  */

    if (s_bits) {

        tcg_out_dat_imm(s, COND_AL, ARITH_TST,

                        0, addrlo, (1 << s_bits) - 1);

    }

    tcg_out_dat_reg(s, (s_bits ? COND_EQ : COND_AL), ARITH_CMP, 0,

                    TCG_REG_R0, TCG_REG_TMP, SHIFT_IMM_LSL(TARGET_PAGE_BITS));

    if (TARGET_LONG_BITS == 64) {

        tcg_out_dat_reg(s, COND_EQ, ARITH_CMP, 0,

                        TCG_REG_R1, addrhi, SHIFT_IMM_LSL(0));

    }

}


static void qdm2_decode_super_block(QDM2Context *q)

{

    GetBitContext gb;

    QDM2SubPacket header, *packet;

    int i, packet_bytes, sub_packet_size, sub_packets_D;

    unsigned int next_index = 0;

    memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));

    memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));

    memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));

    q->sub_packets_B = 0;

    sub_packets_D    = 0;

    average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]

    init_get_bits(&gb, q->compressed_data, q->compressed_size * 8);

    qdm2_decode_sub_packet_header(&gb, &header);

    if (header.type < 2 || header.type >= 8) {

        q->has_errors = 1;

        av_log(NULL, AV_LOG_ERROR, "bad superblock type\n");

        return;

    }

    q->superblocktype_2_3 = (header.type == 2 || header.type == 3);

    packet_bytes          = (q->compressed_size - get_bits_count(&gb) / 8);

    init_get_bits(&gb, header.data, header.size * 8);

    if (header.type == 2 || header.type == 4 || header.type == 5) {

        int csum = 257 * get_bits(&gb, 8);

        csum += 2 * get_bits(&gb, 8);

        csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);

        if (csum != 0) {

            q->has_errors = 1;

            av_log(NULL, AV_LOG_ERROR, "bad packet checksum\n");

            return;

        }

    }

    q->sub_packet_list_B[0].packet = NULL;

    q->sub_packet_list_D[0].packet = NULL;

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

        if (--q->fft_level_exp[i] < 0)

            q->fft_level_exp[i] = 0;

    for (i = 0; packet_bytes > 0; i++) {

        int j;

        if (i >= FF_ARRAY_ELEMS(q->sub_packet_list_A)) {

            SAMPLES_NEEDED_2("too many packet bytes");

            return;

        }

        q->sub_packet_list_A[i].next = NULL;

        if (i > 0) {

            q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];

            /* seek to next block */

            init_get_bits(&gb, header.data, header.size * 8);

            skip_bits(&gb, next_index * 8);

            if (next_index >= header.size)

                break;

        }

        /* decode subpacket */

        packet = &q->sub_packets[i];

        qdm2_decode_sub_packet_header(&gb, packet);

        next_index      = packet->size + get_bits_count(&gb) / 8;

        sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;

        if (packet->type == 0)

            break;

        if (sub_packet_size > packet_bytes) {

            if (packet->type != 10 && packet->type != 11 && packet->type != 12)

                break;

            packet->size += packet_bytes - sub_packet_size;

        }

        packet_bytes -= sub_packet_size;

        /* add subpacket to 'all subpackets' list */

        q->sub_packet_list_A[i].packet = packet;

        /* add subpacket to related list */

        if (packet->type == 8) {

            SAMPLES_NEEDED_2("packet type 8");

            return;

        } else if (packet->type >= 9 && packet->type <= 12) {

            /* packets for MPEG Audio like Synthesis Filter */

            QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);

        } else if (packet->type == 13) {

            for (j = 0; j < 6; j++)

                q->fft_level_exp[j] = get_bits(&gb, 6);

        } else if (packet->type == 14) {

            for (j = 0; j < 6; j++)

                q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);

        } else if (packet->type == 15) {

            SAMPLES_NEEDED_2("packet type 15")

            return;

        } else if (packet->type >= 16 && packet->type < 48 &&

                   !fft_subpackets[packet->type - 16]) {

            /* packets for FFT */

            QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);

        }

    } // Packet bytes loop

    if (q->sub_packet_list_D[0].packet != NULL) {

        process_synthesis_subpackets(q, q->sub_packet_list_D);

        q->do_synth_filter = 1;

    } else if (q->do_synth_filter) {

        process_subpacket_10(q, NULL);

        process_subpacket_11(q, NULL);

        process_subpacket_12(q, NULL);

    }

}


static void hScale8To15_c(SwsContext *c, int16_t *dst, int dstW, const uint8_t *src,

                          const int16_t *filter, const int16_t *filterPos,

                          int filterSize)

{

    int i;

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

        int j;

        int srcPos= filterPos[i];

        int val=0;

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

            val += ((int)src[srcPos + j])*filter[filterSize*i + j];

        }

        //filter += hFilterSize;

        dst[i] = FFMIN(val>>7, (1<<15)-1); // the cubic equation does overflow ...

        //dst[i] = val>>7;

    }

}


MigrationState *migrate_get_current(void)

{

    static MigrationState current_migration = {

        .state = MIG_STATE_NONE,

        .bandwidth_limit = MAX_THROTTLE,

        .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,

        .mbps = -1,

    };

    return &current_migration;

}


qemu_co_sendv_recvv(int sockfd, struct iovec *iov, unsigned iov_cnt,

                    size_t offset, size_t bytes, bool do_send)

{

    size_t done = 0;

    ssize_t ret;

    while (done < bytes) {

        ret = iov_send_recv(sockfd, iov,

                            offset + done, bytes - done, do_send);

        if (ret > 0) {

            done += ret;

        } else if (ret < 0) {

            if (errno == EAGAIN) {

                qemu_coroutine_yield();

            } else if (done == 0) {

                return -1;

            } else {

                break;

            }

        } else if (ret == 0 && !do_send) {

            /* write (send) should never return 0.

             * read (recv) returns 0 for end-of-file (-data).

             * In both cases there's little point retrying,

             * but we do for write anyway, just in case */

            break;

        }

    }

    return done;

}


static int qcow2_change_backing_file(BlockDriverState *bs,

    const char *backing_file, const char *backing_fmt)

{

    return qcow2_update_ext_header(bs, backing_file, backing_fmt);

}


static void av_always_inline filter_mb_edgech( uint8_t *pix, int stride, const int16_t bS[4], unsigned int qp, H264Context *h ) {

    const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    const unsigned int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[qp - qp_bd_offset + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]]+1;

        tc[1] = tc0_table[index_a][bS[1]]+1;

        tc[2] = tc0_table[index_a][bS[2]]+1;

        tc[3] = tc0_table[index_a][bS[3]]+1;

        h->h264dsp.h264_v_loop_filter_chroma(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_v_loop_filter_chroma_intra(pix, stride, alpha, beta);

    }

}


static void sun4d_hw_init(const struct sun4d_hwdef *hwdef, ram_addr_t RAM_size,

                          const char *boot_device,

                          DisplayState *ds, const char *kernel_filename,

                          const char *kernel_cmdline,

                          const char *initrd_filename, const char *cpu_model)

{

    CPUState *env, *envs[MAX_CPUS];

    unsigned int i;

    void *iounits[MAX_IOUNITS], *espdma, *ledma, *main_esp, *nvram, *sbi;

    qemu_irq *cpu_irqs[MAX_CPUS], *sbi_irq, *sbi_cpu_irq,

        *espdma_irq, *ledma_irq;

    qemu_irq *esp_reset, *le_reset;

    ram_addr_t ram_offset, prom_offset, tcx_offset;

    unsigned long kernel_size;

    int ret;

    char buf[1024];

    int drive_index;

    void *fw_cfg;

    /* init CPUs */

    if (!cpu_model)

        cpu_model = hwdef->default_cpu_model;

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

        env = cpu_init(cpu_model);

        if (!env) {

            fprintf(stderr, "qemu: Unable to find Sparc CPU definition\n");

            exit(1);

        }

        cpu_sparc_set_id(env, i);

        envs[i] = env;

        if (i == 0) {

            qemu_register_reset(main_cpu_reset, env);

        } else {

            qemu_register_reset(secondary_cpu_reset, env);

            env->halted = 1;

        }

        cpu_irqs[i] = qemu_allocate_irqs(cpu_set_irq, envs[i], MAX_PILS);

        env->prom_addr = hwdef->slavio_base;

    }

    for (i = smp_cpus; i < MAX_CPUS; i++)

        cpu_irqs[i] = qemu_allocate_irqs(dummy_cpu_set_irq, NULL, MAX_PILS);

    /* allocate RAM */

    if ((uint64_t)RAM_size > hwdef->max_mem) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d, maximum %d\n",

                (unsigned int)(RAM_size / (1024 * 1024)),

                (unsigned int)(hwdef->max_mem / (1024 * 1024)));

        exit(1);

    }

    ram_offset = qemu_ram_alloc(RAM_size);

    cpu_register_physical_memory(0, RAM_size, ram_offset);

    /* load boot prom */

    prom_offset = qemu_ram_alloc(PROM_SIZE_MAX);

    cpu_register_physical_memory(hwdef->slavio_base,

                                 (PROM_SIZE_MAX + TARGET_PAGE_SIZE - 1) &

                                 TARGET_PAGE_MASK,

                                 prom_offset | IO_MEM_ROM);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    snprintf(buf, sizeof(buf), "%s/%s", bios_dir, bios_name);

    ret = load_elf(buf, hwdef->slavio_base - PROM_VADDR, NULL, NULL, NULL);

    if (ret < 0 || ret > PROM_SIZE_MAX)

        ret = load_image_targphys(buf, hwdef->slavio_base, PROM_SIZE_MAX);

    if (ret < 0 || ret > PROM_SIZE_MAX) {

        fprintf(stderr, "qemu: could not load prom '%s'\n",

                buf);

        exit(1);

    }

    /* set up devices */

    sbi = sbi_init(hwdef->sbi_base, &sbi_irq, &sbi_cpu_irq, cpu_irqs);

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

        if (hwdef->iounit_bases[i] != (target_phys_addr_t)-1)

            iounits[i] = iommu_init(hwdef->iounit_bases[i],

                                    hwdef->iounit_version,

                                    sbi_irq[hwdef->me_irq]);

    espdma = sparc32_dma_init(hwdef->espdma_base, sbi_irq[hwdef->esp_irq],

                              iounits[0], &espdma_irq, &esp_reset);

    ledma = sparc32_dma_init(hwdef->ledma_base, sbi_irq[hwdef->le_irq],

                             iounits[0], &ledma_irq, &le_reset);

    if (graphic_depth != 8 && graphic_depth != 24) {

        fprintf(stderr, "qemu: Unsupported depth: %d\n", graphic_depth);

        exit (1);

    }

    tcx_offset = qemu_ram_alloc(hwdef->vram_size);

    tcx_init(ds, hwdef->tcx_base, phys_ram_base + tcx_offset, tcx_offset,

             hwdef->vram_size, graphic_width, graphic_height, graphic_depth);

    if (nd_table[0].model == NULL)

        nd_table[0].model = "lance";

    if (strcmp(nd_table[0].model, "lance") == 0) {

        lance_init(&nd_table[0], hwdef->le_base, ledma, *ledma_irq, le_reset);

    } else if (strcmp(nd_table[0].model, "?") == 0) {

        fprintf(stderr, "qemu: Supported NICs: lance\n");

        exit (1);

    } else {

        fprintf(stderr, "qemu: Unsupported NIC: %s\n", nd_table[0].model);

        exit (1);

    }

    nvram = m48t59_init(sbi_irq[0], hwdef->nvram_base, 0,

                        hwdef->nvram_size, 8);

    slavio_timer_init_all(hwdef->counter_base, sbi_irq[hwdef->clock1_irq],

                          sbi_cpu_irq, smp_cpus);

    slavio_serial_ms_kbd_init(hwdef->ms_kb_base, sbi_irq[hwdef->ms_kb_irq],

                              nographic, ESCC_CLOCK, 1);

    // Slavio TTYA (base+4, Linux ttyS0) is the first Qemu serial device

    // Slavio TTYB (base+0, Linux ttyS1) is the second Qemu serial device

    escc_init(hwdef->serial_base, sbi_irq[hwdef->ser_irq], serial_hds[1],

              serial_hds[0], ESCC_CLOCK, 1);

    if (drive_get_max_bus(IF_SCSI) > 0) {

        fprintf(stderr, "qemu: too many SCSI bus\n");

        exit(1);

    }

    main_esp = esp_init(hwdef->esp_base, 2,

                        espdma_memory_read, espdma_memory_write,

                        espdma, *espdma_irq, esp_reset);

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

        drive_index = drive_get_index(IF_SCSI, 0, i);

        if (drive_index == -1)

            continue;

        esp_scsi_attach(main_esp, drives_table[drive_index].bdrv, i);

    }

    kernel_size = sun4m_load_kernel(kernel_filename, initrd_filename,

                                    RAM_size);

    nvram_init(nvram, (uint8_t *)&nd_table[0].macaddr, kernel_cmdline,

               boot_device, RAM_size, kernel_size, graphic_width,

               graphic_height, graphic_depth, hwdef->nvram_machine_id,

               "Sun4d");

    fw_cfg = fw_cfg_init(0, 0, CFG_ADDR, CFG_ADDR + 2);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, hwdef->machine_id);

}


static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested)

{

    int num_cq_events = 0, ret = 0;

    struct ibv_cq *cq;

    void *cq_ctx;

    uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;

    if (ibv_req_notify_cq(rdma->cq, 0)) {

        return -1;

    }

    /* poll cq first */

    while (wr_id != wrid_requested) {

        ret = qemu_rdma_poll(rdma, &wr_id_in);

        if (ret < 0) {

            return ret;

        }

        wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

        if (wr_id == RDMA_WRID_NONE) {

            break;

        }

        if (wr_id != wrid_requested) {

            DDDPRINTF("A Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",

                print_wrid(wrid_requested),

                wrid_requested, print_wrid(wr_id), wr_id);

        }

    }

    if (wr_id == wrid_requested) {

        return 0;

    }

    while (1) {

        /*

         * Coroutine doesn't start until process_incoming_migration()

         * so don't yield unless we know we're running inside of a coroutine.

         */

        if (rdma->migration_started_on_destination) {

            yield_until_fd_readable(rdma->comp_channel->fd);

        }

        if (ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx)) {

            perror("ibv_get_cq_event");

            goto err_block_for_wrid;

        }

        num_cq_events++;

        if (ibv_req_notify_cq(cq, 0)) {

            goto err_block_for_wrid;

        }

        while (wr_id != wrid_requested) {

            ret = qemu_rdma_poll(rdma, &wr_id_in);

            if (ret < 0) {

                goto err_block_for_wrid;

            }

            wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

            if (wr_id == RDMA_WRID_NONE) {

                break;

            }

            if (wr_id != wrid_requested) {

                DDDPRINTF("B Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",

                    print_wrid(wrid_requested), wrid_requested,

                    print_wrid(wr_id), wr_id);

            }

        }

        if (wr_id == wrid_requested) {

            goto success_block_for_wrid;

        }

    }

success_block_for_wrid:

    if (num_cq_events) {

        ibv_ack_cq_events(cq, num_cq_events);

    }

    return 0;

err_block_for_wrid:

    if (num_cq_events) {

        ibv_ack_cq_events(cq, num_cq_events);

    }

    return ret;

}


static inline void RENAME(rgb15to32)(const uint8_t *src, uint8_t *dst, int src_size)

{

    const uint16_t *end;

    const uint16_t *mm_end;

    uint8_t *d = dst;

    const uint16_t *s = (const uint16_t *)src;

    end = s + src_size/2;

    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");

    __asm__ volatile("pxor    %%mm7,%%mm7    \n\t":::"memory");

    __asm__ volatile("pcmpeqd %%mm6,%%mm6    \n\t":::"memory");

    mm_end = end - 3;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

            "movq          %1, %%mm0    \n\t"

            "movq          %1, %%mm1    \n\t"

            "movq          %1, %%mm2    \n\t"

            "pand          %2, %%mm0    \n\t"

            "pand          %3, %%mm1    \n\t"

            "pand          %4, %%mm2    \n\t"

            "psllq         $3, %%mm0    \n\t"

            "psrlq         $2, %%mm1    \n\t"

            "psrlq         $7, %%mm2    \n\t"

            PACK_RGB32

            :"=m"(*d)

            :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r)

            :"memory");

        d += 16;

        s += 4;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

    while (s < end) {

        register uint16_t bgr;

        bgr = *s++;

        *d++ = (bgr&0x1F)<<3;

        *d++ = (bgr&0x3E0)>>2;

        *d++ = (bgr&0x7C00)>>7;

        *d++ = 255;

    }

}


static int mux_chr_can_read(void *opaque)

{

    CharDriverState *chr = opaque;

    MuxDriver *d = chr->opaque;

    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)

        return 1;

    if (d->chr_can_read[chr->focus])

        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);

    return 0;

}


static inline bool vtd_queued_inv_enable_check(IntelIOMMUState *s)

{

    return s->iq_tail == 0;

}


static av_always_inline void hcscale(SwsContext *c, int16_t *dst1, int16_t *dst2, int dstWidth,

                                     const uint8_t *src_in[4],

                                     int srcW, int xInc, const int16_t *hChrFilter,

                                     const int16_t *hChrFilterPos, int hChrFilterSize,

                                     uint8_t *formatConvBuffer, uint32_t *pal)

{

    const uint8_t *src1 = src_in[1], *src2 = src_in[2];

    if (c->chrToYV12) {

        uint8_t *buf2 = formatConvBuffer + FFALIGN(srcW * FFALIGN(c->srcBpc, 8) >> 3, 16);

        c->chrToYV12(formatConvBuffer, buf2, src1, src2, srcW, pal);

        src1= formatConvBuffer;

        src2= buf2;

    } else if (c->readChrPlanar) {

        uint8_t *buf2 = formatConvBuffer + FFALIGN(srcW * FFALIGN(c->srcBpc, 8) >> 3, 16);

        c->readChrPlanar(formatConvBuffer, buf2, src_in, srcW);

        src1= formatConvBuffer;

        src2= buf2;

    }

    if (!c->hcscale_fast) {

        c->hcScale(c, dst1, dstWidth, src1, hChrFilter, hChrFilterPos, hChrFilterSize);

        c->hcScale(c, dst2, dstWidth, src2, hChrFilter, hChrFilterPos, hChrFilterSize);

    } else { // fast bilinear upscale / crap downscale

        c->hcscale_fast(c, dst1, dst2, dstWidth, src1, src2, srcW, xInc);

    }

    if (c->chrConvertRange)

        c->chrConvertRange(dst1, dst2, dstWidth);

}