static void avc_loopfilter_luma_inter_edge_hor_msa(uint8_t *data,

                                                   uint8_t bs0, uint8_t bs1,

                                                   uint8_t bs2, uint8_t bs3,

                                                   uint8_t tc0, uint8_t tc1,

                                                   uint8_t tc2, uint8_t tc3,

                                                   uint8_t alpha_in,

                                                   uint8_t beta_in,

                                                   uint32_t image_width)

{

    v16u8 p2_asub_p0, u8_q2asub_q0;

    v16u8 alpha, beta, is_less_than, is_less_than_beta;

    v16u8 p1, p0, q0, q1;

    v8i16 p1_r = { 0 };

    v8i16 p0_r, q0_r, q1_r = { 0 };

    v8i16 p1_l = { 0 };

    v8i16 p0_l, q0_l, q1_l = { 0 };

    v16u8 p2_org, p1_org, p0_org, q0_org, q1_org, q2_org;

    v8i16 p2_org_r, p1_org_r, p0_org_r, q0_org_r, q1_org_r, q2_org_r;

    v8i16 p2_org_l, p1_org_l, p0_org_l, q0_org_l, q1_org_l, q2_org_l;

    v16i8 zero = { 0 };

    v16u8 tmp_vec;

    v16u8 bs = { 0 };

    v16i8 tc = { 0 };

    tmp_vec = (v16u8) __msa_fill_b(bs0);

    bs = (v16u8) __msa_insve_w((v4i32) bs, 0, (v4i32) tmp_vec);

    tmp_vec = (v16u8) __msa_fill_b(bs1);

    bs = (v16u8) __msa_insve_w((v4i32) bs, 1, (v4i32) tmp_vec);

    tmp_vec = (v16u8) __msa_fill_b(bs2);

    bs = (v16u8) __msa_insve_w((v4i32) bs, 2, (v4i32) tmp_vec);

    tmp_vec = (v16u8) __msa_fill_b(bs3);

    bs = (v16u8) __msa_insve_w((v4i32) bs, 3, (v4i32) tmp_vec);

    if (!__msa_test_bz_v(bs)) {

        tmp_vec = (v16u8) __msa_fill_b(tc0);

        tc = (v16i8) __msa_insve_w((v4i32) tc, 0, (v4i32) tmp_vec);

        tmp_vec = (v16u8) __msa_fill_b(tc1);

        tc = (v16i8) __msa_insve_w((v4i32) tc, 1, (v4i32) tmp_vec);

        tmp_vec = (v16u8) __msa_fill_b(tc2);

        tc = (v16i8) __msa_insve_w((v4i32) tc, 2, (v4i32) tmp_vec);

        tmp_vec = (v16u8) __msa_fill_b(tc3);

        tc = (v16i8) __msa_insve_w((v4i32) tc, 3, (v4i32) tmp_vec);

        alpha = (v16u8) __msa_fill_b(alpha_in);

        beta = (v16u8) __msa_fill_b(beta_in);

        p2_org = LOAD_UB(data - (3 * image_width));

        p1_org = LOAD_UB(data - (image_width << 1));

        p0_org = LOAD_UB(data - image_width);

        q0_org = LOAD_UB(data);

        q1_org = LOAD_UB(data + image_width);

        {

            v16u8 p0_asub_q0, p1_asub_p0, q1_asub_q0;

            v16u8 is_less_than_alpha, is_bs_greater_than0;

            is_bs_greater_than0 = ((v16u8) zero < bs);

            p0_asub_q0 = __msa_asub_u_b(p0_org, q0_org);

            p1_asub_p0 = __msa_asub_u_b(p1_org, p0_org);

            q1_asub_q0 = __msa_asub_u_b(q1_org, q0_org);

            is_less_than_alpha = (p0_asub_q0 < alpha);

            is_less_than_beta = (p1_asub_p0 < beta);

            is_less_than = is_less_than_beta & is_less_than_alpha;

            is_less_than_beta = (q1_asub_q0 < beta);

            is_less_than = is_less_than_beta & is_less_than;

            is_less_than = is_less_than & is_bs_greater_than0;

        }

        if (!__msa_test_bz_v(is_less_than)) {

            v16i8 sign_negate_tc, negate_tc;

            v8i16 negate_tc_r, i16_negatetc_l, tc_l, tc_r;

            q2_org = LOAD_UB(data + (2 * image_width));

            negate_tc = zero - tc;

            sign_negate_tc = __msa_clti_s_b(negate_tc, 0);

            negate_tc_r = (v8i16) __msa_ilvr_b(sign_negate_tc, negate_tc);

            i16_negatetc_l = (v8i16) __msa_ilvl_b(sign_negate_tc, negate_tc);

            tc_r = (v8i16) __msa_ilvr_b(zero, tc);

            tc_l = (v8i16) __msa_ilvl_b(zero, tc);

            p1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p1_org);

            p0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p0_org);

            q0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q0_org);

            p1_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p1_org);

            p0_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p0_org);

            q0_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q0_org);

            p2_asub_p0 = __msa_asub_u_b(p2_org, p0_org);

            is_less_than_beta = (p2_asub_p0 < beta);

            is_less_than_beta = is_less_than_beta & is_less_than;

            {

                v8u16 is_less_than_beta_r, is_less_than_beta_l;

                is_less_than_beta_r =

                    (v8u16) __msa_sldi_b((v16i8) is_less_than_beta, zero, 8);

                if (!__msa_test_bz_v((v16u8) is_less_than_beta_r)) {

                    p2_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p2_org);

                    AVC_LOOP_FILTER_P1_OR_Q1(p0_org_r, q0_org_r,

                                             p1_org_r, p2_org_r,

                                             negate_tc_r, tc_r, p1_r);

                }

                is_less_than_beta_l =

                    (v8u16) __msa_sldi_b(zero, (v16i8) is_less_than_beta, 8);

                if (!__msa_test_bz_v((v16u8) is_less_than_beta_l)) {

                    p2_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p2_org);

                    AVC_LOOP_FILTER_P1_OR_Q1(p0_org_l, q0_org_l,

                                             p1_org_l, p2_org_l,

                                             i16_negatetc_l, tc_l, p1_l);

                }

            }

            if (!__msa_test_bz_v(is_less_than_beta)) {

                p1 = (v16u8) __msa_pckev_b((v16i8) p1_l, (v16i8) p1_r);

                p1_org = __msa_bmnz_v(p1_org, p1, is_less_than_beta);

                STORE_UB(p1_org, data - (2 * image_width));

                is_less_than_beta = __msa_andi_b(is_less_than_beta, 1);

                tc = tc + (v16i8) is_less_than_beta;

            }

            u8_q2asub_q0 = __msa_asub_u_b(q2_org, q0_org);

            is_less_than_beta = (u8_q2asub_q0 < beta);

            is_less_than_beta = is_less_than_beta & is_less_than;

            {

                v8u16 is_less_than_beta_r, is_less_than_beta_l;

                is_less_than_beta_r =

                    (v8u16) __msa_sldi_b((v16i8) is_less_than_beta, zero, 8);

                q1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q1_org);

                if (!__msa_test_bz_v((v16u8) is_less_than_beta_r)) {

                    q2_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q2_org);

                    AVC_LOOP_FILTER_P1_OR_Q1(p0_org_r, q0_org_r,

                                             q1_org_r, q2_org_r,

                                             negate_tc_r, tc_r, q1_r);

                }

                is_less_than_beta_l =

                    (v8u16) __msa_sldi_b(zero, (v16i8) is_less_than_beta, 8);

                q1_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q1_org);

                if (!__msa_test_bz_v((v16u8) is_less_than_beta_l)) {

                    q2_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q2_org);

                    AVC_LOOP_FILTER_P1_OR_Q1(p0_org_l, q0_org_l,

                                             q1_org_l, q2_org_l,

                                             i16_negatetc_l, tc_l, q1_l);

                }

            }

            if (!__msa_test_bz_v(is_less_than_beta)) {

                q1 = (v16u8) __msa_pckev_b((v16i8) q1_l, (v16i8) q1_r);

                q1_org = __msa_bmnz_v(q1_org, q1, is_less_than_beta);

                STORE_UB(q1_org, data + image_width);

                is_less_than_beta = __msa_andi_b(is_less_than_beta, 1);

                tc = tc + (v16i8) is_less_than_beta;

            }

            {

                v16i8 negate_thresh, sign_negate_thresh;

                v8i16 threshold_r, threshold_l;

                v8i16 negate_thresh_l, negate_thresh_r;

                negate_thresh = zero - tc;

                sign_negate_thresh = __msa_clti_s_b(negate_thresh, 0);

                threshold_r = (v8i16) __msa_ilvr_b(zero, tc);

                negate_thresh_r = (v8i16) __msa_ilvr_b(sign_negate_thresh,

                                                       negate_thresh);

                AVC_LOOP_FILTER_P0Q0(q0_org_r, p0_org_r, p1_org_r, q1_org_r,

                                     negate_thresh_r, threshold_r, p0_r, q0_r);

                threshold_l = (v8i16) __msa_ilvl_b(zero, tc);

                negate_thresh_l = (v8i16) __msa_ilvl_b(sign_negate_thresh,

                                                       negate_thresh);

                AVC_LOOP_FILTER_P0Q0(q0_org_l, p0_org_l, p1_org_l, q1_org_l,

                                     negate_thresh_l, threshold_l, p0_l, q0_l);

            }

            p0 = (v16u8) __msa_pckev_b((v16i8) p0_l, (v16i8) p0_r);

            q0 = (v16u8) __msa_pckev_b((v16i8) q0_l, (v16i8) q0_r);

            p0_org = __msa_bmnz_v(p0_org, p0, is_less_than);

            q0_org = __msa_bmnz_v(q0_org, q0, is_less_than);

            STORE_UB(p0_org, (data - image_width));

            STORE_UB(q0_org, data);

        }

    }

}


void x86_cpu_list (FILE *f, int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

                  const char *optarg)

{

    unsigned char model = !strcmp("?model", optarg);

    unsigned char dump = !strcmp("?dump", optarg);

    unsigned char cpuid = !strcmp("?cpuid", optarg);

    x86_def_t *def;

    char buf[256];

    if (cpuid) {

        (*cpu_fprintf)(f, "Recognized CPUID flags:\n");

        listflags(buf, sizeof (buf), (uint32_t)~0, feature_name, 1);

        (*cpu_fprintf)(f, "  f_edx: %s\n", buf);

        listflags(buf, sizeof (buf), (uint32_t)~0, ext_feature_name, 1);

        (*cpu_fprintf)(f, "  f_ecx: %s\n", buf);

        listflags(buf, sizeof (buf), (uint32_t)~0, ext2_feature_name, 1);

        (*cpu_fprintf)(f, "  extf_edx: %s\n", buf);

        listflags(buf, sizeof (buf), (uint32_t)~0, ext3_feature_name, 1);

        (*cpu_fprintf)(f, "  extf_ecx: %s\n", buf);

        return;

    }

    for (def = x86_defs; def; def = def->next) {

        snprintf(buf, sizeof (buf), def->flags ? "[%s]": "%s", def->name);

        if (model || dump) {

            (*cpu_fprintf)(f, "x86 %16s  %-48s\n", buf, def->model_id);

        } else {

            (*cpu_fprintf)(f, "x86 %16s\n", buf);

        }

        if (dump) {

            memcpy(buf, &def->vendor1, sizeof (def->vendor1));

            memcpy(buf + 4, &def->vendor2, sizeof (def->vendor2));

            memcpy(buf + 8, &def->vendor3, sizeof (def->vendor3));

            buf[12] = '\0';

            (*cpu_fprintf)(f,

                "  family %d model %d stepping %d level %d xlevel 0x%x"

                " vendor \"%s\"\n",

                def->family, def->model, def->stepping, def->level,

                def->xlevel, buf);

            listflags(buf, sizeof (buf), def->features, feature_name, 0);

            (*cpu_fprintf)(f, "  feature_edx %08x (%s)\n", def->features,

                buf);

            listflags(buf, sizeof (buf), def->ext_features, ext_feature_name,

                0);

            (*cpu_fprintf)(f, "  feature_ecx %08x (%s)\n", def->ext_features,

                buf);

            listflags(buf, sizeof (buf), def->ext2_features, ext2_feature_name,

                0);

            (*cpu_fprintf)(f, "  extfeature_edx %08x (%s)\n",

                def->ext2_features, buf);

            listflags(buf, sizeof (buf), def->ext3_features, ext3_feature_name,

                0);

            (*cpu_fprintf)(f, "  extfeature_ecx %08x (%s)\n",

                def->ext3_features, buf);

            (*cpu_fprintf)(f, "\n");

        }

    }

    if (kvm_enabled()) {

        (*cpu_fprintf)(f, "x86 %16s\n", "[host]");

    }

}


static void dec_misc(DisasContext *dc, uint32_t insn)

{

    uint32_t op0, op1;

    uint32_t ra, rb, rd;

#ifdef OPENRISC_DISAS

    uint32_t L6, K5;

#endif

    uint32_t I16, I5, I11, N26, tmp;

    TCGMemOp mop;

    op0 = extract32(insn, 26, 6);

    op1 = extract32(insn, 24, 2);

    ra = extract32(insn, 16, 5);

    rb = extract32(insn, 11, 5);

    rd = extract32(insn, 21, 5);

#ifdef OPENRISC_DISAS

    L6 = extract32(insn, 5, 6);

    K5 = extract32(insn, 0, 5);

#endif

    I16 = extract32(insn, 0, 16);

    I5 = extract32(insn, 21, 5);

    I11 = extract32(insn, 0, 11);

    N26 = extract32(insn, 0, 26);

    tmp = (I5<<11) + I11;

    switch (op0) {

    case 0x00:    /* l.j */

        LOG_DIS("l.j %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x01:    /* l.jal */

        LOG_DIS("l.jal %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x03:    /* l.bnf */

        LOG_DIS("l.bnf %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x04:    /* l.bf */

        LOG_DIS("l.bf %d\n", N26);

        gen_jump(dc, N26, 0, op0);

        break;

    case 0x05:

        switch (op1) {

        case 0x01:    /* l.nop */

            LOG_DIS("l.nop %d\n", I16);

            break;

        default:

            gen_illegal_exception(dc);

            break;

        }

        break;

    case 0x11:    /* l.jr */

        LOG_DIS("l.jr r%d\n", rb);

         gen_jump(dc, 0, rb, op0);

         break;

    case 0x12:    /* l.jalr */

        LOG_DIS("l.jalr r%d\n", rb);

        gen_jump(dc, 0, rb, op0);

        break;

    case 0x13:    /* l.maci */

        LOG_DIS("l.maci %d, r%d, %d\n", I5, ra, I11);

        {

            TCGv_i64 t1 = tcg_temp_new_i64();

            TCGv_i64 t2 = tcg_temp_new_i64();

            TCGv_i32 dst = tcg_temp_new_i32();

            TCGv ttmp = tcg_const_tl(tmp);

            tcg_gen_mul_tl(dst, cpu_R[ra], ttmp);

            tcg_gen_ext_i32_i64(t1, dst);

            tcg_gen_concat_i32_i64(t2, maclo, machi);

            tcg_gen_add_i64(t2, t2, t1);

            tcg_gen_trunc_i64_i32(maclo, t2);

            tcg_gen_shri_i64(t2, t2, 32);

            tcg_gen_trunc_i64_i32(machi, t2);

            tcg_temp_free_i32(dst);

            tcg_temp_free(ttmp);

            tcg_temp_free_i64(t1);

            tcg_temp_free_i64(t2);

        }

        break;

    case 0x09:    /* l.rfe */

        LOG_DIS("l.rfe\n");

        {

#if defined(CONFIG_USER_ONLY)

            return;

#else

            if (dc->mem_idx == MMU_USER_IDX) {

                gen_illegal_exception(dc);

                return;

            }

            gen_helper_rfe(cpu_env);

            dc->is_jmp = DISAS_UPDATE;

#endif

        }

        break;

    case 0x1c:    /* l.cust1 */

        LOG_DIS("l.cust1\n");

        break;

    case 0x1d:    /* l.cust2 */

        LOG_DIS("l.cust2\n");

        break;

    case 0x1e:    /* l.cust3 */

        LOG_DIS("l.cust3\n");

        break;

    case 0x1f:    /* l.cust4 */

        LOG_DIS("l.cust4\n");

        break;

    case 0x3c:    /* l.cust5 */

        LOG_DIS("l.cust5 r%d, r%d, r%d, %d, %d\n", rd, ra, rb, L6, K5);

        break;

    case 0x3d:    /* l.cust6 */

        LOG_DIS("l.cust6\n");

        break;

    case 0x3e:    /* l.cust7 */

        LOG_DIS("l.cust7\n");

        break;

    case 0x3f:    /* l.cust8 */

        LOG_DIS("l.cust8\n");

        break;

/* not used yet, open it when we need or64.  */

/*#ifdef TARGET_OPENRISC64

    case 0x20:     l.ld

        LOG_DIS("l.ld r%d, r%d, %d\n", rd, ra, I16);

        check_ob64s(dc);

        mop = MO_TEQ;

        goto do_load;

#endif*/

    case 0x21:    /* l.lwz */

        LOG_DIS("l.lwz r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TEUL;

        goto do_load;

    case 0x22:    /* l.lws */

        LOG_DIS("l.lws r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TESL;

        goto do_load;

    case 0x23:    /* l.lbz */

        LOG_DIS("l.lbz r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_UB;

        goto do_load;

    case 0x24:    /* l.lbs */

        LOG_DIS("l.lbs r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_SB;

        goto do_load;

    case 0x25:    /* l.lhz */

        LOG_DIS("l.lhz r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TEUW;

        goto do_load;

    case 0x26:    /* l.lhs */

        LOG_DIS("l.lhs r%d, r%d, %d\n", rd, ra, I16);

        mop = MO_TESW;

        goto do_load;

    do_load:

        {

            TCGv t0 = tcg_temp_new();

            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(I16, 16));

            tcg_gen_qemu_ld_tl(cpu_R[rd], t0, dc->mem_idx, mop);

            tcg_temp_free(t0);

        }

        break;

    case 0x27:    /* l.addi */

        LOG_DIS("l.addi r%d, r%d, %d\n", rd, ra, I16);

        {

            if (I16 == 0) {

                tcg_gen_mov_tl(cpu_R[rd], cpu_R[ra]);

            } else {

                int lab = gen_new_label();

                TCGv_i64 ta = tcg_temp_new_i64();

                TCGv_i64 td = tcg_temp_local_new_i64();

                TCGv_i32 res = tcg_temp_local_new_i32();

                TCGv_i32 sr_ove = tcg_temp_local_new_i32();

                tcg_gen_extu_i32_i64(ta, cpu_R[ra]);

                tcg_gen_addi_i64(td, ta, sign_extend(I16, 16));

                tcg_gen_trunc_i64_i32(res, td);

                tcg_gen_shri_i64(td, td, 32);

                tcg_gen_andi_i64(td, td, 0x3);

                /* Jump to lab when no overflow.  */

                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x0, lab);

                tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x3, lab);

                tcg_gen_ori_i32(cpu_sr, cpu_sr, (SR_OV | SR_CY));

                tcg_gen_andi_i32(sr_ove, cpu_sr, SR_OVE);

                tcg_gen_brcondi_i32(TCG_COND_NE, sr_ove, SR_OVE, lab);

                gen_exception(dc, EXCP_RANGE);

                gen_set_label(lab);

                tcg_gen_mov_i32(cpu_R[rd], res);

                tcg_temp_free_i64(ta);

                tcg_temp_free_i64(td);

                tcg_temp_free_i32(res);

                tcg_temp_free_i32(sr_ove);

            }

        }

        break;

    case 0x28:    /* l.addic */

        LOG_DIS("l.addic r%d, r%d, %d\n", rd, ra, I16);

        {

            int lab = gen_new_label();

            TCGv_i64 ta = tcg_temp_new_i64();

            TCGv_i64 td = tcg_temp_local_new_i64();

            TCGv_i64 tcy = tcg_temp_local_new_i64();

            TCGv_i32 res = tcg_temp_local_new_i32();

            TCGv_i32 sr_cy = tcg_temp_local_new_i32();

            TCGv_i32 sr_ove = tcg_temp_local_new_i32();

            tcg_gen_extu_i32_i64(ta, cpu_R[ra]);

            tcg_gen_andi_i32(sr_cy, cpu_sr, SR_CY);

            tcg_gen_shri_i32(sr_cy, sr_cy, 10);

            tcg_gen_extu_i32_i64(tcy, sr_cy);

            tcg_gen_addi_i64(td, ta, sign_extend(I16, 16));

            tcg_gen_add_i64(td, td, tcy);

            tcg_gen_trunc_i64_i32(res, td);

            tcg_gen_shri_i64(td, td, 32);

            tcg_gen_andi_i64(td, td, 0x3);

            /* Jump to lab when no overflow.  */

            tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x0, lab);

            tcg_gen_brcondi_i64(TCG_COND_EQ, td, 0x3, lab);

            tcg_gen_ori_i32(cpu_sr, cpu_sr, (SR_OV | SR_CY));

            tcg_gen_andi_i32(sr_ove, cpu_sr, SR_OVE);

            tcg_gen_brcondi_i32(TCG_COND_NE, sr_ove, SR_OVE, lab);

            gen_exception(dc, EXCP_RANGE);

            gen_set_label(lab);

            tcg_gen_mov_i32(cpu_R[rd], res);

            tcg_temp_free_i64(ta);

            tcg_temp_free_i64(td);

            tcg_temp_free_i64(tcy);

            tcg_temp_free_i32(res);

            tcg_temp_free_i32(sr_cy);

            tcg_temp_free_i32(sr_ove);

        }

        break;

    case 0x29:    /* l.andi */

        LOG_DIS("l.andi r%d, r%d, %d\n", rd, ra, I16);

        tcg_gen_andi_tl(cpu_R[rd], cpu_R[ra], zero_extend(I16, 16));

        break;

    case 0x2a:    /* l.ori */

        LOG_DIS("l.ori r%d, r%d, %d\n", rd, ra, I16);

        tcg_gen_ori_tl(cpu_R[rd], cpu_R[ra], zero_extend(I16, 16));

        break;

    case 0x2b:    /* l.xori */

        LOG_DIS("l.xori r%d, r%d, %d\n", rd, ra, I16);

        tcg_gen_xori_tl(cpu_R[rd], cpu_R[ra], sign_extend(I16, 16));

        break;

    case 0x2c:    /* l.muli */

        LOG_DIS("l.muli r%d, r%d, %d\n", rd, ra, I16);

        if (ra != 0 && I16 != 0) {

            TCGv_i32 im = tcg_const_i32(I16);

            gen_helper_mul32(cpu_R[rd], cpu_env, cpu_R[ra], im);

            tcg_temp_free_i32(im);

        } else {

            tcg_gen_movi_tl(cpu_R[rd], 0x0);

        }

        break;

    case 0x2d:    /* l.mfspr */

        LOG_DIS("l.mfspr r%d, r%d, %d\n", rd, ra, I16);

        {

#if defined(CONFIG_USER_ONLY)

            return;

#else

            TCGv_i32 ti = tcg_const_i32(I16);

            if (dc->mem_idx == MMU_USER_IDX) {

                gen_illegal_exception(dc);

                return;

            }

            gen_helper_mfspr(cpu_R[rd], cpu_env, cpu_R[rd], cpu_R[ra], ti);

            tcg_temp_free_i32(ti);

#endif

        }

        break;

    case 0x30:    /* l.mtspr */

        LOG_DIS("l.mtspr %d, r%d, r%d, %d\n", I5, ra, rb, I11);

        {

#if defined(CONFIG_USER_ONLY)

            return;

#else

            TCGv_i32 im = tcg_const_i32(tmp);

            if (dc->mem_idx == MMU_USER_IDX) {

                gen_illegal_exception(dc);

                return;

            }

            gen_helper_mtspr(cpu_env, cpu_R[ra], cpu_R[rb], im);

            tcg_temp_free_i32(im);

#endif

        }

        break;

/* not used yet, open it when we need or64.  */

/*#ifdef TARGET_OPENRISC64

    case 0x34:     l.sd

        LOG_DIS("l.sd %d, r%d, r%d, %d\n", I5, ra, rb, I11);

        check_ob64s(dc);

        mop = MO_TEQ;

        goto do_store;

#endif*/

    case 0x35:    /* l.sw */

        LOG_DIS("l.sw %d, r%d, r%d, %d\n", I5, ra, rb, I11);

        mop = MO_TEUL;

        goto do_store;

    case 0x36:    /* l.sb */

        LOG_DIS("l.sb %d, r%d, r%d, %d\n", I5, ra, rb, I11);

        mop = MO_UB;

        goto do_store;

    case 0x37:    /* l.sh */

        LOG_DIS("l.sh %d, r%d, r%d, %d\n", I5, ra, rb, I11);

        mop = MO_TEUW;

        goto do_store;

    do_store:

        {

            TCGv t0 = tcg_temp_new();

            tcg_gen_addi_tl(t0, cpu_R[ra], sign_extend(tmp, 16));

            tcg_gen_qemu_st_tl(cpu_R[rb], t0, dc->mem_idx, mop);

            tcg_temp_free(t0);

        }

        break;

    default:

        gen_illegal_exception(dc);

        break;

    }

}


int socket_connect(SocketAddress *addr, NonBlockingConnectHandler *callback,

                   void *opaque, Error **errp)

{

    int fd;

    switch (addr->type) {

    case SOCKET_ADDRESS_KIND_INET:

        fd = inet_connect_saddr(addr->u.inet.data, callback, opaque, errp);

        break;

    case SOCKET_ADDRESS_KIND_UNIX:

        fd = unix_connect_saddr(addr->u.q_unix.data, callback, opaque, errp);

        break;

    case SOCKET_ADDRESS_KIND_FD:

        fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);

        if (fd >= 0 && callback) {

            qemu_set_nonblock(fd);

            callback(fd, NULL, opaque);

        }

        break;

    case SOCKET_ADDRESS_KIND_VSOCK:

        fd = vsock_connect_saddr(addr->u.vsock.data, callback, opaque, errp);

        break;

    default:

        abort();

    }

    return fd;

}


static av_cold int init(AVFilterContext *ctx)

{

    FormatContext *s = ctx->priv;

    char *cur, *sep;

    int nb_formats = 1;

    int i;

    int ret;

    /* count the formats */

    cur = s->pix_fmts;

    while ((cur = strchr(cur, '|'))) {

        nb_formats++;

        if (*cur)

            cur++;

    }

    s->formats = av_malloc_array(nb_formats + 1, sizeof(*s->formats));

    if (!s->formats)

        return AVERROR(ENOMEM);

    if (!s->pix_fmts)

        return AVERROR(EINVAL);

    /* parse the list of formats */

    cur = s->pix_fmts;

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

        sep = strchr(cur, '|');

        if (sep)

            *sep++ = 0;

        if ((ret = ff_parse_pixel_format(&s->formats[i], cur, ctx)) < 0)

            return ret;

        cur = sep;

    }

    s->formats[nb_formats] = AV_PIX_FMT_NONE;

    if (!strcmp(ctx->filter->name, "noformat")) {

        const AVPixFmtDescriptor *desc = NULL;

        enum AVPixelFormat *formats_allowed;

        int nb_formats_lavu = 0, nb_formats_allowed = 0;

        /* count the formats known to lavu */

        while ((desc = av_pix_fmt_desc_next(desc)))

            nb_formats_lavu++;

        formats_allowed = av_malloc_array(nb_formats_lavu + 1, sizeof(*formats_allowed));

        if (!formats_allowed)

            return AVERROR(ENOMEM);

        /* for each format known to lavu, check if it's in the list of

         * forbidden formats */

        while ((desc = av_pix_fmt_desc_next(desc))) {

            enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(desc);

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

                if (s->formats[i] == pix_fmt)

                    break;

            }

            if (i < nb_formats)

                continue;

            formats_allowed[nb_formats_allowed++] = pix_fmt;

        }

        formats_allowed[nb_formats_allowed] = AV_PIX_FMT_NONE;

        av_freep(&s->formats);

        s->formats = formats_allowed;

    }

    return 0;

}


static void tcg_commit(MemoryListener *listener)

{

    CPUAddressSpace *cpuas;

    AddressSpaceDispatch *d;

    /* since each CPU stores ram addresses in its TLB cache, we must

       reset the modified entries */

    cpuas = container_of(listener, CPUAddressSpace, tcg_as_listener);

    cpu_reloading_memory_map();

    /* The CPU and TLB are protected by the iothread lock.

     * We reload the dispatch pointer now because cpu_reloading_memory_map()

     * may have split the RCU critical section.

     */

    d = atomic_rcu_read(&cpuas->as->dispatch);

    cpuas->memory_dispatch = d;

    tlb_flush(cpuas->cpu, 1);

}


static int qemu_chr_open_null(QemuOpts *opts, CharDriverState **_chr)

{

    CharDriverState *chr;

    chr = g_malloc0(sizeof(CharDriverState));

    chr->chr_write = null_chr_write;

    *_chr= chr;

    return 0;

}


void host_net_remove_completion(ReadLineState *rs, int nb_args, const char *str)

{

    NetClientState *ncs[MAX_QUEUE_NUM];

    int count, i, len;

    len = strlen(str);

    readline_set_completion_index(rs, len);

    if (nb_args == 2) {

        count = qemu_find_net_clients_except(NULL, ncs,

                                             NET_CLIENT_OPTIONS_KIND_NONE,

                                             MAX_QUEUE_NUM);

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

            int id;

            char name[16];

            if (net_hub_id_for_client(ncs[i], &id)) {

                continue;

            }

            snprintf(name, sizeof(name), "%d", id);

            if (!strncmp(str, name, len)) {

                readline_add_completion(rs, name);

            }

        }

        return;

    } else if (nb_args == 3) {

        count = qemu_find_net_clients_except(NULL, ncs,

                                             NET_CLIENT_OPTIONS_KIND_NIC,

                                             MAX_QUEUE_NUM);

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

            int id;

            const char *name;

            if (ncs[i]->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT ||

                net_hub_id_for_client(ncs[i], &id)) {

                continue;

            }

            name = ncs[i]->name;

            if (!strncmp(str, name, len)) {

                readline_add_completion(rs, name);

            }

        }

        return;

    }

}


int ff_mpeg_update_thread_context(AVCodecContext *dst,

                                  const AVCodecContext *src)

{

    MpegEncContext *s = dst->priv_data, *s1 = src->priv_data;

    if (dst == src || !s1->context_initialized)

        return 0;

    // FIXME can parameters change on I-frames?

    // in that case dst may need a reinit

    if (!s->context_initialized) {

        memcpy(s, s1, sizeof(MpegEncContext));

        s->avctx                 = dst;

        s->picture_range_start  += MAX_PICTURE_COUNT;

        s->picture_range_end    += MAX_PICTURE_COUNT;

        s->bitstream_buffer      = NULL;

        s->bitstream_buffer_size = s->allocated_bitstream_buffer_size = 0;

        ff_MPV_common_init(s);

    }

    if (s->height != s1->height || s->width != s1->width || s->context_reinit) {

        int err;

        s->context_reinit = 0;

        s->height = s1->height;

        s->width  = s1->width;

        if ((err = ff_MPV_common_frame_size_change(s)) < 0)

            return err;

    }

    s->avctx->coded_height  = s1->avctx->coded_height;

    s->avctx->coded_width   = s1->avctx->coded_width;

    s->avctx->width         = s1->avctx->width;

    s->avctx->height        = s1->avctx->height;

    s->coded_picture_number = s1->coded_picture_number;

    s->picture_number       = s1->picture_number;

    s->input_picture_number = s1->input_picture_number;

    memcpy(s->picture, s1->picture, s1->picture_count * sizeof(Picture));

    memcpy(&s->last_picture, &s1->last_picture,

           (char *) &s1->last_picture_ptr - (char *) &s1->last_picture);

    // reset s->picture[].f.extended_data to s->picture[].f.data

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

        s->picture[i].f.extended_data = s->picture[i].f.data;

    s->last_picture_ptr    = REBASE_PICTURE(s1->last_picture_ptr,    s, s1);

    s->current_picture_ptr = REBASE_PICTURE(s1->current_picture_ptr, s, s1);

    s->next_picture_ptr    = REBASE_PICTURE(s1->next_picture_ptr,    s, s1);

    // Error/bug resilience

    s->next_p_frame_damaged = s1->next_p_frame_damaged;

    s->workaround_bugs      = s1->workaround_bugs;

    // MPEG4 timing info

    memcpy(&s->time_increment_bits, &s1->time_increment_bits,

           (char *) &s1->shape - (char *) &s1->time_increment_bits);

    // B-frame info

    s->max_b_frames = s1->max_b_frames;

    s->low_delay    = s1->low_delay;

    s->dropable     = s1->dropable;

    // DivX handling (doesn't work)

    s->divx_packed  = s1->divx_packed;

    if (s1->bitstream_buffer) {

        if (s1->bitstream_buffer_size +

            FF_INPUT_BUFFER_PADDING_SIZE > s->allocated_bitstream_buffer_size)

            av_fast_malloc(&s->bitstream_buffer,

                           &s->allocated_bitstream_buffer_size,

                           s1->allocated_bitstream_buffer_size);

            s->bitstream_buffer_size = s1->bitstream_buffer_size;

        memcpy(s->bitstream_buffer, s1->bitstream_buffer,

               s1->bitstream_buffer_size);

        memset(s->bitstream_buffer + s->bitstream_buffer_size, 0,

               FF_INPUT_BUFFER_PADDING_SIZE);

    }

    // MPEG2/interlacing info

    memcpy(&s->progressive_sequence, &s1->progressive_sequence,

           (char *) &s1->rtp_mode - (char *) &s1->progressive_sequence);

    if (!s1->first_field) {

        s->last_pict_type = s1->pict_type;

        if (s1->current_picture_ptr)

            s->last_lambda_for[s1->pict_type] = s1->current_picture_ptr->f.quality;

        if (s1->pict_type != AV_PICTURE_TYPE_B) {

            s->last_non_b_pict_type = s1->pict_type;

        }

    }

    return 0;

}


static void init_proc_970FX (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* Time base */

    gen_tbl(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_clear,

                 0x60000000);

    /* 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);

    /* XXX : not implemented */

    spr_register(env, SPR_970_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 POWERPC970_HID5_INIT);

    /* XXX : not implemented */

    spr_register(env, SPR_L2CR, "L2CR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, NULL,

                 0x00000000);

    /* Memory management */

    /* XXX: not correct */

    gen_low_BATs(env);

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCFG, "MMUCFG",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000); /* TOFIX */

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCSR0, "MMUCSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000); /* TOFIX */

    spr_register(env, SPR_HIOR, "SPR_HIOR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_hior, &spr_write_hior,

                 0x00000000);

    spr_register(env, SPR_CTRL, "SPR_CTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_UCTRL, "SPR_UCTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_VRSAVE, "SPR_VRSAVE",

                 &spr_read_generic, &spr_write_generic,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

#if !defined(CONFIG_USER_ONLY)

    env->slb_nr = 64;

#endif

    init_excp_970(env);

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

    /* Allocate hardware IRQ controller */

    ppc970_irq_init(env);

    /* Can't find information on what this should be on reset.  This

     * value is the one used by 74xx processors. */

    vscr_init(env, 0x00010000);

}


int av_fifo_generic_read(AVFifoBuffer *f, int buf_size, void (*func)(void*, void*, int), void* dest)

{

    int size = av_fifo_size(f);

    if (size < buf_size)

        return -1;

    do {

        int len = FFMIN(f->end - f->rptr, buf_size);

        if(func) func(dest, f->rptr, len);

        else{

            memcpy(dest, f->rptr, len);

            dest = (uint8_t*)dest + len;

        }

        av_fifo_drain(f, len);

        buf_size -= len;

    } while (buf_size > 0);

    return 0;

}


static int cmp_pkt_sub_ts_pos(const void *a, const void *b)

{

    const AVPacket *s1 = a;

    const AVPacket *s2 = b;

    if (s1->pts == s2->pts) {

        if (s1->pos == s2->pos)

            return 0;

        return s1->pos > s2->pos ? 1 : -1;

    }

    return s1->pts > s2->pts ? 1 : -1;

}


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

{

    KVMXICSState *icpkvm = KVM_XICS(dev);

    XICSState *icp = XICS_COMMON(dev);

    int i, rc;

    Error *error = NULL;

    struct kvm_create_device xics_create_device = {

        .type = KVM_DEV_TYPE_XICS,

        .flags = 0,

    };

    if (!kvm_enabled() || !kvm_check_extension(kvm_state, KVM_CAP_IRQ_XICS)) {

        error_setg(errp,

                   "KVM and IRQ_XICS capability must be present for in-kernel XICS");

        goto fail;

    }

    icpkvm->set_xive_token = spapr_rtas_register("ibm,set-xive", rtas_dummy);

    icpkvm->get_xive_token = spapr_rtas_register("ibm,get-xive", rtas_dummy);

    icpkvm->int_off_token = spapr_rtas_register("ibm,int-off", rtas_dummy);

    icpkvm->int_on_token = spapr_rtas_register("ibm,int-on", rtas_dummy);

    rc = kvmppc_define_rtas_kernel_token(icpkvm->set_xive_token,

                                         "ibm,set-xive");

    if (rc < 0) {

        error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,set-xive");

        goto fail;

    }

    rc = kvmppc_define_rtas_kernel_token(icpkvm->get_xive_token,

                                         "ibm,get-xive");

    if (rc < 0) {

        error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,get-xive");

        goto fail;

    }

    rc = kvmppc_define_rtas_kernel_token(icpkvm->int_on_token, "ibm,int-on");

    if (rc < 0) {

        error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,int-on");

        goto fail;

    }

    rc = kvmppc_define_rtas_kernel_token(icpkvm->int_off_token, "ibm,int-off");

    if (rc < 0) {

        error_setg(errp, "kvmppc_define_rtas_kernel_token: ibm,int-off");

        goto fail;

    }

    /* Create the kernel ICP */

    rc = kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &xics_create_device);

    if (rc < 0) {

        error_setg_errno(errp, -rc, "Error on KVM_CREATE_DEVICE for XICS");

        goto fail;

    }

    icpkvm->kernel_xics_fd = xics_create_device.fd;

    object_property_set_bool(OBJECT(icp->ics), true, "realized", &error);

    if (error) {

        error_propagate(errp, error);

        goto fail;

    }

    assert(icp->nr_servers);

    for (i = 0; i < icp->nr_servers; i++) {

        object_property_set_bool(OBJECT(&icp->ss[i]), true, "realized", &error);

        if (error) {

            error_propagate(errp, error);

            goto fail;

        }

    }

    kvm_kernel_irqchip = true;

    kvm_irqfds_allowed = true;

    kvm_msi_via_irqfd_allowed = true;

    kvm_gsi_direct_mapping = true;

    return;

fail:

    kvmppc_define_rtas_kernel_token(0, "ibm,set-xive");

    kvmppc_define_rtas_kernel_token(0, "ibm,get-xive");

    kvmppc_define_rtas_kernel_token(0, "ibm,int-on");

    kvmppc_define_rtas_kernel_token(0, "ibm,int-off");

}


static int decode_lt_rps(HEVCContext *s, LongTermRPS *rps, GetBitContext *gb)

{

    const HEVCSPS *sps = s->ps.sps;

    int max_poc_lsb    = 1 << sps->log2_max_poc_lsb;

    int prev_delta_msb = 0;

    unsigned int nb_sps = 0, nb_sh;

    int i;

    rps->nb_refs = 0;

    if (!sps->long_term_ref_pics_present_flag)

        return 0;

    if (sps->num_long_term_ref_pics_sps > 0)

        nb_sps = get_ue_golomb_long(gb);

    nb_sh = get_ue_golomb_long(gb);

    if (nb_sps > sps->num_long_term_ref_pics_sps)

        return AVERROR_INVALIDDATA;

    if (nb_sh + (uint64_t)nb_sps > FF_ARRAY_ELEMS(rps->poc))

        return AVERROR_INVALIDDATA;

    rps->nb_refs = nb_sh + nb_sps;

    for (i = 0; i < rps->nb_refs; i++) {

        uint8_t delta_poc_msb_present;

        if (i < nb_sps) {

            uint8_t lt_idx_sps = 0;

            if (sps->num_long_term_ref_pics_sps > 1)

                lt_idx_sps = get_bits(gb, av_ceil_log2(sps->num_long_term_ref_pics_sps));

            rps->poc[i]  = sps->lt_ref_pic_poc_lsb_sps[lt_idx_sps];

            rps->used[i] = sps->used_by_curr_pic_lt_sps_flag[lt_idx_sps];

        } else {

            rps->poc[i]  = get_bits(gb, sps->log2_max_poc_lsb);

            rps->used[i] = get_bits1(gb);

        }

        delta_poc_msb_present = get_bits1(gb);

        if (delta_poc_msb_present) {

            int delta = get_ue_golomb_long(gb);

            if (i && i != nb_sps)

                delta += prev_delta_msb;

            rps->poc[i] += s->poc - delta * max_poc_lsb - s->sh.pic_order_cnt_lsb;

            prev_delta_msb = delta;

        }

    }

    return 0;

}


static void xenstore_update_be(char *watch, char *type, int dom,

                               struct XenDevOps *ops)

{

    struct XenDevice *xendev;

    char path[XEN_BUFSIZE], *dom0, *bepath;

    unsigned int len, dev;

    dom0 = xs_get_domain_path(xenstore, 0);

    len = snprintf(path, sizeof(path), "%s/backend/%s/%d", dom0, type, dom);

    free(dom0);

    if (strncmp(path, watch, len) != 0) {

        return;

    }

    if (sscanf(watch+len, "/%u/%255s", &dev, path) != 2) {

        strcpy(path, "");

        if (sscanf(watch+len, "/%u", &dev) != 1) {

            dev = -1;

        }

    }

    if (dev == -1) {

        return;

    }

    xendev = xen_be_get_xendev(type, dom, dev, ops);

    if (xendev != NULL) {

        bepath = xs_read(xenstore, 0, xendev->be, &len);

        if (bepath == NULL) {

            xen_be_del_xendev(dom, dev);

        } else {

            free(bepath);

            xen_be_backend_changed(xendev, path);

            xen_be_check_state(xendev);

        }

    }

}


static int open_url(HLSContext *c, URLContext **uc, const char *url, AVDictionary *opts)

{

    AVDictionary *tmp = NULL;

    int ret;

    const char *proto_name = avio_find_protocol_name(url);

    // only http(s) & file are allowed

    if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL))

        return AVERROR_INVALIDDATA;

    if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')

        ;

    else if (strcmp(proto_name, "file") || !strcmp(url, "file,"))

        return AVERROR_INVALIDDATA;

    av_dict_copy(&tmp, c->avio_opts, 0);

    av_dict_copy(&tmp, opts, 0);

    ret = ffurl_open(uc, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);

    if( ret >= 0) {

        // update cookies on http response with setcookies.

        URLContext *u = *uc;

        update_options(&c->cookies, "cookies", u->priv_data);

        av_dict_set(&opts, "cookies", c->cookies, 0);

    }

    av_dict_free(&tmp);

    return ret;

}


static int rm_assemble_video_frame(AVFormatContext *s, RMContext *rm, AVPacket *pkt, int len)

{

    ByteIOContext *pb = &s->pb;

    int hdr, seq, pic_num, len2, pos;

    int type;

    int ssize;

    hdr = get_byte(pb); len--;

    type = hdr >> 6;

    switch(type){

    case 0: // slice

    case 2: // last slice

        seq = get_byte(pb); len--;

        len2 = get_num(pb, &len);

        pos = get_num(pb, &len);

        pic_num = get_byte(pb); len--;

        rm->remaining_len = len;

        break;

    case 1: //whole frame

        seq = get_byte(pb); len--;

        if(av_new_packet(pkt, len + 9) < 0)

            return AVERROR(EIO);

        pkt->data[0] = 0;

        AV_WL32(pkt->data + 1, 1);

        AV_WL32(pkt->data + 5, 0);

        get_buffer(pb, pkt->data + 9, len);

        rm->remaining_len = 0;

        return 0;

    case 3: //frame as a part of packet

        len2 = get_num(pb, &len);

        pos = get_num(pb, &len);

        pic_num = get_byte(pb); len--;

        rm->remaining_len = len - len2;

        if(av_new_packet(pkt, len2 + 9) < 0)

            return AVERROR(EIO);

        pkt->data[0] = 0;

        AV_WL32(pkt->data + 1, 1);

        AV_WL32(pkt->data + 5, 0);

        get_buffer(pb, pkt->data + 9, len2);

        return 0;

    }

    //now we have to deal with single slice

    if((seq & 0x7F) == 1 || rm->curpic_num != pic_num){

        rm->slices = ((hdr & 0x3F) << 1) + 1;

        ssize = len2 + 8*rm->slices + 1;

        rm->videobuf = av_realloc(rm->videobuf, ssize);

        rm->videobufsize = ssize;

        rm->videobufpos = 8*rm->slices + 1;

        rm->cur_slice = 0;

        rm->curpic_num = pic_num;

        rm->pktpos = url_ftell(pb);

    }

    if(type == 2){

        len = FFMIN(len, pos);

        pos = len2 - pos;

    }

    if(++rm->cur_slice > rm->slices)

        return 1;

    AV_WL32(rm->videobuf - 7 + 8*rm->cur_slice, 1);

    AV_WL32(rm->videobuf - 3 + 8*rm->cur_slice, rm->videobufpos - 8*rm->slices - 1);

    if(rm->videobufpos + len > rm->videobufsize)

        return 1;

    if (get_buffer(pb, rm->videobuf + rm->videobufpos, len) != len)

        return AVERROR(EIO);

    rm->videobufpos += len,

    rm->remaining_len-= len;

    if(type == 2 || (rm->videobufpos) == rm->videobufsize){

         rm->videobuf[0] = rm->cur_slice-1;

         if(av_new_packet(pkt, rm->videobufpos - 8*(rm->slices - rm->cur_slice)) < 0)

             return AVERROR(ENOMEM);

         memcpy(pkt->data, rm->videobuf, 1 + 8*rm->cur_slice);

         memcpy(pkt->data + 1 + 8*rm->cur_slice, rm->videobuf + 1 + 8*rm->slices, rm->videobufpos - 1 - 8*rm->slices);

         pkt->pts = AV_NOPTS_VALUE;

         pkt->pos = rm->pktpos;

         return 0;

    }

    return 1;

}


static int sunrast_decode_frame(AVCodecContext *avctx, void *data,

                                int *data_size, AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    const uint8_t *buf_end = avpkt->data + avpkt->size;

    SUNRASTContext * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p = &s->picture;

    unsigned int w, h, depth, type, maptype, maplength, stride, x, y, len, alen;

    uint8_t *ptr;

    const uint8_t *bufstart = buf;

    if (avpkt->size < 32)

        return AVERROR_INVALIDDATA;

    if (AV_RB32(buf) != 0x59a66a95) {

        av_log(avctx, AV_LOG_ERROR, "this is not sunras encoded data\n");

        return -1;

    }

    w         = AV_RB32(buf+4);

    h         = AV_RB32(buf+8);

    depth     = AV_RB32(buf+12);

    type      = AV_RB32(buf+20);

    maptype   = AV_RB32(buf+24);

    maplength = AV_RB32(buf+28);

    buf      += 32;

    if (type == RT_FORMAT_TIFF || type == RT_FORMAT_IFF) {

        av_log(avctx, AV_LOG_ERROR, "unsupported (compression) type\n");

        return -1;

    }

    if (type < RT_OLD || type > RT_FORMAT_IFF) {

        av_log(avctx, AV_LOG_ERROR, "invalid (compression) type\n");

        return -1;

    }

    if (av_image_check_size(w, h, 0, avctx)) {

        av_log(avctx, AV_LOG_ERROR, "invalid image size\n");

        return -1;

    }

    if (maptype & ~1) {

        av_log(avctx, AV_LOG_ERROR, "invalid colormap type\n");

        return -1;

    }

    switch (depth) {

        case 1:

            avctx->pix_fmt = PIX_FMT_MONOWHITE;

            break;

        case 8:

            avctx->pix_fmt = PIX_FMT_PAL8;

            break;

        case 24:

            avctx->pix_fmt = (type == RT_FORMAT_RGB) ? PIX_FMT_RGB24 : PIX_FMT_BGR24;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "invalid depth\n");

            return -1;

    }

    if (p->data[0])

        avctx->release_buffer(avctx, p);

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

    if (avctx->get_buffer(avctx, p) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return -1;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    if (buf_end - buf < maplength)

        return AVERROR_INVALIDDATA;

    if (depth != 8 && maplength) {

        av_log(avctx, AV_LOG_WARNING, "useless colormap found or file is corrupted, trying to recover\n");

    } else if (depth == 8) {

        unsigned int len = maplength / 3;

        if (!maplength) {

            av_log(avctx, AV_LOG_ERROR, "colormap expected\n");

            return -1;

        }

        if (maplength % 3 || maplength > 768) {

            av_log(avctx, AV_LOG_WARNING, "invalid colormap length\n");

            return -1;

        }

        ptr = p->data[1];

        for (x=0; x<len; x++, ptr+=4)

            *(uint32_t *)ptr = (buf[x]<<16) + (buf[len+x]<<8) + buf[len+len+x];

    }

    buf += maplength;

    ptr    = p->data[0];

    stride = p->linesize[0];

    /* scanlines are aligned on 16 bit boundaries */

    len  = (depth * w + 7) >> 3;

    alen = len + (len&1);

    if (type == RT_BYTE_ENCODED) {

        int value, run;

        uint8_t *end = ptr + h*stride;

        x = 0;

        while (ptr != end && buf < buf_end) {

            run = 1;

            if (buf_end - buf < 1)

                return AVERROR_INVALIDDATA;

            if ((value = *buf++) == 0x80) {

                run = *buf++ + 1;

                if (run != 1)

                    value = *buf++;

            }

            while (run--) {

                if (x < len)

                    ptr[x] = value;

                if (++x >= alen) {

                    x = 0;

                    ptr += stride;

                    if (ptr == end)

                        break;

                }

            }

        }

    } else {

        for (y=0; y<h; y++) {

            if (buf_end - buf < len)

                break;

            memcpy(ptr, buf, len);

            ptr += stride;

            buf += alen;

        }

    }

    *picture = s->picture;

    *data_size = sizeof(AVFrame);

    return buf - bufstart;

}


static void external_snapshot_prepare(BlkTransactionStates *common,

                                      Error **errp)

{

    BlockDriver *proto_drv;

    BlockDriver *drv;

    int flags, ret;

    Error *local_err = NULL;

    const char *device;

    const char *new_image_file;

    const char *format = "qcow2";

    enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    ExternalSnapshotStates *states =

                             DO_UPCAST(ExternalSnapshotStates, common, common);

    TransactionAction *action = common->action;

    /* get parameters */

    g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);

    device = action->blockdev_snapshot_sync->device;

    new_image_file = action->blockdev_snapshot_sync->snapshot_file;

    if (action->blockdev_snapshot_sync->has_format) {

        format = action->blockdev_snapshot_sync->format;

    }

    if (action->blockdev_snapshot_sync->has_mode) {

        mode = action->blockdev_snapshot_sync->mode;

    }

    /* start processing */

    drv = bdrv_find_format(format);

    if (!drv) {

        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

        return;

    }

    states->old_bs = bdrv_find(device);

    if (!states->old_bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (!bdrv_is_inserted(states->old_bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (bdrv_in_use(states->old_bs)) {

        error_set(errp, QERR_DEVICE_IN_USE, device);

        return;

    }

    if (!bdrv_is_read_only(states->old_bs)) {

        if (bdrv_flush(states->old_bs)) {

            error_set(errp, QERR_IO_ERROR);

            return;

        }

    }

    flags = states->old_bs->open_flags;

    proto_drv = bdrv_find_protocol(new_image_file);

    if (!proto_drv) {

        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

        return;

    }

    /* create new image w/backing file */

    if (mode != NEW_IMAGE_MODE_EXISTING) {

        bdrv_img_create(new_image_file, format,

                        states->old_bs->filename,

                        states->old_bs->drv->format_name,

                        NULL, -1, flags, &local_err, false);

        if (error_is_set(&local_err)) {

            error_propagate(errp, local_err);

            return;

        }

    }

    /* We will manually add the backing_hd field to the bs later */

    states->new_bs = bdrv_new("");

    /* TODO Inherit bs->options or only take explicit options with an

     * extended QMP command? */

    ret = bdrv_open(states->new_bs, new_image_file, NULL,

                    flags | BDRV_O_NO_BACKING, drv);

    if (ret != 0) {

        error_setg_file_open(errp, -ret, new_image_file);

    }

}


static void virtqueue_map_iovec(struct iovec *sg, hwaddr *addr,

                                unsigned int *num_sg, unsigned int max_size,

                                int is_write)

{

    unsigned int i;

    hwaddr len;

    /* Note: this function MUST validate input, some callers

     * are passing in num_sg values received over the network.

     */

    /* TODO: teach all callers that this can fail, and return failure instead

     * of asserting here.

     * When we do, we might be able to re-enable NDEBUG below.

     */

#ifdef NDEBUG

#error building with NDEBUG is not supported

#endif

    assert(*num_sg <= max_size);

    for (i = 0; i < *num_sg; i++) {

        len = sg[i].iov_len;

        sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);

        if (!sg[i].iov_base) {

            error_report("virtio: error trying to map MMIO memory");

            exit(1);

        }

        if (len != sg[i].iov_len) {

            error_report("virtio: unexpected memory split");

            exit(1);

        }

    }

}


static void bdrv_inherited_options(int *child_flags, QDict *child_options,

                                   int parent_flags, QDict *parent_options)

{

    int flags = parent_flags;

    /* Enable protocol handling, disable format probing for bs->file */

    flags |= BDRV_O_PROTOCOL;

    /* If the cache mode isn't explicitly set, inherit direct and no-flush from

     * the parent. */

    qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);

    qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);

    /* Inherit the read-only option from the parent if it's not set */

    qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);

    /* Our block drivers take care to send flushes and respect unmap policy,

     * so we can default to enable both on lower layers regardless of the

     * corresponding parent options. */

    flags |= BDRV_O_UNMAP;

    /* Clear flags that only apply to the top layer */

    flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |

               BDRV_O_NO_IO);

    *child_flags = flags;

}


static inline void tcg_out_st(TCGContext *s, TCGType type, TCGReg arg,

                              TCGReg arg1, intptr_t arg2)

{

    int opi, opx;

    assert(TCG_TARGET_REG_BITS == 64 || type == TCG_TYPE_I32);

    if (type == TCG_TYPE_I32) {

        opi = STW, opx = STWX;

    } else {

        opi = STD, opx = STDX;

    }

    tcg_out_mem_long(s, opi, opx, arg, arg1, arg2);

}


static void IRQ_local_pipe(OpenPICState *opp, int n_CPU, int n_IRQ)

{

    IRQDest *dst;

    IRQSource *src;

    int priority;

    dst = &opp->dst[n_CPU];

    src = &opp->src[n_IRQ];

    if (src->output != OPENPIC_OUTPUT_INT) {

        /* On Freescale MPIC, critical interrupts ignore priority,

         * IACK, EOI, etc.  Before MPIC v4.1 they also ignore

         * masking.

         */

        src->ivpr |= IVPR_ACTIVITY_MASK;

        DPRINTF("%s: Raise OpenPIC output %d cpu %d irq %d\n",

                __func__, src->output, n_CPU, n_IRQ);

        qemu_irq_raise(opp->dst[n_CPU].irqs[src->output]);

        return;

    }

    priority = IVPR_PRIORITY(src->ivpr);

    if (priority <= dst->ctpr) {

        /* Too low priority */

        DPRINTF("%s: IRQ %d has too low priority on CPU %d\n",

                __func__, n_IRQ, n_CPU);

        return;

    }

    if (IRQ_testbit(&dst->raised, n_IRQ)) {

        /* Interrupt miss */

        DPRINTF("%s: IRQ %d was missed on CPU %d\n",

                __func__, n_IRQ, n_CPU);

        return;

    }

    src->ivpr |= IVPR_ACTIVITY_MASK;

    IRQ_setbit(&dst->raised, n_IRQ);

    if (priority < dst->raised.priority) {

        /* An higher priority IRQ is already raised */

        DPRINTF("%s: IRQ %d is hidden by raised IRQ %d on CPU %d\n",

                __func__, n_IRQ, dst->raised.next, n_CPU);

        return;

    }

    IRQ_check(opp, &dst->raised);

    if (IRQ_get_next(opp, &dst->servicing) != -1 &&

        priority <= dst->servicing.priority) {

        DPRINTF("%s: IRQ %d is hidden by servicing IRQ %d on CPU %d\n",

                __func__, n_IRQ, dst->servicing.next, n_CPU);

        /* Already servicing a higher priority IRQ */

        return;

    }

    DPRINTF("Raise OpenPIC INT output cpu %d irq %d\n", n_CPU, n_IRQ);

    qemu_irq_raise(opp->dst[n_CPU].irqs[OPENPIC_OUTPUT_INT]);

}


static void test_acpi_dsdt_table(test_data *data)

{

    AcpiSdtTable dsdt_table;

    uint32_t addr = le32_to_cpu(data->fadt_table.dsdt);

    test_dst_table(&dsdt_table, addr);

    ACPI_ASSERT_CMP(dsdt_table.header.signature, "DSDT");

    /* Since DSDT isn't in RSDT, add DSDT to ASL test tables list manually */

    g_array_append_val(data->tables, dsdt_table);

}


static void vfio_err_notifier_handler(void *opaque)

{

    VFIOPCIDevice *vdev = opaque;

    if (!event_notifier_test_and_clear(&vdev->err_notifier)) {

        return;

    }

    /*

     * TBD. Retrieve the error details and decide what action

     * needs to be taken. One of the actions could be to pass

     * the error to the guest and have the guest driver recover

     * from the error. This requires that PCIe capabilities be

     * exposed to the guest. For now, we just terminate the

     * guest to contain the error.

     */

    error_report("%s(%04x:%02x:%02x.%x) Unrecoverable error detected.  "

                 "Please collect any data possible and then kill the guest",

                 __func__, vdev->host.domain, vdev->host.bus,

                 vdev->host.slot, vdev->host.function);

    vm_stop(RUN_STATE_INTERNAL_ERROR);

}


static int do_attach(USBDevice *dev)

{

    USBBus *bus = usb_bus_from_device(dev);

    USBPort *port;

    if (dev->attached) {

        error_report("Error: tried to attach usb device %s twice\n",

                dev->product_desc);

        return -1;

    }

    if (bus->nfree == 0) {

        error_report("Error: tried to attach usb device %s to a bus with no free ports\n",

                dev->product_desc);

        return -1;

    }

    if (dev->port_path) {

        QTAILQ_FOREACH(port, &bus->free, next) {

            if (strcmp(port->path, dev->port_path) == 0) {

                break;

            }

        }

        if (port == NULL) {

            error_report("Error: usb port %s (bus %s) not found\n",

                    dev->port_path, bus->qbus.name);

            return -1;

        }

    } else {

        port = QTAILQ_FIRST(&bus->free);

    }

    if (!(port->speedmask & dev->speedmask)) {

        error_report("Warning: speed mismatch trying to attach usb device %s to bus %s\n",

                dev->product_desc, bus->qbus.name);

        return -1;

    }

    dev->attached++;

    QTAILQ_REMOVE(&bus->free, port, next);

    bus->nfree--;

    usb_attach(port, dev);

    QTAILQ_INSERT_TAIL(&bus->used, port, next);

    bus->nused++;

    return 0;

}


static void apply_dependent_coupling(AACContext * ac, SingleChannelElement * target, ChannelElement * cce, int index) {

    IndividualChannelStream * ics = &cce->ch[0].ics;

    const uint16_t * offsets = ics->swb_offset;

    float * dest = target->coeffs;

    const float * src = cce->ch[0].coeffs;

    int g, i, group, k, idx = 0;

    if(ac->m4ac.object_type == AOT_AAC_LTP) {

        av_log(ac->avccontext, AV_LOG_ERROR,

               "Dependent coupling is not supported together with LTP\n");

        return;

    }

    for (g = 0; g < ics->num_window_groups; g++) {

        for (i = 0; i < ics->max_sfb; i++, idx++) {

            if (cce->ch[0].band_type[idx] != ZERO_BT) {

                for (group = 0; group < ics->group_len[g]; group++) {

                    for (k = offsets[i]; k < offsets[i+1]; k++) {

                        // XXX dsputil-ize

                        dest[group*128+k] += cce->coup.gain[index][idx] * src[group*128+k];

                    }

                }

            }

        }

        dest += ics->group_len[g]*128;

        src  += ics->group_len[g]*128;

    }

}


static inline void omap_timer_update(struct omap_mpu_timer_s *timer)

{

    int64_t expires;

    if (timer->enable && timer->st && timer->rate) {

        timer->val = timer->reset_val;	/* Should skip this on clk enable */

        expires = timer->time + muldiv64(timer->val << (timer->ptv + 1),

                        ticks_per_sec, timer->rate);

        qemu_mod_timer(timer->timer, expires);

    } else

        qemu_del_timer(timer->timer);

}


void cpu_save(QEMUFile *f, void *opaque)

{

    CPUState *env = opaque;

    uint16_t fptag, fpus, fpuc, fpregs_format;

    uint32_t hflags;

    int32_t a20_mask;

    int i;

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

        qemu_put_betls(f, &env->regs[i]);

    qemu_put_betls(f, &env->eip);

    qemu_put_betls(f, &env->eflags);

    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */

    qemu_put_be32s(f, &hflags);

    /* FPU */

    fpuc = env->fpuc;

    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;

    fptag = 0;

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

        fptag |= ((!env->fptags[i]) << i);

    }

    qemu_put_be16s(f, &fpuc);

    qemu_put_be16s(f, &fpus);

    qemu_put_be16s(f, &fptag);

#ifdef USE_X86LDOUBLE

    fpregs_format = 0;

#else

    fpregs_format = 1;

#endif

    qemu_put_be16s(f, &fpregs_format);

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

#ifdef USE_X86LDOUBLE

        {

            uint64_t mant;

            uint16_t exp;

            /* we save the real CPU data (in case of MMX usage only 'mant'

               contains the MMX register */

            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);

            qemu_put_be64(f, mant);

            qemu_put_be16(f, exp);

        }

#else

        /* if we use doubles for float emulation, we save the doubles to

           avoid losing information in case of MMX usage. It can give

           problems if the image is restored on a CPU where long

           doubles are used instead. */

        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));

#endif

    }

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

        cpu_put_seg(f, &env->segs[i]);

    cpu_put_seg(f, &env->ldt);

    cpu_put_seg(f, &env->tr);

    cpu_put_seg(f, &env->gdt);

    cpu_put_seg(f, &env->idt);

    qemu_put_be32s(f, &env->sysenter_cs);

    qemu_put_be32s(f, &env->sysenter_esp);

    qemu_put_be32s(f, &env->sysenter_eip);

    qemu_put_betls(f, &env->cr[0]);

    qemu_put_betls(f, &env->cr[2]);

    qemu_put_betls(f, &env->cr[3]);

    qemu_put_betls(f, &env->cr[4]);

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

        qemu_put_betls(f, &env->dr[i]);

    /* MMU */

    a20_mask = (int32_t) env->a20_mask;

    qemu_put_sbe32s(f, &a20_mask);

    /* XMM */

    qemu_put_be32s(f, &env->mxcsr);

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

        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));

        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));

    }

#ifdef TARGET_X86_64

    qemu_put_be64s(f, &env->efer);

    qemu_put_be64s(f, &env->star);

    qemu_put_be64s(f, &env->lstar);

    qemu_put_be64s(f, &env->cstar);

    qemu_put_be64s(f, &env->fmask);

    qemu_put_be64s(f, &env->kernelgsbase);

#endif

    qemu_put_be32s(f, &env->smbase);

    qemu_put_be64s(f, &env->pat);

    qemu_put_be32s(f, &env->hflags2);

    qemu_put_be64s(f, &env->vm_hsave);

    qemu_put_be64s(f, &env->vm_vmcb);

    qemu_put_be64s(f, &env->tsc_offset);

    qemu_put_be64s(f, &env->intercept);

    qemu_put_be16s(f, &env->intercept_cr_read);

    qemu_put_be16s(f, &env->intercept_cr_write);

    qemu_put_be16s(f, &env->intercept_dr_read);

    qemu_put_be16s(f, &env->intercept_dr_write);

    qemu_put_be32s(f, &env->intercept_exceptions);

    qemu_put_8s(f, &env->v_tpr);

}


static void omap_mcbsp_source_tick(void *opaque)

{

    struct omap_mcbsp_s *s = (struct omap_mcbsp_s *) opaque;

    static const int bps[8] = { 0, 1, 1, 2, 2, 2, -255, -255 };

    if (!s->rx_rate)

        return;

    if (s->rx_req)

        printf("%s: Rx FIFO overrun\n", __FUNCTION__);

    s->rx_req = s->rx_rate << bps[(s->rcr[0] >> 5) & 7];

    omap_mcbsp_rx_newdata(s);

    timer_mod(s->source_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +

                   NANOSECONDS_PER_SECOND);

}


static int xen_9pfs_free(struct XenDevice *xendev)

{

    return -1;

}


static void phys_sections_clear(PhysPageMap *map)

{

    while (map->sections_nb > 0) {

        MemoryRegionSection *section = &map->sections[--map->sections_nb];

        phys_section_destroy(section->mr);

    }

    g_free(map->sections);

    g_free(map->nodes);

}


static void test_qemu_strtoull_correct(void)

{

    const char *str = "12345 foo";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 12345);

    g_assert(endptr == str + 5);

}


static void test_visitor_in_enum(TestInputVisitorData *data,

                                 const void *unused)

{

    Error *err = NULL;

    Visitor *v;

    EnumOne i;

    for (i = 0; EnumOne_lookup[i]; i++) {

        EnumOne res = -1;

        v = visitor_input_test_init(data, "%s", EnumOne_lookup[i]);

        visit_type_EnumOne(v, &res, NULL, &err);

        g_assert(!err);

        g_assert_cmpint(i, ==, res);

    }

}


static void v9fs_lock(void *opaque)

{

    int8_t status;

    V9fsFlock *flock;

    size_t offset = 7;

    struct stat stbuf;

    V9fsFidState *fidp;

    int32_t fid, err = 0;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    flock = g_malloc(sizeof(*flock));

    pdu_unmarshal(pdu, offset, "dbdqqds", &fid, &flock->type,

                  &flock->flags, &flock->start, &flock->length,

                  &flock->proc_id, &flock->client_id);

    trace_v9fs_lock(pdu->tag, pdu->id, fid,

                    flock->type, flock->start, flock->length);

    status = P9_LOCK_ERROR;

    /* We support only block flag now (that too ignored currently) */

    if (flock->flags & ~P9_LOCK_FLAGS_BLOCK) {

        err = -EINVAL;

        goto out_nofid;

    }

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    err = v9fs_co_fstat(pdu, fidp, &stbuf);

    if (err < 0) {

        goto out;

    }

    status = P9_LOCK_SUCCESS;

out:

    put_fid(pdu, fidp);

out_nofid:

    err = offset;

    err += pdu_marshal(pdu, offset, "b", status);

    trace_v9fs_lock_return(pdu->tag, pdu->id, status);

    complete_pdu(s, pdu, err);

    v9fs_string_free(&flock->client_id);

    g_free(flock);

}


int ff_intrax8_decode_picture(IntraX8Context *const w, int dquant,

                              int quant_offset)

{

    MpegEncContext *const s = w->s;

    int mb_xy;

    assert(s);

    w->use_quant_matrix = get_bits1(&s->gb);

    w->dquant = dquant;

    w->quant  = dquant >> 1;

    w->qsum   = quant_offset;

    w->divide_quant_dc_luma = ((1 << 16) + (w->quant >> 1)) / w->quant;

    if (w->quant < 5) {

        w->quant_dc_chroma        = w->quant;

        w->divide_quant_dc_chroma = w->divide_quant_dc_luma;

    } else {

        w->quant_dc_chroma        = w->quant + ((w->quant + 3) >> 3);

        w->divide_quant_dc_chroma = ((1 << 16) + (w->quant_dc_chroma >> 1)) / w->quant_dc_chroma;

    }

    x8_reset_vlc_tables(w);

    for (s->mb_y = 0; s->mb_y < s->mb_height * 2; s->mb_y++) {

        x8_init_block_index(w, s->current_picture.f, s->mb_y);

        mb_xy = (s->mb_y >> 1) * s->mb_stride;

        for (s->mb_x = 0; s->mb_x < s->mb_width * 2; s->mb_x++) {

            x8_get_prediction(w);

            if (x8_setup_spatial_predictor(w, 0))

                goto error;

            if (x8_decode_intra_mb(w, 0))

                goto error;

            if (s->mb_x & s->mb_y & 1) {

                x8_get_prediction_chroma(w);

                /* when setting up chroma, no vlc is read,

                 * so no error condition can be reached */

                x8_setup_spatial_predictor(w, 1);

                if (x8_decode_intra_mb(w, 1))

                    goto error;

                x8_setup_spatial_predictor(w, 2);

                if (x8_decode_intra_mb(w, 2))

                    goto error;

                w->dest[1] += 8;

                w->dest[2] += 8;

                /* emulate MB info in the relevant tables */

                s->mbskip_table[mb_xy]                 = 0;

                s->mbintra_table[mb_xy]                = 1;

                s->current_picture.qscale_table[mb_xy] = w->quant;

                mb_xy++;

            }

            w->dest[0] += 8;

        }

        if (s->mb_y & 1)

            ff_mpeg_draw_horiz_band(s, (s->mb_y - 1) * 8, 16);

    }

error:

    return 0;

}


void commit_start(BlockDriverState *bs, BlockDriverState *base,

                  BlockDriverState *top, int64_t speed,

                  BlockdevOnError on_error, BlockDriverCompletionFunc *cb,

                  void *opaque, Error **errp)

{

    CommitBlockJob *s;

    BlockReopenQueue *reopen_queue = NULL;

    int orig_overlay_flags;

    int orig_base_flags;

    BlockDriverState *overlay_bs;

    Error *local_err = NULL;

    if ((on_error == BLOCKDEV_ON_ERROR_STOP ||

         on_error == BLOCKDEV_ON_ERROR_ENOSPC) &&

        !bdrv_iostatus_is_enabled(bs)) {

        error_set(errp, QERR_INVALID_PARAMETER_COMBINATION);

        return;

    }

    /* Once we support top == active layer, remove this check */

    if (top == bs) {

        error_setg(errp,

                   "Top image as the active layer is currently unsupported");

        return;

    }

    if (top == base) {

        error_setg(errp, "Invalid files for merge: top and base are the same");

        return;

    }

    overlay_bs = bdrv_find_overlay(bs, top);

    if (overlay_bs == NULL) {

        error_setg(errp, "Could not find overlay image for %s:", top->filename);

        return;

    }

    orig_base_flags    = bdrv_get_flags(base);

    orig_overlay_flags = bdrv_get_flags(overlay_bs);

    /* convert base & overlay_bs to r/w, if necessary */

    if (!(orig_base_flags & BDRV_O_RDWR)) {

        reopen_queue = bdrv_reopen_queue(reopen_queue, base,

                                         orig_base_flags | BDRV_O_RDWR);

    }

    if (!(orig_overlay_flags & BDRV_O_RDWR)) {

        reopen_queue = bdrv_reopen_queue(reopen_queue, overlay_bs,

                                         orig_overlay_flags | BDRV_O_RDWR);

    }

    if (reopen_queue) {

        bdrv_reopen_multiple(reopen_queue, &local_err);

        if (local_err != NULL) {

            error_propagate(errp, local_err);

            return;

        }

    }

    s = block_job_create(&commit_job_driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->base   = base;

    s->top    = top;

    s->active = bs;

    s->base_flags          = orig_base_flags;

    s->orig_overlay_flags  = orig_overlay_flags;

    s->on_error = on_error;

    s->common.co = qemu_coroutine_create(commit_run);

    trace_commit_start(bs, base, top, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


static void blizzard_screen_dump(void *opaque, const char *filename,

                                 bool cswitch, Error **errp)

{

    BlizzardState *s = (BlizzardState *) opaque;

    DisplaySurface *surface = qemu_console_surface(s->con);

    blizzard_update_display(opaque);

    if (s && surface_data(surface)) {

        ppm_save(filename, surface, errp);

    }

}


static void lan9118_writew(void *opaque, target_phys_addr_t offset,

                           uint32_t val)

{

    lan9118_state *s = (lan9118_state *)opaque;

    offset &= 0xff;

    if (s->write_word_prev_offset != (offset & ~0x3)) {

        /* New offset, reset word counter */

        s->write_word_n = 0;

        s->write_word_prev_offset = offset & ~0x3;

    }

    if (offset & 0x2) {

        s->write_word_h = val;

    } else {

        s->write_word_l = val;

    }

    //DPRINTF("Writew reg 0x%02x = 0x%08x\n", (int)offset, val);

    s->write_word_n++;

    if (s->write_word_n == 2) {

        s->write_word_n = 0;

        lan9118_writel(s, offset & ~3, s->write_word_l +

                (s->write_word_h << 16), 4);

    }

}


int float32_eq( float32 a, float32 b STATUS_PARAM )

{

    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )

         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )

       ) {

        if ( float32_is_signaling_nan( a ) || float32_is_signaling_nan( b ) ) {

            float_raise( float_flag_invalid STATUS_VAR);

        }

        return 0;

    }

    return ( a == b ) || ( (bits32) ( ( a | b )<<1 ) == 0 );

}


int chsc_sei_nt2_get_event(void *res)

{

    ChscSeiNt2Res *nt2_res = (ChscSeiNt2Res *)res;

    PciCcdfAvail *accdf;

    PciCcdfErr *eccdf;

    int rc = 1;

    SeiContainer *sei_cont;

    S390pciState *s = S390_PCI_HOST_BRIDGE(

        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));

    if (!s) {

        return rc;

    }

    sei_cont = QTAILQ_FIRST(&s->pending_sei);

    if (sei_cont) {

        QTAILQ_REMOVE(&s->pending_sei, sei_cont, link);

        nt2_res->nt = 2;

        nt2_res->cc = sei_cont->cc;

        nt2_res->length = cpu_to_be16(sizeof(ChscSeiNt2Res));

        switch (sei_cont->cc) {

        case 1: /* error event */

            eccdf = (PciCcdfErr *)nt2_res->ccdf;

            eccdf->fid = cpu_to_be32(sei_cont->fid);

            eccdf->fh = cpu_to_be32(sei_cont->fh);

            eccdf->e = cpu_to_be32(sei_cont->e);

            eccdf->faddr = cpu_to_be64(sei_cont->faddr);

            eccdf->pec = cpu_to_be16(sei_cont->pec);

            break;

        case 2: /* availability event */

            accdf = (PciCcdfAvail *)nt2_res->ccdf;

            accdf->fid = cpu_to_be32(sei_cont->fid);

            accdf->fh = cpu_to_be32(sei_cont->fh);

            accdf->pec = cpu_to_be16(sei_cont->pec);

            break;

        default:

            abort();

        }

        g_free(sei_cont);

        rc = 0;

    }

    return rc;

}


static void icount_adjust_rt(void *opaque)

{

    timer_mod(icount_rt_timer,

              qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);

    icount_adjust();

}


static inline int tcg_target_const_match(tcg_target_long val,

                                         const TCGArgConstraint *arg_ct)

{

    int ct;

    ct = arg_ct->ct;

    if (ct & TCG_CT_CONST)

        return 1;

    else if ((ct & TCG_CT_CONST_S11) && ABS(val) == (ABS(val) & 0x3ff))

        return 1;

    else if ((ct & TCG_CT_CONST_S13) && ABS(val) == (ABS(val) & 0xfff))

        return 1;

    else

        return 0;

}


static void iscsi_close(BlockDriverState *bs)

{

    IscsiLun *iscsilun = bs->opaque;

    struct iscsi_context *iscsi = iscsilun->iscsi;

    iscsi_detach_aio_context(bs);

    if (iscsi_is_logged_in(iscsi)) {

        iscsi_logout_sync(iscsi);

    }

    iscsi_destroy_context(iscsi);

    g_free(iscsilun->zeroblock);

    g_free(iscsilun->allocationmap);

    memset(iscsilun, 0, sizeof(IscsiLun));

}


void i2c_register_slave(I2CSlaveInfo *info)

{

    assert(info->qdev.size >= sizeof(i2c_slave));

    info->qdev.init = i2c_slave_qdev_init;

    info->qdev.bus_type = BUS_TYPE_I2C;

    qdev_register(&info->qdev);

}


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

{

    const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;

    BlockBackend *blk1, *blk2;

    BlockDriverState *bs1, *bs2;

    int64_t total_sectors1, total_sectors2;

    uint8_t *buf1 = NULL, *buf2 = NULL;

    int pnum1, pnum2;

    int allocated1, allocated2;

    int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */

    bool progress = false, quiet = false, strict = false;

    int flags;

    int64_t total_sectors;

    int64_t sector_num = 0;

    int64_t nb_sectors;

    int c, pnum;

    uint64_t progress_base;

    cache = BDRV_DEFAULT_CACHE;

    for (;;) {

        c = getopt(argc, argv, "hf:F:T:pqs");

        if (c == -1) {

            break;

        }

        switch (c) {

        case '?':

        case 'h':

            help();

            break;

        case 'f':

            fmt1 = optarg;

            break;

        case 'F':

            fmt2 = optarg;

            break;

        case 'T':

            cache = optarg;

            break;

        case 'p':

            progress = true;

            break;

        case 'q':

            quiet = true;

            break;

        case 's':

            strict = true;

            break;

        }

    }

    /* Progress is not shown in Quiet mode */

    if (quiet) {

        progress = false;

    }

    if (optind != argc - 2) {

        error_exit("Expecting two image file names");

    }

    filename1 = argv[optind++];

    filename2 = argv[optind++];

    /* Initialize before goto out */

    qemu_progress_init(progress, 2.0);

    flags = BDRV_O_FLAGS;

    ret = bdrv_parse_cache_flags(cache, &flags);

    if (ret < 0) {

        error_report("Invalid source cache option: %s", cache);

        ret = 2;

        goto out3;

    }

    blk1 = img_open("image_1", filename1, fmt1, flags, true, quiet);

    if (!blk1) {

        ret = 2;

        goto out3;

    }

    bs1 = blk_bs(blk1);

    blk2 = img_open("image_2", filename2, fmt2, flags, true, quiet);

    if (!blk2) {

        ret = 2;

        goto out2;

    }

    bs2 = blk_bs(blk2);

    buf1 = blk_blockalign(blk1, IO_BUF_SIZE);

    buf2 = blk_blockalign(blk2, IO_BUF_SIZE);

    total_sectors1 = blk_nb_sectors(blk1);

    if (total_sectors1 < 0) {

        error_report("Can't get size of %s: %s",

                     filename1, strerror(-total_sectors1));

        ret = 4;

        goto out;

    }

    total_sectors2 = blk_nb_sectors(blk2);

    if (total_sectors2 < 0) {

        error_report("Can't get size of %s: %s",

                     filename2, strerror(-total_sectors2));

        ret = 4;

        goto out;

    }

    total_sectors = MIN(total_sectors1, total_sectors2);

    progress_base = MAX(total_sectors1, total_sectors2);

    qemu_progress_print(0, 100);

    if (strict && total_sectors1 != total_sectors2) {

        ret = 1;

        qprintf(quiet, "Strict mode: Image size mismatch!\n");

        goto out;

    }

    for (;;) {

        int64_t status1, status2;

        nb_sectors = sectors_to_process(total_sectors, sector_num);

        if (nb_sectors <= 0) {

            break;

        }

        status1 = bdrv_get_block_status_above(bs1, NULL, sector_num,

                                              total_sectors1 - sector_num,

                                              &pnum1);

        if (status1 < 0) {

            ret = 3;

            error_report("Sector allocation test failed for %s", filename1);

            goto out;

        }

        allocated1 = status1 & BDRV_BLOCK_ALLOCATED;

        status2 = bdrv_get_block_status_above(bs2, NULL, sector_num,

                                              total_sectors2 - sector_num,

                                              &pnum2);

        if (status2 < 0) {

            ret = 3;

            error_report("Sector allocation test failed for %s", filename2);

            goto out;

        }

        allocated2 = status2 & BDRV_BLOCK_ALLOCATED;

        if (pnum1) {

            nb_sectors = MIN(nb_sectors, pnum1);

        }

        if (pnum2) {

            nb_sectors = MIN(nb_sectors, pnum2);

        }

        if (strict) {

            if ((status1 & ~BDRV_BLOCK_OFFSET_MASK) !=

                (status2 & ~BDRV_BLOCK_OFFSET_MASK)) {

                ret = 1;

                qprintf(quiet, "Strict mode: Offset %" PRId64

                        " block status mismatch!\n",

                        sectors_to_bytes(sector_num));

                goto out;

            }

        }

        if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {

            nb_sectors = MIN(pnum1, pnum2);

        } else if (allocated1 == allocated2) {

            if (allocated1) {

                ret = blk_read(blk1, sector_num, buf1, nb_sectors);

                if (ret < 0) {

                    error_report("Error while reading offset %" PRId64 " of %s:"

                                 " %s", sectors_to_bytes(sector_num), filename1,

                                 strerror(-ret));

                    ret = 4;

                    goto out;

                }

                ret = blk_read(blk2, sector_num, buf2, nb_sectors);

                if (ret < 0) {

                    error_report("Error while reading offset %" PRId64

                                 " of %s: %s", sectors_to_bytes(sector_num),

                                 filename2, strerror(-ret));

                    ret = 4;

                    goto out;

                }

                ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);

                if (ret || pnum != nb_sectors) {

                    qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",

                            sectors_to_bytes(

                                ret ? sector_num : sector_num + pnum));

                    ret = 1;

                    goto out;

                }

            }

        } else {

            if (allocated1) {

                ret = check_empty_sectors(blk1, sector_num, nb_sectors,

                                          filename1, buf1, quiet);

            } else {

                ret = check_empty_sectors(blk2, sector_num, nb_sectors,

                                          filename2, buf1, quiet);

            }

            if (ret) {

                if (ret < 0) {

                    error_report("Error while reading offset %" PRId64 ": %s",

                                 sectors_to_bytes(sector_num), strerror(-ret));

                    ret = 4;

                }

                goto out;

            }

        }

        sector_num += nb_sectors;

        qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);

    }

    if (total_sectors1 != total_sectors2) {

        BlockBackend *blk_over;

        int64_t total_sectors_over;

        const char *filename_over;

        qprintf(quiet, "Warning: Image size mismatch!\n");

        if (total_sectors1 > total_sectors2) {

            total_sectors_over = total_sectors1;

            blk_over = blk1;

            filename_over = filename1;

        } else {

            total_sectors_over = total_sectors2;

            blk_over = blk2;

            filename_over = filename2;

        }

        for (;;) {

            nb_sectors = sectors_to_process(total_sectors_over, sector_num);

            if (nb_sectors <= 0) {

                break;

            }

            ret = bdrv_is_allocated_above(blk_bs(blk_over), NULL, sector_num,

                                          nb_sectors, &pnum);

            if (ret < 0) {

                ret = 3;

                error_report("Sector allocation test failed for %s",

                             filename_over);

                goto out;

            }

            nb_sectors = pnum;

            if (ret) {

                ret = check_empty_sectors(blk_over, sector_num, nb_sectors,

                                          filename_over, buf1, quiet);

                if (ret) {

                    if (ret < 0) {

                        error_report("Error while reading offset %" PRId64

                                     " of %s: %s", sectors_to_bytes(sector_num),

                                     filename_over, strerror(-ret));

                        ret = 4;

                    }

                    goto out;

                }

            }

            sector_num += nb_sectors;

            qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);

        }

    }

    qprintf(quiet, "Images are identical.\n");

    ret = 0;

out:

    qemu_vfree(buf1);

    qemu_vfree(buf2);

    blk_unref(blk2);

out2:

    blk_unref(blk1);

out3:

    qemu_progress_end();

    return ret;

}


static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)

{

    struct video_data *s = s1->priv_data;

    AVStream *st;

    int width, height;

    int res, frame_rate, frame_rate_base;

    uint32_t desired_format, capabilities;

    const char *video_device;

    if (!ap || ap->width <= 0 || ap->height <= 0 || ap->time_base.den <= 0) {

        av_log(s1, AV_LOG_ERROR, "Missing/Wrong parameters\n");

        return -1;

    }

    width = ap->width;

    height = ap->height;

    frame_rate = ap->time_base.den;

    frame_rate_base = ap->time_base.num;

    if((unsigned)width > 32767 || (unsigned)height > 32767) {

        av_log(s1, AV_LOG_ERROR, "Wrong size %dx%d\n", width, height);

        return -1;

    }

    st = av_new_stream(s1, 0);

    if (!st) {

        return -ENOMEM;

    }

    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    s->width = width;

    s->height = height;

    s->frame_rate      = frame_rate;

    s->frame_rate_base = frame_rate_base;

    video_device = ap->device;

    if (!video_device) {

        video_device = "/dev/video";

    }

    capabilities = 0;

    s->fd = device_open(video_device, &capabilities);

    if (s->fd < 0) {

        av_free(st);

        return AVERROR_IO;

    }

    av_log(s1, AV_LOG_ERROR, "[%d]Capabilities: %x\n", s->fd, capabilities);

    desired_format = fmt_ff2v4l(ap->pix_fmt);

    if (desired_format == 0 || (device_init(s->fd, &width, &height, desired_format) < 0)) {

        int i, done;

        done = 0; i = 0;

        while (!done) {

            desired_format = fmt_conversion_table[i].v4l2_fmt;

            if (device_init(s->fd, &width, &height, desired_format) < 0) {

                desired_format = 0;

                i++;

            } else {

               done = 1;

            }

            if (i == sizeof(fmt_conversion_table) / sizeof(struct fmt_map)) {

               done = 1;

            }

        }

    }

    if (desired_format == 0) {

        av_log(s1, AV_LOG_ERROR, "Cannot find a proper format.\n");

        close(s->fd);

        av_free(st);

        return AVERROR_IO;

    }

    s->frame_format = desired_format;

    st->codec->pix_fmt = fmt_v4l2ff(desired_format);

    s->frame_size = avpicture_get_size(st->codec->pix_fmt, width, height);

    if (capabilities & V4L2_CAP_STREAMING) {

        s->io_method = io_mmap;

        res = mmap_init(s);

        res = mmap_start(s);

    } else {

        s->io_method = io_read;

        res = read_init(s);

    }

    if (res < 0) {

        close(s->fd);

        av_free(st);

        return AVERROR_IO;

    }

    s->top_field_first = first_field(s->fd);

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_RAWVIDEO;

    st->codec->width = width;

    st->codec->height = height;

    st->codec->time_base.den = frame_rate;

    st->codec->time_base.num = frame_rate_base;

    st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;

    return 0;

}


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

{

    int mod_state;

    if (!alt_grab) {

        mod_state = (ev->key.keysym.mod & gui_grab_code);

    } else {

        mod_state = (ev->key.keysym.mod & (gui_grab_code | KMOD_LSHIFT));

    }

    if (!mod_state && gui_key_modifier_pressed) {

        gui_key_modifier_pressed = 0;

        if (gui_keysym == 0) {

            /* exit/enter grab if pressing Ctrl-Alt */

            if (!gui_grab) {

                /* If the application is not active, do not try to enter grab

                 * state. It prevents 'SDL_WM_GrabInput(SDL_GRAB_ON)' from

                 * blocking all the application (SDL bug). */

                if (is_graphic_console() &&

                    SDL_GetAppState() & SDL_APPACTIVE) {

                    sdl_grab_start();

                }

            } else if (!gui_fullscreen) {

                sdl_grab_end();

            }

            /* SDL does not send back all the modifiers key, so we must

             * correct it. */

            reset_keys();

            return;

        }

        gui_keysym = 0;

    }

    if (is_graphic_console() && !gui_keysym) {

        sdl_process_key(&ev->key);

    }

}


static int mpegts_resync(ByteIOContext *pb)

{

    int c, i;

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

        c = url_fgetc(pb);

        if (c < 0)

            return -1;

        if (c == 0x47) {

            url_fseek(pb, -1, SEEK_CUR);

            return 0;

        }

    }

    /* no sync found */

    return -1;

}


static int write_header(FlashSV2Context * s, uint8_t * buf, int buf_size)

{

    PutBitContext pb;

    int buf_pos, len;

    if (buf_size < 5)

        return -1;

    init_put_bits(&pb, buf, buf_size * 8);

    put_bits(&pb, 4, (s->block_width  >> 4) - 1);

    put_bits(&pb, 12, s->image_width);

    put_bits(&pb, 4, (s->block_height >> 4) - 1);

    put_bits(&pb, 12, s->image_height);

    flush_put_bits(&pb);

    buf_pos = 4;

    buf[buf_pos++] = s->flags;

    if (s->flags & HAS_PALLET_INFO) {

        len = write_palette(s, buf + buf_pos, buf_size - buf_pos);

        if (len < 0)

            return -1;

        buf_pos += len;

    }

    return buf_pos;

}


void usb_ohci_init_pxa(target_phys_addr_t base, int num_ports, int devfn,

                       qemu_irq irq)

{

    OHCIState *ohci = (OHCIState *)qemu_mallocz(sizeof(OHCIState));

    usb_ohci_init(ohci, num_ports, devfn, irq,

                  OHCI_TYPE_PXA, "OHCI USB");

    ohci->mem_base = base;

    cpu_register_physical_memory(ohci->mem_base, 0xfff, ohci->mem);

}


static void RENAME(yuv2rgb32_1)(SwsContext *c, const int16_t *buf0,

                                const int16_t *ubuf[2], const int16_t *bguf[2],

                                const int16_t *abuf0, uint8_t *dest,

                                int dstW, int uvalpha, int y)

{

    const int16_t *ubuf0 = ubuf[0], *ubuf1 = ubuf[1];

    const int16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1(%%REGBP, %5)

                YSCALEYUV2RGB1_ALPHA(%%REGBP)

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (abuf0), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        } else {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1(%%REGBP, %5)

                "pcmpeqd %%mm7, %%mm7                   \n\t"

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        }

    } else {

        if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1b(%%REGBP, %5)

                YSCALEYUV2RGB1_ALPHA(%%REGBP)

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (abuf0), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        } else {

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

                "mov        %4, %%"REG_b"               \n\t"

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB1b(%%REGBP, %5)

                "pcmpeqd %%mm7, %%mm7                   \n\t"

                WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

                   "a" (&c->redDither)

            );

        }

    }

}


VirtIODevice *virtio_9p_init(DeviceState *dev, V9fsConf *conf)

 {

    V9fsState *s;

    int i, len;

    struct stat stat;

    FsTypeEntry *fse;

    s = (V9fsState *)virtio_common_init("virtio-9p",

                                    VIRTIO_ID_9P,

                                    sizeof(struct virtio_9p_config)+

                                    MAX_TAG_LEN,

                                    sizeof(V9fsState));

    /* initialize pdu allocator */

    QLIST_INIT(&s->free_list);

    for (i = 0; i < (MAX_REQ - 1); i++) {

	QLIST_INSERT_HEAD(&s->free_list, &s->pdus[i], next);

    }

    s->vq = virtio_add_queue(&s->vdev, MAX_REQ, handle_9p_output);

    fse = get_fsdev_fsentry(conf->fsdev_id);

    if (!fse) {

        /* We don't have a fsdev identified by fsdev_id */

        fprintf(stderr, "Virtio-9p device couldn't find fsdev "

                    "with the id %s\n", conf->fsdev_id);

        exit(1);

    }

    if (!fse->path || !conf->tag) {

        /* we haven't specified a mount_tag or the path */

        fprintf(stderr, "fsdev with id %s needs path "

                "and Virtio-9p device needs mount_tag arguments\n",

                conf->fsdev_id);

        exit(1);

    }

    if (!strcmp(fse->security_model, "passthrough")) {

        /* Files on the Fileserver set to client user credentials */

        s->ctx.fs_sm = SM_PASSTHROUGH;

    } else if (!strcmp(fse->security_model, "mapped")) {

        /* Files on the fileserver are set to QEMU credentials.

         * Client user credentials are saved in extended attributes.

         */

        s->ctx.fs_sm = SM_MAPPED;

    } else {

        /* user haven't specified a correct security option */

        fprintf(stderr, "one of the following must be specified as the"

                "security option:\n\t security_model=passthrough \n\t "

                "security_model=mapped\n");

        return NULL;

    }

    if (lstat(fse->path, &stat)) {

        fprintf(stderr, "share path %s does not exist\n", fse->path);

        exit(1);

    } else if (!S_ISDIR(stat.st_mode)) {

        fprintf(stderr, "share path %s is not a directory \n", fse->path);

        exit(1);

    }

    s->ctx.fs_root = qemu_strdup(fse->path);

    len = strlen(conf->tag);

    if (len > MAX_TAG_LEN) {

        len = MAX_TAG_LEN;

    }

    /* s->tag is non-NULL terminated string */

    s->tag = qemu_malloc(len);

    memcpy(s->tag, conf->tag, len);

    s->tag_len = len;

    s->ctx.uid = -1;

    s->ops = fse->ops;

    s->vdev.get_features = virtio_9p_get_features;

    s->config_size = sizeof(struct virtio_9p_config) +

                        s->tag_len;

    s->vdev.get_config = virtio_9p_get_config;

    return &s->vdev;

}


int pcilg_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2)

{

    CPUS390XState *env = &cpu->env;

    S390PCIBusDevice *pbdev;

    uint64_t offset;

    uint64_t data;

    MemoryRegion *mr;

    uint8_t len;

    uint32_t fh;

    uint8_t pcias;

    cpu_synchronize_state(CPU(cpu));

    if (env->psw.mask & PSW_MASK_PSTATE) {

        program_interrupt(env, PGM_PRIVILEGED, 4);

        return 0;

    }

    if (r2 & 0x1) {

        program_interrupt(env, PGM_SPECIFICATION, 4);

        return 0;

    }

    fh = env->regs[r2] >> 32;

    pcias = (env->regs[r2] >> 16) & 0xf;

    len = env->regs[r2] & 0xf;

    offset = env->regs[r2 + 1];

    pbdev = s390_pci_find_dev_by_fh(fh);

    if (!pbdev) {

        DPRINTF("pcilg no pci dev\n");

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    }

    switch (pbdev->state) {

    case ZPCI_FS_RESERVED:

    case ZPCI_FS_STANDBY:

    case ZPCI_FS_DISABLED:

    case ZPCI_FS_PERMANENT_ERROR:

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    case ZPCI_FS_ERROR:

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r2, ZPCI_PCI_ST_BLOCKED);

        return 0;

    default:

        break;

    }

    if (pcias < 6) {

        if ((8 - (offset & 0x7)) < len) {

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

        mr = pbdev->pdev->io_regions[pcias].memory;

        memory_region_dispatch_read(mr, offset, &data, len,

                                    MEMTXATTRS_UNSPECIFIED);

    } else if (pcias == 15) {

        if ((4 - (offset & 0x3)) < len) {

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

        data =  pci_host_config_read_common(

                   pbdev->pdev, offset, pci_config_size(pbdev->pdev), len);

        switch (len) {

        case 1:

            break;

        case 2:

            data = bswap16(data);

            break;

        case 4:

            data = bswap32(data);

            break;

        case 8:

            data = bswap64(data);

            break;

        default:

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

    } else {

        DPRINTF("invalid space\n");

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r2, ZPCI_PCI_ST_INVAL_AS);

        return 0;

    }

    env->regs[r1] = data;

    setcc(cpu, ZPCI_PCI_LS_OK);

    return 0;

}


static void vnc_client_cache_auth(VncState *client)

{

    if (!client->info) {

        return;

    }

#ifdef CONFIG_VNC_TLS

    if (client->tls.session &&

        client->tls.dname) {

        client->info->has_x509_dname = true;

        client->info->x509_dname = g_strdup(client->tls.dname);

    }

#endif

#ifdef CONFIG_VNC_SASL

    if (client->sasl.conn &&

        client->sasl.username) {

        client->info->has_sasl_username = true;

        client->info->sasl_username = g_strdup(client->sasl.username);

    }

#endif

}


static void add_wav(int16_t *dest, int n, int skip_first, int *m,

                    const int16_t *s1, const int8_t *s2, const int8_t *s3)

{

    int i;

    int v[3];

    v[0] = 0;

    for (i=!skip_first; i<3; i++)

        v[i] = (gain_val_tab[n][i] * m[i]) >> gain_exp_tab[n];

        dest[i] = (s1[i]*v[0] + s2[i]*v[1] + s3[i]*v[2]) >> 12;


void qtest_qmp(QTestState *s, const char *fmt, ...)
{
    va_list ap;
    bool has_reply = false;
    int nesting = 0;
    /* Send QMP request */
    va_start(ap, fmt);
    socket_sendf(s->qmp_fd, fmt, ap);
    va_end(ap);
    /* Receive reply */
    while (!has_reply || nesting > 0) {
        ssize_t len;
        char c;
        len = read(s->qmp_fd, &c, 1);
        if (len == -1 && errno == EINTR) {
            continue;
        switch (c) {
        case '{':
            nesting++;
            has_reply = true;
            break;
        case '}':
            nesting--;
            break;


static void vmxnet3_reset(VMXNET3State *s)

{

    VMW_CBPRN("Resetting vmxnet3...");

    vmxnet3_deactivate_device(s);

    vmxnet3_reset_interrupt_states(s);

    vmxnet_tx_pkt_reset(s->tx_pkt);

    s->drv_shmem = 0;

    s->tx_sop = true;

    s->skip_current_tx_pkt = false;

}


static av_cold int X264_close(AVCodecContext *avctx)

{

    X264Context *x4 = avctx->priv_data;

    av_freep(&avctx->extradata);

    av_free(x4->sei);

    if (x4->enc)

        x264_encoder_close(x4->enc);

    av_frame_free(&avctx->coded_frame);

    return 0;

}