START_TEST(qdict_haskey_not_test)

{

    fail_unless(qdict_haskey(tests_dict, "test") == 0);

}


static void test_acpi_piix4_tcg_memhp(void)

{

    test_data data;

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

    data.machine = MACHINE_PC;

    data.variant = ".memhp";

    test_acpi_one(" -m 128,slots=3,maxmem=1G -numa node", &data);

    free_test_data(&data);

}


static void gen_sse(DisasContext *s, int b, target_ulong pc_start, int rex_r)

{

    int b1, op1_offset, op2_offset, is_xmm, val, ot;

    int modrm, mod, rm, reg, reg_addr, offset_addr;

    GenOpFunc2 *sse_op2;

    GenOpFunc3 *sse_op3;

    b &= 0xff;

    if (s->prefix & PREFIX_DATA)

        b1 = 1;

    else if (s->prefix & PREFIX_REPZ)

        b1 = 2;

    else if (s->prefix & PREFIX_REPNZ)

        b1 = 3;

    else

        b1 = 0;

    sse_op2 = sse_op_table1[b][b1];

    if (!sse_op2)

        goto illegal_op;

    if ((b <= 0x5f && b >= 0x10) || b == 0xc6 || b == 0xc2) {

        is_xmm = 1;

    } else {

        if (b1 == 0) {

            /* MMX case */

            is_xmm = 0;

        } else {

            is_xmm = 1;

        }

    }

    /* simple MMX/SSE operation */

    if (s->flags & HF_TS_MASK) {

        gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);

        return;

    }

    if (s->flags & HF_EM_MASK) {

    illegal_op:

        gen_exception(s, EXCP06_ILLOP, pc_start - s->cs_base);

        return;

    }

    if (is_xmm && !(s->flags & HF_OSFXSR_MASK))

        goto illegal_op;

    if (b == 0x77 || b == 0x0e) {

        /* emms or femms */

        gen_op_emms();

        return;

    }

    /* prepare MMX state (XXX: optimize by storing fptt and fptags in

       the static cpu state) */

    if (!is_xmm) {

        gen_op_enter_mmx();

    }

    modrm = ldub_code(s->pc++);

    reg = ((modrm >> 3) & 7);

    if (is_xmm)

        reg |= rex_r;

    mod = (modrm >> 6) & 3;

    if (sse_op2 == SSE_SPECIAL) {

        b |= (b1 << 8);

        switch(b) {

        case 0x0e7: /* movntq */

            if (mod == 3)

                goto illegal_op;

            gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

            gen_stq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,fpregs[reg].mmx));

            break;

        case 0x1e7: /* movntdq */

        case 0x02b: /* movntps */

        case 0x12b: /* movntps */

        case 0x3f0: /* lddqu */

            if (mod == 3)

                goto illegal_op;

            gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

            gen_sto_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg]));

            break;

        case 0x6e: /* movd mm, ea */

#ifdef TARGET_X86_64

            if (s->dflag == 2) {

                gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 0);

                gen_op_movq_mm_T0_mmx(offsetof(CPUX86State,fpregs[reg].mmx));

            } else

#endif

            {

                gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 0);

                gen_op_movl_mm_T0_mmx(offsetof(CPUX86State,fpregs[reg].mmx));

            }

            break;

        case 0x16e: /* movd xmm, ea */

#ifdef TARGET_X86_64

            if (s->dflag == 2) {

                gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 0);

                gen_op_movq_mm_T0_xmm(offsetof(CPUX86State,xmm_regs[reg]));

            } else

#endif

            {

                gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 0);

                gen_op_movl_mm_T0_xmm(offsetof(CPUX86State,xmm_regs[reg]));

            }

            break;

        case 0x6f: /* movq mm, ea */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,fpregs[reg].mmx));

            } else {

                rm = (modrm & 7);

                gen_op_movq(offsetof(CPUX86State,fpregs[reg].mmx),

                            offsetof(CPUX86State,fpregs[rm].mmx));

            }

            break;

        case 0x010: /* movups */

        case 0x110: /* movupd */

        case 0x028: /* movaps */

        case 0x128: /* movapd */

        case 0x16f: /* movdqa xmm, ea */

        case 0x26f: /* movdqu xmm, ea */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldo_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg]));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movo(offsetof(CPUX86State,xmm_regs[reg]),

                            offsetof(CPUX86State,xmm_regs[rm]));

            }

            break;

        case 0x210: /* movss xmm, ea */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_op_ld_T0_A0(OT_LONG + s->mem_index);

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));

                gen_op_movl_T0_0();

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)));

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)));

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_L(0)));

            }

            break;

        case 0x310: /* movsd xmm, ea */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

                gen_op_movl_T0_0();

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)));

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));

            }

            break;

        case 0x012: /* movlps */

        case 0x112: /* movlpd */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            } else {

                /* movhlps */

                rm = (modrm & 7) | REX_B(s);

                gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_Q(1)));

            }

            break;

        case 0x212: /* movsldup */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldo_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg]));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_L(0)));

                gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_L(2)));

            }

            gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)),

                        offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));

            gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)),

                        offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)));

            break;

        case 0x312: /* movddup */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));

            }

            gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)),

                        offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            break;

        case 0x016: /* movhps */

        case 0x116: /* movhpd */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));

            } else {

                /* movlhps */

                rm = (modrm & 7) | REX_B(s);

                gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));

            }

            break;

        case 0x216: /* movshdup */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldo_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg]));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_L(1)));

                gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_L(3)));

            }

            gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)),

                        offsetof(CPUX86State,xmm_regs[reg].XMM_L(1)));

            gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].XMM_L(2)),

                        offsetof(CPUX86State,xmm_regs[reg].XMM_L(3)));

            break;

        case 0x7e: /* movd ea, mm */

#ifdef TARGET_X86_64

            if (s->dflag == 2) {

                gen_op_movq_T0_mm_mmx(offsetof(CPUX86State,fpregs[reg].mmx));

                gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 1);

            } else

#endif

            {

                gen_op_movl_T0_mm_mmx(offsetof(CPUX86State,fpregs[reg].mmx));

                gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 1);

            }

            break;

        case 0x17e: /* movd ea, xmm */

#ifdef TARGET_X86_64

            if (s->dflag == 2) {

                gen_op_movq_T0_mm_xmm(offsetof(CPUX86State,xmm_regs[reg]));

                gen_ldst_modrm(s, modrm, OT_QUAD, OR_TMP0, 1);

            } else

#endif

            {

                gen_op_movl_T0_mm_xmm(offsetof(CPUX86State,xmm_regs[reg]));

                gen_ldst_modrm(s, modrm, OT_LONG, OR_TMP0, 1);

            }

            break;

        case 0x27e: /* movq xmm, ea */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),

                            offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));

            }

            gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));

            break;

        case 0x7f: /* movq ea, mm */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_stq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,fpregs[reg].mmx));

            } else {

                rm = (modrm & 7);

                gen_op_movq(offsetof(CPUX86State,fpregs[rm].mmx),

                            offsetof(CPUX86State,fpregs[reg].mmx));

            }

            break;

        case 0x011: /* movups */

        case 0x111: /* movupd */

        case 0x029: /* movaps */

        case 0x129: /* movapd */

        case 0x17f: /* movdqa ea, xmm */

        case 0x27f: /* movdqu ea, xmm */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_sto_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg]));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movo(offsetof(CPUX86State,xmm_regs[rm]),

                            offsetof(CPUX86State,xmm_regs[reg]));

            }

            break;

        case 0x211: /* movss ea, xmm */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_op_movl_T0_env(offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));

                gen_op_st_T0_A0(OT_LONG + s->mem_index);

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movl(offsetof(CPUX86State,xmm_regs[rm].XMM_L(0)),

                            offsetof(CPUX86State,xmm_regs[reg].XMM_L(0)));

            }

            break;

        case 0x311: /* movsd ea, xmm */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_stq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)),

                            offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            }

            break;

        case 0x013: /* movlps */

        case 0x113: /* movlpd */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_stq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            } else {

                goto illegal_op;

            }

            break;

        case 0x017: /* movhps */

        case 0x117: /* movhpd */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_stq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));

            } else {

                goto illegal_op;

            }

            break;

        case 0x71: /* shift mm, im */

        case 0x72:

        case 0x73:

        case 0x171: /* shift xmm, im */

        case 0x172:

        case 0x173:

            val = ldub_code(s->pc++);

            if (is_xmm) {

                gen_op_movl_T0_im(val);

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_t0.XMM_L(0)));

                gen_op_movl_T0_0();

                gen_op_movl_env_T0(offsetof(CPUX86State,xmm_t0.XMM_L(1)));

                op1_offset = offsetof(CPUX86State,xmm_t0);

            } else {

                gen_op_movl_T0_im(val);

                gen_op_movl_env_T0(offsetof(CPUX86State,mmx_t0.MMX_L(0)));

                gen_op_movl_T0_0();

                gen_op_movl_env_T0(offsetof(CPUX86State,mmx_t0.MMX_L(1)));

                op1_offset = offsetof(CPUX86State,mmx_t0);

            }

            sse_op2 = sse_op_table2[((b - 1) & 3) * 8 + (((modrm >> 3)) & 7)][b1];

            if (!sse_op2)

                goto illegal_op;

            if (is_xmm) {

                rm = (modrm & 7) | REX_B(s);

                op2_offset = offsetof(CPUX86State,xmm_regs[rm]);

            } else {

                rm = (modrm & 7);

                op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);

            }

            sse_op2(op2_offset, op1_offset);

            break;

        case 0x050: /* movmskps */

            rm = (modrm & 7) | REX_B(s);

            gen_op_movmskps(offsetof(CPUX86State,xmm_regs[rm]));

            gen_op_mov_reg_T0(OT_LONG, reg);

            break;

        case 0x150: /* movmskpd */

            rm = (modrm & 7) | REX_B(s);

            gen_op_movmskpd(offsetof(CPUX86State,xmm_regs[rm]));

            gen_op_mov_reg_T0(OT_LONG, reg);

            break;

        case 0x02a: /* cvtpi2ps */

        case 0x12a: /* cvtpi2pd */

            gen_op_enter_mmx();

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                op2_offset = offsetof(CPUX86State,mmx_t0);

                gen_ldq_env_A0[s->mem_index >> 2](op2_offset);

            } else {

                rm = (modrm & 7);

                op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);

            }

            op1_offset = offsetof(CPUX86State,xmm_regs[reg]);

            switch(b >> 8) {

            case 0x0:

                gen_op_cvtpi2ps(op1_offset, op2_offset);

                break;

            default:

            case 0x1:

                gen_op_cvtpi2pd(op1_offset, op2_offset);

                break;

            }

            break;

        case 0x22a: /* cvtsi2ss */

        case 0x32a: /* cvtsi2sd */

            ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;

            gen_ldst_modrm(s, modrm, ot, OR_TMP0, 0);

            op1_offset = offsetof(CPUX86State,xmm_regs[reg]);

            sse_op_table3[(s->dflag == 2) * 2 + ((b >> 8) - 2)](op1_offset);

            break;

        case 0x02c: /* cvttps2pi */

        case 0x12c: /* cvttpd2pi */

        case 0x02d: /* cvtps2pi */

        case 0x12d: /* cvtpd2pi */

            gen_op_enter_mmx();

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                op2_offset = offsetof(CPUX86State,xmm_t0);

                gen_ldo_env_A0[s->mem_index >> 2](op2_offset);

            } else {

                rm = (modrm & 7) | REX_B(s);

                op2_offset = offsetof(CPUX86State,xmm_regs[rm]);

            }

            op1_offset = offsetof(CPUX86State,fpregs[reg & 7].mmx);

            switch(b) {

            case 0x02c:

                gen_op_cvttps2pi(op1_offset, op2_offset);

                break;

            case 0x12c:

                gen_op_cvttpd2pi(op1_offset, op2_offset);

                break;

            case 0x02d:

                gen_op_cvtps2pi(op1_offset, op2_offset);

                break;

            case 0x12d:

                gen_op_cvtpd2pi(op1_offset, op2_offset);

                break;

            }

            break;

        case 0x22c: /* cvttss2si */

        case 0x32c: /* cvttsd2si */

        case 0x22d: /* cvtss2si */

        case 0x32d: /* cvtsd2si */

            ot = (s->dflag == 2) ? OT_QUAD : OT_LONG;

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                if ((b >> 8) & 1) {

                    gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_t0.XMM_Q(0)));

                } else {

                    gen_op_ld_T0_A0(OT_LONG + s->mem_index);

                    gen_op_movl_env_T0(offsetof(CPUX86State,xmm_t0.XMM_L(0)));

                }

                op2_offset = offsetof(CPUX86State,xmm_t0);

            } else {

                rm = (modrm & 7) | REX_B(s);

                op2_offset = offsetof(CPUX86State,xmm_regs[rm]);

            }

            sse_op_table3[(s->dflag == 2) * 2 + ((b >> 8) - 2) + 4 +

                          (b & 1) * 4](op2_offset);

            gen_op_mov_reg_T0(ot, reg);

            break;

        case 0xc4: /* pinsrw */

        case 0x1c4:

            s->rip_offset = 1;

            gen_ldst_modrm(s, modrm, OT_WORD, OR_TMP0, 0);

            val = ldub_code(s->pc++);

            if (b1) {

                val &= 7;

                gen_op_pinsrw_xmm(offsetof(CPUX86State,xmm_regs[reg]), val);

            } else {

                val &= 3;

                gen_op_pinsrw_mmx(offsetof(CPUX86State,fpregs[reg].mmx), val);

            }

            break;

        case 0xc5: /* pextrw */

        case 0x1c5:

            if (mod != 3)

                goto illegal_op;

            val = ldub_code(s->pc++);

            if (b1) {

                val &= 7;

                rm = (modrm & 7) | REX_B(s);

                gen_op_pextrw_xmm(offsetof(CPUX86State,xmm_regs[rm]), val);

            } else {

                val &= 3;

                rm = (modrm & 7);

                gen_op_pextrw_mmx(offsetof(CPUX86State,fpregs[rm].mmx), val);

            }

            reg = ((modrm >> 3) & 7) | rex_r;

            gen_op_mov_reg_T0(OT_LONG, reg);

            break;

        case 0x1d6: /* movq ea, xmm */

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                gen_stq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

            } else {

                rm = (modrm & 7) | REX_B(s);

                gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)),

                            offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)));

                gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[rm].XMM_Q(1)));

            }

            break;

        case 0x2d6: /* movq2dq */

            gen_op_enter_mmx();

            rm = (modrm & 7);

            gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(0)),

                        offsetof(CPUX86State,fpregs[rm].mmx));

            gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].XMM_Q(1)));

            break;

        case 0x3d6: /* movdq2q */

            gen_op_enter_mmx();

            rm = (modrm & 7) | REX_B(s);

            gen_op_movq(offsetof(CPUX86State,fpregs[reg & 7].mmx),

                        offsetof(CPUX86State,xmm_regs[rm].XMM_Q(0)));

            break;

        case 0xd7: /* pmovmskb */

        case 0x1d7:

            if (mod != 3)

                goto illegal_op;

            if (b1) {

                rm = (modrm & 7) | REX_B(s);

                gen_op_pmovmskb_xmm(offsetof(CPUX86State,xmm_regs[rm]));

            } else {

                rm = (modrm & 7);

                gen_op_pmovmskb_mmx(offsetof(CPUX86State,fpregs[rm].mmx));

            }

            reg = ((modrm >> 3) & 7) | rex_r;

            gen_op_mov_reg_T0(OT_LONG, reg);

            break;

        default:

            goto illegal_op;

        }

    } else {

        /* generic MMX or SSE operation */

        switch(b) {

        case 0xf7:

            /* maskmov : we must prepare A0 */

            if (mod != 3)

                goto illegal_op;

#ifdef TARGET_X86_64

            if (s->aflag == 2) {

                gen_op_movq_A0_reg(R_EDI);

            } else

#endif

            {

                gen_op_movl_A0_reg(R_EDI);

                if (s->aflag == 0)

                    gen_op_andl_A0_ffff();

            }

            gen_add_A0_ds_seg(s);

            break;

        case 0x70: /* pshufx insn */

        case 0xc6: /* pshufx insn */

        case 0xc2: /* compare insns */

            s->rip_offset = 1;

            break;

        default:

            break;

        }

        if (is_xmm) {

            op1_offset = offsetof(CPUX86State,xmm_regs[reg]);

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                op2_offset = offsetof(CPUX86State,xmm_t0);

                if (b1 >= 2 && ((b >= 0x50 && b <= 0x5f && b != 0x5b) ||

                                b == 0xc2)) {

                    /* specific case for SSE single instructions */

                    if (b1 == 2) {

                        /* 32 bit access */

                        gen_op_ld_T0_A0(OT_LONG + s->mem_index);

                        gen_op_movl_env_T0(offsetof(CPUX86State,xmm_t0.XMM_L(0)));

                    } else {

                        /* 64 bit access */

                        gen_ldq_env_A0[s->mem_index >> 2](offsetof(CPUX86State,xmm_t0.XMM_D(0)));

                    }

                } else {

                    gen_ldo_env_A0[s->mem_index >> 2](op2_offset);

                }

            } else {

                rm = (modrm & 7) | REX_B(s);

                op2_offset = offsetof(CPUX86State,xmm_regs[rm]);

            }

        } else {

            op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);

            if (mod != 3) {

                gen_lea_modrm(s, modrm, &reg_addr, &offset_addr);

                op2_offset = offsetof(CPUX86State,mmx_t0);

                gen_ldq_env_A0[s->mem_index >> 2](op2_offset);

            } else {

                rm = (modrm & 7);

                op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);

            }

        }

        switch(b) {

        case 0x0f: /* 3DNow! data insns */

            val = ldub_code(s->pc++);

            sse_op2 = sse_op_table5[val];

            if (!sse_op2)

                goto illegal_op;

            sse_op2(op1_offset, op2_offset);

            break;

        case 0x70: /* pshufx insn */

        case 0xc6: /* pshufx insn */

            val = ldub_code(s->pc++);

            sse_op3 = (GenOpFunc3 *)sse_op2;

            sse_op3(op1_offset, op2_offset, val);

            break;

        case 0xc2:

            /* compare insns */

            val = ldub_code(s->pc++);

            if (val >= 8)

                goto illegal_op;

            sse_op2 = sse_op_table4[val][b1];

            sse_op2(op1_offset, op2_offset);

            break;

        default:

            sse_op2(op1_offset, op2_offset);

            break;

        }

        if (b == 0x2e || b == 0x2f) {

            s->cc_op = CC_OP_EFLAGS;

        }

    }

}


int ff_h264_pred_weight_table(GetBitContext *gb, const SPS *sps,

                              const int *ref_count, int slice_type_nos,

                              H264PredWeightTable *pwt, void *logctx)

{

    int list, i, j;

    int luma_def, chroma_def;

    pwt->use_weight             = 0;

    pwt->use_weight_chroma      = 0;

    pwt->luma_log2_weight_denom = get_ue_golomb(gb);

    if (sps->chroma_format_idc)

        pwt->chroma_log2_weight_denom = get_ue_golomb(gb);

    if (pwt->luma_log2_weight_denom > 7U) {

        av_log(logctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", pwt->luma_log2_weight_denom);

        pwt->luma_log2_weight_denom = 0;

    }

    if (pwt->chroma_log2_weight_denom > 7U) {

        av_log(logctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", pwt->chroma_log2_weight_denom);

        pwt->chroma_log2_weight_denom = 0;

    }

    luma_def   = 1 << pwt->luma_log2_weight_denom;

    chroma_def = 1 << pwt->chroma_log2_weight_denom;

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

        pwt->luma_weight_flag[list]   = 0;

        pwt->chroma_weight_flag[list] = 0;

        for (i = 0; i < ref_count[list]; i++) {

            int luma_weight_flag, chroma_weight_flag;

            luma_weight_flag = get_bits1(gb);

            if (luma_weight_flag) {

                pwt->luma_weight[i][list][0] = get_se_golomb(gb);

                pwt->luma_weight[i][list][1] = get_se_golomb(gb);

                if (pwt->luma_weight[i][list][0] != luma_def ||

                    pwt->luma_weight[i][list][1] != 0) {

                    pwt->use_weight             = 1;

                    pwt->luma_weight_flag[list] = 1;

                }

            } else {

                pwt->luma_weight[i][list][0] = luma_def;

                pwt->luma_weight[i][list][1] = 0;

            }

            if (sps->chroma_format_idc) {

                chroma_weight_flag = get_bits1(gb);

                if (chroma_weight_flag) {

                    int j;

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

                        pwt->chroma_weight[i][list][j][0] = get_se_golomb(gb);

                        pwt->chroma_weight[i][list][j][1] = get_se_golomb(gb);

                        if ((int8_t)pwt->chroma_weight[i][list][j][0] != pwt->chroma_weight[i][list][j][0] ||

                            (int8_t)pwt->chroma_weight[i][list][j][1] != pwt->chroma_weight[i][list][j][1])

                        if (pwt->chroma_weight[i][list][j][0] != chroma_def ||

                            pwt->chroma_weight[i][list][j][1] != 0) {

                            pwt->use_weight_chroma        = 1;

                            pwt->chroma_weight_flag[list] = 1;

                        }

                    }

                } else {

                    int j;

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

                        pwt->chroma_weight[i][list][j][0] = chroma_def;

                        pwt->chroma_weight[i][list][j][1] = 0;

                    }

                }

            }

            // for MBAFF

            pwt->luma_weight[16 + 2 * i][list][0] = pwt->luma_weight[16 + 2 * i + 1][list][0] = pwt->luma_weight[i][list][0];

            pwt->luma_weight[16 + 2 * i][list][1] = pwt->luma_weight[16 + 2 * i + 1][list][1] = pwt->luma_weight[i][list][1];

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

                pwt->chroma_weight[16 + 2 * i][list][j][0] = pwt->chroma_weight[16 + 2 * i + 1][list][j][0] = pwt->chroma_weight[i][list][j][0];

                pwt->chroma_weight[16 + 2 * i][list][j][1] = pwt->chroma_weight[16 + 2 * i + 1][list][j][1] = pwt->chroma_weight[i][list][j][1];

            }

        }

        if (slice_type_nos != AV_PICTURE_TYPE_B)

            break;

    }

    pwt->use_weight = pwt->use_weight || pwt->use_weight_chroma;

    return 0;

out_range_weight:

    avpriv_request_sample(logctx, "Out of range weight\n");

    return AVERROR_INVALIDDATA;

}


static int do_vm_stop(RunState state)

{

    int ret = 0;

    if (runstate_is_running()) {

        cpu_disable_ticks();

        pause_all_vcpus();

        runstate_set(state);

        vm_state_notify(0, state);

        qapi_event_send_stop(&error_abort);

    }

    bdrv_drain_all();

    ret = blk_flush_all();

    return ret;

}


static int cin_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    CinDemuxContext *cin = s->priv_data;

    ByteIOContext *pb = s->pb;

    CinFrameHeader *hdr = &cin->frame_header;

    int rc, palette_type, pkt_size;

    if (cin->audio_buffer_size == 0) {

        rc = cin_read_frame_header(cin, pb);

        if (rc)

            return rc;

        if ((int16_t)hdr->pal_colors_count < 0) {

            hdr->pal_colors_count = -(int16_t)hdr->pal_colors_count;

            palette_type = 1;

        } else {

            palette_type = 0;

        }

        /* palette and video packet */

        pkt_size = (palette_type + 3) * hdr->pal_colors_count + hdr->video_frame_size;

        if (av_new_packet(pkt, 4 + pkt_size))

            return AVERROR(ENOMEM);

        pkt->stream_index = cin->video_stream_index;

        pkt->pts = cin->video_stream_pts++;

        pkt->data[0] = palette_type;

        pkt->data[1] = hdr->pal_colors_count & 0xFF;

        pkt->data[2] = hdr->pal_colors_count >> 8;

        pkt->data[3] = hdr->video_frame_type;

        if (get_buffer(pb, &pkt->data[4], pkt_size) != pkt_size)

            return AVERROR(EIO);

        /* sound buffer will be processed on next read_packet() call */

        cin->audio_buffer_size = hdr->audio_frame_size;

        return 0;

    }

    /* audio packet */

    if (av_new_packet(pkt, cin->audio_buffer_size))

        return AVERROR(ENOMEM);

    pkt->stream_index = cin->audio_stream_index;

    pkt->pts = cin->audio_stream_pts;

    cin->audio_stream_pts += cin->audio_buffer_size * 2 / cin->file_header.audio_frame_size;

    if (get_buffer(pb, pkt->data, cin->audio_buffer_size) != cin->audio_buffer_size)

        return AVERROR(EIO);

    cin->audio_buffer_size = 0;

    return 0;

}


static void kvm_do_inject_x86_mce(void *_data)

{

    struct kvm_x86_mce_data *data = _data;

    int r;

    r = kvm_set_mce(data->env, data->mce);

    if (r < 0)

        perror("kvm_set_mce FAILED");

}


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

{

    V4L2m2mContext *s = avctx->priv_data;

    V4L2Context *const capture = &s->capture;

    V4L2Context *const output = &s->output;

    int ret;

    if (s->draining)

        goto dequeue;

    if (!output->streamon) {

        ret = ff_v4l2_context_set_status(output, VIDIOC_STREAMON);

        if (ret) {

            av_log(avctx, AV_LOG_ERROR, "VIDIOC_STREAMOFF failed on output context\n");

            return ret;

        }

    }

    if (!capture->streamon) {

        ret = ff_v4l2_context_set_status(capture, VIDIOC_STREAMON);

        if (ret) {

            av_log(avctx, AV_LOG_ERROR, "VIDIOC_STREAMON failed on capture context\n");

            return ret;

        }

    }

dequeue:

    return ff_v4l2_context_dequeue_packet(capture, avpkt);

}


static int mov_rewrite_dvd_sub_extradata(AVStream *st)

{

    char pal_s[256];

    char buf[256];

    int pal_s_pos = 0;

    uint8_t *src = st->codec->extradata;

    int i;

    if (st->codec->extradata_size != 64)

        return 0;

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

        uint32_t yuv = AV_RB32(src + i * 4);

        uint32_t rgba = yuv_to_rgba(yuv);

        snprintf(pal_s + pal_s_pos, sizeof(pal_s) - pal_s_pos, "%06x%s", rgba,

                 i != 15 ? ", " : "");

        pal_s_pos = strlen(pal_s);

        if (pal_s_pos >= sizeof(pal_s))

            return 0;

    }

    snprintf(buf, sizeof(buf), "size: %dx%d\npalette: %s\n",

             st->codec->width, st->codec->height, pal_s);

    av_freep(&st->codec->extradata);

    st->codec->extradata_size = 0;

    st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!st->codec->extradata)

        return AVERROR(ENOMEM);

    st->codec->extradata_size = strlen(buf);

    memcpy(st->codec->extradata, buf, st->codec->extradata_size);

    return 0;

}


static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)

{

    OutputFile *of = output_files[ost->file_index];

    int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);

    AVPacket opkt;

    av_init_packet(&opkt);

    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&

        !ost->copy_initial_nonkeyframes)

        return;

    if (of->recording_time != INT64_MAX &&

        ist->last_dts >= of->recording_time + of->start_time) {

        ost->is_past_recording_time = 1;

        return;

    }

    /* force the input stream PTS */

    if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

        audio_size += pkt->size;

    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

        video_size += pkt->size;

        ost->sync_opts++;

    }

    if (pkt->pts != AV_NOPTS_VALUE)

        opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;

    else

        opkt.pts = AV_NOPTS_VALUE;

    if (pkt->dts == AV_NOPTS_VALUE)

        opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);

    else

        opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);

    opkt.dts -= ost_tb_start_time;

    opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);

    opkt.flags    = pkt->flags;

    // FIXME remove the following 2 lines they shall be replaced by the bitstream filters

    if (  ost->st->codec->codec_id != AV_CODEC_ID_H264

       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO

       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO

       && ost->st->codec->codec_id != AV_CODEC_ID_VC1

       ) {

        if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))

            opkt.destruct = av_destruct_packet;

    } else {

        opkt.data = pkt->data;

        opkt.size = pkt->size;

    }

    write_frame(of->ctx, &opkt, ost);

    ost->st->codec->frame_number++;

    av_free_packet(&opkt);

}


static int au_read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    int ret;

    ret= av_get_packet(s->pb, pkt, BLOCK_SIZE *

                       s->streams[0]->codec->channels *

                       av_get_bits_per_sample(s->streams[0]->codec->codec_id) >> 3);

    if (ret < 0)

        return ret;

    pkt->flags &= ~AV_PKT_FLAG_CORRUPT;

    pkt->stream_index = 0;

    return 0;

}


int av_find_stream_info(AVFormatContext *ic)

{

    int i, count, ret, read_size, j;

    AVStream *st;

    AVPacket pkt1, *pkt;

    int64_t old_offset = url_ftell(ic->pb);

    struct {

        int64_t last_dts;

        int64_t duration_gcd;

        int duration_count;

        double duration_error[MAX_STD_TIMEBASES];

        int64_t codec_info_duration;

    } info[MAX_STREAMS] = {{0}};

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

        st = ic->streams[i];

        if (st->codec->codec_id == CODEC_ID_AAC) {

            st->codec->sample_rate = 0;

            st->codec->frame_size = 0;

            st->codec->channels = 0;

        }

        if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){

/*            if(!st->time_base.num)

                st->time_base= */

            if(!st->codec->time_base.num)

                st->codec->time_base= st->time_base;

        }

        //only for the split stuff

        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {

            st->parser = av_parser_init(st->codec->codec_id);

            if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){

                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;

            }

        }

        assert(!st->codec->codec);

        //try to just open decoders, in case this is enough to get parameters

        if(!has_codec_parameters(st->codec)){

            AVCodec *codec = avcodec_find_decoder(st->codec->codec_id);

            if (codec)

                avcodec_open(st->codec, codec);

        }

    }

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

        info[i].last_dts= AV_NOPTS_VALUE;

    }

    count = 0;

    read_size = 0;

    for(;;) {

        if(url_interrupt_cb()){

            ret= AVERROR(EINTR);

            av_log(ic, AV_LOG_DEBUG, "interrupted\n");

            break;

        }

        /* check if one codec still needs to be handled */

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

            st = ic->streams[i];

            if (!has_codec_parameters(st->codec))

                break;

            /* variable fps and no guess at the real fps */

            if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)

               && info[i].duration_count<20 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

                break;

            if(st->parser && st->parser->parser->split && !st->codec->extradata)

                break;

            if(st->first_dts == AV_NOPTS_VALUE)

                break;

        }

        if (i == ic->nb_streams) {

            /* NOTE: if the format has no header, then we need to read

               some packets to get most of the streams, so we cannot

               stop here */

            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {

                /* if we found the info for all the codecs, we can stop */

                ret = count;

                av_log(ic, AV_LOG_DEBUG, "All info found\n");

                break;

            }

        }

        /* we did not get all the codec info, but we read too much data */

        if (read_size >= ic->probesize) {

            ret = count;

            av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);

            break;

        }

        /* NOTE: a new stream can be added there if no header in file

           (AVFMTCTX_NOHEADER) */

        ret = av_read_frame_internal(ic, &pkt1);

        if(ret == AVERROR(EAGAIN))

            continue;

        if (ret < 0) {

            /* EOF or error */

            ret = -1; /* we could not have all the codec parameters before EOF */

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

                st = ic->streams[i];

                if (!has_codec_parameters(st->codec)){

                    char buf[256];

                    avcodec_string(buf, sizeof(buf), st->codec, 0);

                    av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);

                } else {

                    ret = 0;

                }

            }

            break;

        }

        pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);

        if(av_dup_packet(pkt) < 0) {

            return AVERROR(ENOMEM);

        }

        read_size += pkt->size;

        st = ic->streams[pkt->stream_index];

        if(st->codec_info_nb_frames>1) {

            if (st->time_base.den > 0 && av_rescale_q(info[st->index].codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration){

                av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");

                break;

            }

            info[st->index].codec_info_duration += pkt->duration;

        }

        {

            int index= pkt->stream_index;

            int64_t last= info[index].last_dts;

            int64_t duration= pkt->dts - last;

            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){

                double dur= duration * av_q2d(st->time_base);

//                if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

//                    av_log(NULL, AV_LOG_ERROR, "%f\n", dur);

                if(info[index].duration_count < 2)

                    memset(info[index].duration_error, 0, sizeof(info[index].duration_error));

                for(i=1; i<MAX_STD_TIMEBASES; i++){

                    int framerate= get_std_framerate(i);

                    int ticks= lrintf(dur*framerate/(1001*12));

                    double error= dur - ticks*1001*12/(double)framerate;

                    info[index].duration_error[i] += error*error;

                }

                info[index].duration_count++;

                // ignore the first 4 values, they might have some random jitter

                if (info[index].duration_count > 3)

                    info[index].duration_gcd = av_gcd(info[index].duration_gcd, duration);

            }

            if(last == AV_NOPTS_VALUE || info[index].duration_count <= 1)

                info[pkt->stream_index].last_dts = pkt->dts;

        }

        if(st->parser && st->parser->parser->split && !st->codec->extradata){

            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);

            if(i){

                st->codec->extradata_size= i;

                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);

                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);

            }

        }

        /* if still no information, we try to open the codec and to

           decompress the frame. We try to avoid that in most cases as

           it takes longer and uses more memory. For MPEG-4, we need to

           decompress for QuickTime. */

        if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))

            try_decode_frame(st, pkt);

        st->codec_info_nb_frames++;

        count++;

    }

    // close codecs which were opened in try_decode_frame()

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

        st = ic->streams[i];

        if(st->codec->codec)

            avcodec_close(st->codec);

    }

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

        st = ic->streams[i];

        if(st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && info[i].codec_info_duration)

            av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,

                     (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,

                      info[i].codec_info_duration*(int64_t)st->time_base.num, 60000);

        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample)

                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);

            // the check for tb_unreliable() is not completely correct, since this is not about handling

            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.

            // ipmovie.c produces.

            if (tb_unreliable(st->codec) && info[i].duration_count > 15 && info[i].duration_gcd > 1 && !st->r_frame_rate.num)

                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * info[i].duration_gcd, INT_MAX);

            if(info[i].duration_count && !st->r_frame_rate.num

               && tb_unreliable(st->codec) /*&&

               //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...

               st->time_base.num*duration_sum[i]/info[i].duration_count*101LL > st->time_base.den*/){

                int num = 0;

                double best_error= 2*av_q2d(st->time_base);

                best_error= best_error*best_error*info[i].duration_count*1000*12*30;

                for(j=1; j<MAX_STD_TIMEBASES; j++){

                    double error= info[i].duration_error[j] * get_std_framerate(j);

//                    if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

//                        av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);

                    if(error < best_error){

                        best_error= error;

                        num = get_std_framerate(j);

                    }

                }

                // do not increase frame rate by more than 1 % in order to match a standard rate.

                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))

                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);

            }

            if (!st->r_frame_rate.num){

                if(    st->codec->time_base.den * (int64_t)st->time_base.num

                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){

                    st->r_frame_rate.num = st->codec->time_base.den;

                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;

                }else{

                    st->r_frame_rate.num = st->time_base.den;

                    st->r_frame_rate.den = st->time_base.num;

                }

            }

        }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if(!st->codec->bits_per_coded_sample)

                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);

        }

    }

    av_estimate_timings(ic, old_offset);

    compute_chapters_end(ic);

#if 0

    /* correct DTS for B-frame streams with no timestamps */

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

        st = ic->streams[i];

        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

            if(b-frames){

                ppktl = &ic->packet_buffer;

                while(ppkt1){

                    if(ppkt1->stream_index != i)

                        continue;

                    if(ppkt1->pkt->dts < 0)

                        break;

                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)

                        break;

                    ppkt1->pkt->dts -= delta;

                    ppkt1= ppkt1->next;

                }

                if(ppkt1)

                    continue;

                st->cur_dts -= delta;

            }

        }

    }

#endif

    return ret;

}


static int r3d_read_reda(AVFormatContext *s, AVPacket *pkt, Atom *atom)

{

    AVStream *st = s->streams[1];

    int av_unused tmp, tmp2;

    int samples, size;

    uint64_t pos = avio_tell(s->pb);

    unsigned dts;

    int ret;

    dts = avio_rb32(s->pb);

    st->codec->sample_rate = avio_rb32(s->pb);

    if (st->codec->sample_rate <= 0) {

        av_log(s, AV_LOG_ERROR, "Bad sample rate\n");

        return AVERROR_INVALIDDATA;

    }

    samples = avio_rb32(s->pb);

    tmp = avio_rb32(s->pb);

    av_dlog(s, "packet num %d\n", tmp);

    tmp = avio_rb16(s->pb); // unknown

    av_dlog(s, "unknown %d\n", tmp);

    tmp  = avio_r8(s->pb); // major version

    tmp2 = avio_r8(s->pb); // minor version

    av_dlog(s, "version %d.%d\n", tmp, tmp2);

    tmp = avio_rb32(s->pb); // unknown

    av_dlog(s, "unknown %d\n", tmp);

    size = atom->size - 8 - (avio_tell(s->pb) - pos);

    if (size < 0)

        return -1;

    ret = av_get_packet(s->pb, pkt, size);

    if (ret < 0) {

        av_log(s, AV_LOG_ERROR, "error reading audio packet\n");

        return ret;

    }

    pkt->stream_index = 1;

    pkt->dts = dts;

    pkt->duration = av_rescale(samples, st->time_base.den, st->codec->sample_rate);

    av_dlog(s, "pkt dts %"PRId64" duration %d samples %d sample rate %d\n",

            pkt->dts, pkt->duration, samples, st->codec->sample_rate);

    return 0;

}


void hmp_hostfwd_add(Monitor *mon, const QDict *qdict)

{

    const char *redir_str;

    SlirpState *s;

    const char *arg1 = qdict_get_str(qdict, "arg1");

    const char *arg2 = qdict_get_try_str(qdict, "arg2");

    const char *arg3 = qdict_get_try_str(qdict, "arg3");

    if (arg2) {

        s = slirp_lookup(mon, arg1, arg2);

        redir_str = arg3;

    } else {

        s = slirp_lookup(mon, NULL, NULL);

        redir_str = arg1;

    }

    if (s) {

        slirp_hostfwd(s, redir_str, 0);

    }

}


void rgb16tobgr32(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint16_t *end;

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (uint16_t *)src;

	end = s + src_size/2;

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

		#ifdef WORDS_BIGENDIAN

			*d++ = 0;

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

			*d++ = (bgr&0x7E0)>>3;

			*d++ = (bgr&0xF800)>>8;

		#else

			*d++ = (bgr&0xF800)>>8;

			*d++ = (bgr&0x7E0)>>3;

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

			*d++ = 0;

		#endif

	}

}


static void ir2_decode_plane_inter(Ir2Context *ctx, int width, int height, uint8_t *dst, int stride,

                             const uint8_t *table)

{

    int j;

    int out = 0;

    int c;

    int t;

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

        out = 0;

        while (out < width){

            c = ir2_get_code(&ctx->gb);

            if(c > 0x80) { /* we have a skip */

                c -= 0x80;

                out += c * 2;

            } else { /* add two deltas from table */

                t = dst[out] + (table[c * 2] - 128);

                CLAMP_TO_BYTE(t);

                dst[out] = t;

                out++;

                t = dst[out] + (table[(c * 2) + 1] - 128);

                CLAMP_TO_BYTE(t);

                dst[out] = t;

                out++;

            }

        }

        dst += stride;

    }

}


static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt, int *serial)

{

    int got_picture;

    if (packet_queue_get(&is->videoq, pkt, 1, serial) < 0)

        return -1;

    if (pkt->data == flush_pkt.data) {

        avcodec_flush_buffers(is->video_st->codec);

        SDL_LockMutex(is->pictq_mutex);

        // Make sure there are no long delay timers (ideally we should just flush the queue but that's harder)

        while (is->pictq_size && !is->videoq.abort_request) {

            SDL_CondWait(is->pictq_cond, is->pictq_mutex);

        }

        is->video_current_pos = -1;

        is->frame_last_pts = AV_NOPTS_VALUE;

        is->frame_last_duration = 0;

        is->frame_timer = (double)av_gettime() / 1000000.0;

        is->frame_last_dropped_pts = AV_NOPTS_VALUE;

        SDL_UnlockMutex(is->pictq_mutex);

        return 0;

    }

    if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)

        return 0;

    if (got_picture) {

        int ret = 1;

        if (decoder_reorder_pts == -1) {

            *pts = av_frame_get_best_effort_timestamp(frame);

        } else if (decoder_reorder_pts) {

            *pts = frame->pkt_pts;

        } else {

            *pts = frame->pkt_dts;

        }

        if (*pts == AV_NOPTS_VALUE) {

            *pts = 0;

        }

        if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {

            SDL_LockMutex(is->pictq_mutex);

            if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {

                double clockdiff = get_video_clock(is) - get_master_clock(is);

                double dpts = av_q2d(is->video_st->time_base) * *pts;

                double ptsdiff = dpts - is->frame_last_pts;

                if (!isnan(clockdiff) && fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&

                     ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&

                     clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {

                    is->frame_last_dropped_pos = pkt->pos;

                    is->frame_last_dropped_pts = dpts;

                    is->frame_drops_early++;

                    ret = 0;

                }

            }

            SDL_UnlockMutex(is->pictq_mutex);

        }

        return ret;

    }

    return 0;

}


int ff_audio_rechunk_interleave(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush,

                        int (*get_packet)(AVFormatContext *, AVPacket *, AVPacket *, int),

                        int (*compare_ts)(AVFormatContext *, AVPacket *, AVPacket *))

{

    int i;

    if (pkt) {

        AVStream *st = s->streams[pkt->stream_index];

        AudioInterleaveContext *aic = st->priv_data;

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            unsigned new_size = av_fifo_size(aic->fifo) + pkt->size;

            if (new_size > aic->fifo_size) {

                if (av_fifo_realloc2(aic->fifo, new_size) < 0)

                    return -1;

                aic->fifo_size = new_size;

            }

            av_fifo_generic_write(aic->fifo, pkt->data, pkt->size, NULL);

        } else {

            // rewrite pts and dts to be decoded time line position

            pkt->pts = pkt->dts = aic->dts;

            aic->dts += pkt->duration;

            ff_interleave_add_packet(s, pkt, compare_ts);

        }

        pkt = NULL;

    }

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

        AVStream *st = s->streams[i];

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            AVPacket new_pkt;

            while (ff_interleave_new_audio_packet(s, &new_pkt, i, flush))

                ff_interleave_add_packet(s, &new_pkt, compare_ts);

        }

    }

    return get_packet(s, out, pkt, flush);

}


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

                                int *got_frame_ptr, GetBitContext *gb)

{

    AACContext *ac = avctx->priv_data;

    ChannelElement *che = NULL, *che_prev = NULL;

    enum RawDataBlockType elem_type, elem_type_prev = TYPE_END;

    int err, elem_id;

    int samples = 0, multiplier, audio_found = 0, pce_found = 0;

    if (show_bits(gb, 12) == 0xfff) {

        if (parse_adts_frame_header(ac, gb) < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error decoding AAC frame header.\n");

            err = -1;

            goto fail;

        }

        if (ac->oc[1].m4ac.sampling_index > 12) {

            av_log(ac->avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->oc[1].m4ac.sampling_index);

            err = -1;

            goto fail;

        }

    }

    ac->tags_mapped = 0;

    // parse

    while ((elem_type = get_bits(gb, 3)) != TYPE_END) {

        elem_id = get_bits(gb, 4);

        if (elem_type < TYPE_DSE) {

            if (!(che=get_che(ac, elem_type, elem_id))) {

                av_log(ac->avctx, AV_LOG_ERROR, "channel element %d.%d is not allocated\n",

                       elem_type, elem_id);

                err = -1;

                goto fail;

            }

            samples = 1024;

        }

        switch (elem_type) {

        case TYPE_SCE:

            err = decode_ics(ac, &che->ch[0], gb, 0, 0);

            audio_found = 1;

            break;

        case TYPE_CPE:

            err = decode_cpe(ac, gb, che);

            audio_found = 1;

            break;

        case TYPE_CCE:

            err = decode_cce(ac, gb, che);

            break;

        case TYPE_LFE:

            err = decode_ics(ac, &che->ch[0], gb, 0, 0);

            audio_found = 1;

            break;

        case TYPE_DSE:

            err = skip_data_stream_element(ac, gb);

            break;

        case TYPE_PCE: {

            uint8_t layout_map[MAX_ELEM_ID*4][3];

            int tags;

            push_output_configuration(ac);

            tags = decode_pce(avctx, &ac->oc[1].m4ac, layout_map, gb);

            if (tags < 0) {

                err = tags;

                break;

            }

            if (pce_found) {

                av_log(avctx, AV_LOG_ERROR,

                       "Not evaluating a further program_config_element as this construct is dubious at best.\n");

                pop_output_configuration(ac);

            } else {

                err = output_configure(ac, layout_map, tags, 0, OC_TRIAL_PCE);

                if (!err)

                    ac->oc[1].m4ac.chan_config = 0;

                pce_found = 1;

            }

            break;

        }

        case TYPE_FIL:

            if (elem_id == 15)

                elem_id += get_bits(gb, 8) - 1;

            if (get_bits_left(gb) < 8 * elem_id) {

                    av_log(avctx, AV_LOG_ERROR, overread_err);

                    err = -1;

                    goto fail;

            }

            while (elem_id > 0)

                elem_id -= decode_extension_payload(ac, gb, elem_id, che_prev, elem_type_prev);

            err = 0; /* FIXME */

            break;

        default:

            err = -1; /* should not happen, but keeps compiler happy */

            break;

        }

        che_prev       = che;

        elem_type_prev = elem_type;

        if (err)

            goto fail;

        if (get_bits_left(gb) < 3) {

            av_log(avctx, AV_LOG_ERROR, overread_err);

            err = -1;

            goto fail;

        }

    }

    spectral_to_sample(ac);

    multiplier = (ac->oc[1].m4ac.sbr == 1) ? ac->oc[1].m4ac.ext_sample_rate > ac->oc[1].m4ac.sample_rate : 0;

    samples <<= multiplier;

    if (samples) {

        /* get output buffer */

        ac->frame.nb_samples = samples;

        if ((err = avctx->get_buffer(avctx, &ac->frame)) < 0) {

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

            err = -1;

            goto fail;

        }

        if (avctx->sample_fmt == AV_SAMPLE_FMT_FLT)

            ac->fmt_conv.float_interleave((float *)ac->frame.data[0],

                                          (const float **)ac->output_data,

                                          samples, avctx->channels);

        else

            ac->fmt_conv.float_to_int16_interleave((int16_t *)ac->frame.data[0],

                                                   (const float **)ac->output_data,

                                                   samples, avctx->channels);

        *(AVFrame *)data = ac->frame;

    }

    *got_frame_ptr = !!samples;

    if (ac->oc[1].status && audio_found) {

        avctx->sample_rate = ac->oc[1].m4ac.sample_rate << multiplier;

        avctx->frame_size = samples;

        ac->oc[1].status = OC_LOCKED;

    }

    return 0;

fail:

    pop_output_configuration(ac);

    return err;

}


static void musicpal_init(MachineState *machine)

{

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    ARMCPU *cpu;

    qemu_irq pic[32];

    DeviceState *dev;

    DeviceState *i2c_dev;

    DeviceState *lcd_dev;

    DeviceState *key_dev;

    DeviceState *wm8750_dev;

    SysBusDevice *s;

    I2CBus *i2c;

    int i;

    unsigned long flash_size;

    DriveInfo *dinfo;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    if (!cpu_model) {

        cpu_model = "arm926";

    }

    cpu = ARM_CPU(cpu_generic_init(TYPE_ARM_CPU, cpu_model));

    if (!cpu) {

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

        exit(1);

    }

    /* For now we use a fixed - the original - RAM size */

    memory_region_allocate_system_memory(ram, NULL, "musicpal.ram",

                                         MP_RAM_DEFAULT_SIZE);

    memory_region_add_subregion(address_space_mem, 0, ram);

    memory_region_init_ram(sram, NULL, "musicpal.sram", MP_SRAM_SIZE,

                           &error_fatal);

    memory_region_add_subregion(address_space_mem, MP_SRAM_BASE, sram);

    dev = sysbus_create_simple(TYPE_MV88W8618_PIC, MP_PIC_BASE,

                               qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_IRQ));

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

        pic[i] = qdev_get_gpio_in(dev, i);

    }

    sysbus_create_varargs(TYPE_MV88W8618_PIT, MP_PIT_BASE, pic[MP_TIMER1_IRQ],

                          pic[MP_TIMER2_IRQ], pic[MP_TIMER3_IRQ],

                          pic[MP_TIMER4_IRQ], NULL);

    if (serial_hds[0]) {

        serial_mm_init(address_space_mem, MP_UART1_BASE, 2, pic[MP_UART1_IRQ],

                       1825000, serial_hds[0], DEVICE_NATIVE_ENDIAN);

    }

    if (serial_hds[1]) {

        serial_mm_init(address_space_mem, MP_UART2_BASE, 2, pic[MP_UART2_IRQ],

                       1825000, serial_hds[1], DEVICE_NATIVE_ENDIAN);

    }

    /* Register flash */

    dinfo = drive_get(IF_PFLASH, 0, 0);

    if (dinfo) {

        BlockBackend *blk = blk_by_legacy_dinfo(dinfo);

        flash_size = blk_getlength(blk);

        if (flash_size != 8*1024*1024 && flash_size != 16*1024*1024 &&

            flash_size != 32*1024*1024) {

            fprintf(stderr, "Invalid flash image size\n");

            exit(1);

        }

        /*

         * The original U-Boot accesses the flash at 0xFE000000 instead of

         * 0xFF800000 (if there is 8 MB flash). So remap flash access if the

         * image is smaller than 32 MB.

         */

#ifdef TARGET_WORDS_BIGENDIAN

        pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL,

                              "musicpal.flash", flash_size,

                              blk, 0x10000, (flash_size + 0xffff) >> 16,

                              MP_FLASH_SIZE_MAX / flash_size,

                              2, 0x00BF, 0x236D, 0x0000, 0x0000,

                              0x5555, 0x2AAA, 1);

#else

        pflash_cfi02_register(0x100000000ULL-MP_FLASH_SIZE_MAX, NULL,

                              "musicpal.flash", flash_size,

                              blk, 0x10000, (flash_size + 0xffff) >> 16,

                              MP_FLASH_SIZE_MAX / flash_size,

                              2, 0x00BF, 0x236D, 0x0000, 0x0000,

                              0x5555, 0x2AAA, 0);

#endif

    }

    sysbus_create_simple(TYPE_MV88W8618_FLASHCFG, MP_FLASHCFG_BASE, NULL);

    qemu_check_nic_model(&nd_table[0], "mv88w8618");

    dev = qdev_create(NULL, TYPE_MV88W8618_ETH);

    qdev_set_nic_properties(dev, &nd_table[0]);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, MP_ETH_BASE);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[MP_ETH_IRQ]);

    sysbus_create_simple("mv88w8618_wlan", MP_WLAN_BASE, NULL);

    sysbus_create_simple(TYPE_MUSICPAL_MISC, MP_MISC_BASE, NULL);

    dev = sysbus_create_simple(TYPE_MUSICPAL_GPIO, MP_GPIO_BASE,

                               pic[MP_GPIO_IRQ]);

    i2c_dev = sysbus_create_simple("gpio_i2c", -1, NULL);

    i2c = (I2CBus *)qdev_get_child_bus(i2c_dev, "i2c");

    lcd_dev = sysbus_create_simple(TYPE_MUSICPAL_LCD, MP_LCD_BASE, NULL);

    key_dev = sysbus_create_simple(TYPE_MUSICPAL_KEY, -1, NULL);

    /* I2C read data */

    qdev_connect_gpio_out(i2c_dev, 0,

                          qdev_get_gpio_in(dev, MP_GPIO_I2C_DATA_BIT));

    /* I2C data */

    qdev_connect_gpio_out(dev, 3, qdev_get_gpio_in(i2c_dev, 0));

    /* I2C clock */

    qdev_connect_gpio_out(dev, 4, qdev_get_gpio_in(i2c_dev, 1));

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

        qdev_connect_gpio_out(dev, i, qdev_get_gpio_in(lcd_dev, i));

    }

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

        qdev_connect_gpio_out(key_dev, i, qdev_get_gpio_in(dev, i + 8));

    }

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

        qdev_connect_gpio_out(key_dev, i, qdev_get_gpio_in(dev, i + 15));

    }

    wm8750_dev = i2c_create_slave(i2c, "wm8750", MP_WM_ADDR);

    dev = qdev_create(NULL, "mv88w8618_audio");

    s = SYS_BUS_DEVICE(dev);

    qdev_prop_set_ptr(dev, "wm8750", wm8750_dev);

    qdev_init_nofail(dev);

    sysbus_mmio_map(s, 0, MP_AUDIO_BASE);

    sysbus_connect_irq(s, 0, pic[MP_AUDIO_IRQ]);

    musicpal_binfo.ram_size = MP_RAM_DEFAULT_SIZE;

    musicpal_binfo.kernel_filename = kernel_filename;

    musicpal_binfo.kernel_cmdline = kernel_cmdline;

    musicpal_binfo.initrd_filename = initrd_filename;

    arm_load_kernel(cpu, &musicpal_binfo);

}


void helper_fxrstor(CPUX86State *env, target_ulong ptr, int data64)

{

    int i, fpus, fptag, nb_xmm_regs;

    floatx80 tmp;

    target_ulong addr;

    /* The operand must be 16 byte aligned */

    if (ptr & 0xf) {

        raise_exception(env, EXCP0D_GPF);

    }

    env->fpuc = cpu_lduw_data(env, ptr);

    fpus = cpu_lduw_data(env, ptr + 2);

    fptag = cpu_lduw_data(env, ptr + 4);

    env->fpstt = (fpus >> 11) & 7;

    env->fpus = fpus & ~0x3800;

    fptag ^= 0xff;

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

        env->fptags[i] = ((fptag >> i) & 1);

    }

    addr = ptr + 0x20;

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

        tmp = helper_fldt(env, addr);

        ST(i) = tmp;

        addr += 16;

    }

    if (env->cr[4] & CR4_OSFXSR_MASK) {

        /* XXX: finish it */

        env->mxcsr = cpu_ldl_data(env, ptr + 0x18);

        /* cpu_ldl_data(env, ptr + 0x1c); */

        if (env->hflags & HF_CS64_MASK) {

            nb_xmm_regs = 16;

        } else {

            nb_xmm_regs = 8;

        }

        addr = ptr + 0xa0;

        /* Fast FXRESTORE leaves out the XMM registers */

        if (!(env->efer & MSR_EFER_FFXSR)

            || (env->hflags & HF_CPL_MASK)

            || !(env->hflags & HF_LMA_MASK)) {

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

                env->xmm_regs[i].XMM_Q(0) = cpu_ldq_data(env, addr);

                env->xmm_regs[i].XMM_Q(1) = cpu_ldq_data(env, addr + 8);

                addr += 16;

            }

        }

    }

}


static int fill_default_ref_list(H264Context *h){

    MpegEncContext * const s = &h->s;

    int i;

    int smallest_poc_greater_than_current = -1;

    Picture sorted_short_ref[32];

    if(h->slice_type==B_TYPE){

        int out_i;

        int limit= -1;

        /* sort frame according to poc in B slice */

        for(out_i=0; out_i<h->short_ref_count; out_i++){

            int best_i=-1;

            int best_poc=INT_MAX;

            for(i=0; i<h->short_ref_count; i++){

                const int poc= h->short_ref[i]->poc;

                if(poc > limit && poc < best_poc){

                    best_poc= poc;

                    best_i= i;

                }

            }

            assert(best_i != -1);

            limit= best_poc;

            sorted_short_ref[out_i]= *h->short_ref[best_i];

            tprintf("sorted poc: %d->%d poc:%d fn:%d\n", best_i, out_i, sorted_short_ref[out_i].poc, sorted_short_ref[out_i].frame_num);

            if (-1 == smallest_poc_greater_than_current) {

                if (h->short_ref[best_i]->poc >= s->current_picture_ptr->poc) {

                    smallest_poc_greater_than_current = out_i;

                }

            }

        }

    }

    if(s->picture_structure == PICT_FRAME){

        if(h->slice_type==B_TYPE){

            int list;

            tprintf("current poc: %d, smallest_poc_greater_than_current: %d\n", s->current_picture_ptr->poc, smallest_poc_greater_than_current);

            // find the largest poc

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

                int index = 0;

                int j= -99;

                int step= list ? -1 : 1;

                for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++, j+=step) {

                    while(j<0 || j>= h->short_ref_count){

                        if(j != -99 && step == (list ? -1 : 1))

                            return -1;

                        step = -step;

                        j= smallest_poc_greater_than_current + (step>>1);

                    }

                    if(sorted_short_ref[j].reference != 3) continue;

                    h->default_ref_list[list][index  ]= sorted_short_ref[j];

                    h->default_ref_list[list][index++].pic_id= sorted_short_ref[j].frame_num;

                }

                for(i = 0; i < 16 && index < h->ref_count[ list ]; i++){

                    if(h->long_ref[i] == NULL) continue;

                    if(h->long_ref[i]->reference != 3) continue;

                    h->default_ref_list[ list ][index  ]= *h->long_ref[i];

                    h->default_ref_list[ list ][index++].pic_id= i;;

                }

                if(list && (smallest_poc_greater_than_current<=0 || smallest_poc_greater_than_current>=h->short_ref_count) && (1 < index)){

                    // swap the two first elements of L1 when

                    // L0 and L1 are identical

                    Picture temp= h->default_ref_list[1][0];

                    h->default_ref_list[1][0] = h->default_ref_list[1][1];

                    h->default_ref_list[1][1] = temp;

                }

                if(index < h->ref_count[ list ])

                    memset(&h->default_ref_list[list][index], 0, sizeof(Picture)*(h->ref_count[ list ] - index));

            }

        }else{

            int index=0;

            for(i=0; i<h->short_ref_count; i++){

                if(h->short_ref[i]->reference != 3) continue; //FIXME refernce field shit

                h->default_ref_list[0][index  ]= *h->short_ref[i];

                h->default_ref_list[0][index++].pic_id= h->short_ref[i]->frame_num;

            }

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

                if(h->long_ref[i] == NULL) continue;

                if(h->long_ref[i]->reference != 3) continue;

                h->default_ref_list[0][index  ]= *h->long_ref[i];

                h->default_ref_list[0][index++].pic_id= i;;

            }

            if(index < h->ref_count[0])

                memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index));

        }

    }else{ //FIELD

        if(h->slice_type==B_TYPE){

        }else{

            //FIXME second field balh

        }

    }

#ifdef TRACE

    for (i=0; i<h->ref_count[0]; i++) {

        tprintf("List0: %s fn:%d 0x%p\n", (h->default_ref_list[0][i].long_ref ? "LT" : "ST"), h->default_ref_list[0][i].pic_id, h->default_ref_list[0][i].data[0]);

    }

    if(h->slice_type==B_TYPE){

        for (i=0; i<h->ref_count[1]; i++) {

            tprintf("List1: %s fn:%d 0x%p\n", (h->default_ref_list[1][i].long_ref ? "LT" : "ST"), h->default_ref_list[1][i].pic_id, h->default_ref_list[0][i].data[0]);

        }

    }

#endif

    return 0;

}


target_ulong helper_rdhwr_cc(CPUMIPSState *env)

{

    check_hwrena(env, 2);

#ifdef CONFIG_USER_ONLY

    return env->CP0_Count;

#else

    return (int32_t)cpu_mips_get_count(env);

#endif

}


void helper_rfci(CPUPPCState *env)

{

    do_rfi(env, env->spr[SPR_BOOKE_CSRR0], SPR_BOOKE_CSRR1,

           ~((target_ulong)0x3FFF0000), 0);

}


static void gen_nabso(DisasContext *ctx)

{

    int l1 = gen_new_label();

    int l2 = gen_new_label();

    tcg_gen_brcondi_tl(TCG_COND_GT, cpu_gpr[rA(ctx->opcode)], 0, l1);

    tcg_gen_mov_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_neg_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    gen_set_label(l2);

    /* nabs never overflows */

    tcg_gen_movi_tl(cpu_ov, 0);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);

}


static coroutine_fn int cow_co_read(BlockDriverState *bs, int64_t sector_num,

                                    uint8_t *buf, int nb_sectors)

{

    int ret;

    BDRVCowState *s = bs->opaque;

    qemu_co_mutex_lock(&s->lock);

    ret = cow_read(bs, sector_num, buf, nb_sectors);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


static inline uint32_t ucf64_stoi(float32 s)

{

    union {

        uint32_t i;

        float32 s;

    } v;

    v.s = s;

    return v.i;

}


static void  ahci_port_write(AHCIState *s, int port, int offset, uint32_t val)

{

    AHCIPortRegs *pr = &s->dev[port].port_regs;

    DPRINTF(port, "offset: 0x%x val: 0x%x\n", offset, val);

    switch (offset) {

        case PORT_LST_ADDR:

            pr->lst_addr = val;

            break;

        case PORT_LST_ADDR_HI:

            pr->lst_addr_hi = val;

            break;

        case PORT_FIS_ADDR:

            pr->fis_addr = val;

            break;

        case PORT_FIS_ADDR_HI:

            pr->fis_addr_hi = val;

            break;

        case PORT_IRQ_STAT:

            pr->irq_stat &= ~val;

            ahci_check_irq(s);

            break;

        case PORT_IRQ_MASK:

            pr->irq_mask = val & 0xfdc000ff;

            ahci_check_irq(s);

            break;

        case PORT_CMD:

            pr->cmd = val & ~(PORT_CMD_LIST_ON | PORT_CMD_FIS_ON);

            if (pr->cmd & PORT_CMD_START) {

                if (ahci_map_clb_address(&s->dev[port])) {

                    pr->cmd |= PORT_CMD_LIST_ON;

                } else {

                    error_report("AHCI: Failed to start DMA engine: "

                                 "bad command list buffer address");

                }

            }

            if (pr->cmd & PORT_CMD_FIS_RX) {

                if (ahci_map_fis_address(&s->dev[port])) {

                    pr->cmd |= PORT_CMD_FIS_ON;

                } else {

                    error_report("AHCI: Failed to start FIS receive engine: "

                                 "bad FIS receive buffer address");

                }

            }

            /* XXX usually the FIS would be pending on the bus here and

                   issuing deferred until the OS enables FIS receival.

                   Instead, we only submit it once - which works in most

                   cases, but is a hack. */

            if ((pr->cmd & PORT_CMD_FIS_ON) &&

                !s->dev[port].init_d2h_sent) {

                ahci_init_d2h(&s->dev[port]);

                s->dev[port].init_d2h_sent = true;

            }

            check_cmd(s, port);

            break;

        case PORT_TFDATA:

            /* Read Only. */

            break;

        case PORT_SIG:

            /* Read Only */

            break;

        case PORT_SCR_STAT:

            /* Read Only */

            break;

        case PORT_SCR_CTL:

            if (((pr->scr_ctl & AHCI_SCR_SCTL_DET) == 1) &&

                ((val & AHCI_SCR_SCTL_DET) == 0)) {

                ahci_reset_port(s, port);

            }

            pr->scr_ctl = val;

            break;

        case PORT_SCR_ERR:

            pr->scr_err &= ~val;

            break;

        case PORT_SCR_ACT:

            /* RW1 */

            pr->scr_act |= val;

            break;

        case PORT_CMD_ISSUE:

            pr->cmd_issue |= val;

            check_cmd(s, port);

            break;

        default:

            break;

    }

}


static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,

                               int64_t count, int64_t *total)

{

    int ret;

    if (count >> 9 > INT_MAX) {

        return -ERANGE;

    }

    ret = blk_write_compressed(blk, offset >> 9, (uint8_t *)buf, count >> 9);

    if (ret < 0) {

        return ret;

    }

    *total = count;

    return 1;

}


void qdict_put_obj(QDict *qdict, const char *key, QObject *value)

{

    unsigned int hash;

    QDictEntry *entry;

    hash = tdb_hash(key) % QDICT_HASH_SIZE;

    entry = qdict_find(qdict, key, hash);

    if (entry) {

        /* replace key's value */

        qobject_decref(entry->value);

        entry->value = value;

    } else {

        /* allocate a new entry */

        entry = alloc_entry(key, value);

        LIST_INSERT_HEAD(&qdict->table[hash], entry, next);

    }

    qdict->size++;

}


static void trigger_page_fault(CPUS390XState *env, target_ulong vaddr,

                               uint32_t type, uint64_t asc, int rw, bool exc)

{

    int ilen = ILEN_LATER;

    uint64_t tec;

    tec = vaddr | (rw == MMU_DATA_STORE ? FS_WRITE : FS_READ) | asc >> 46;

    DPRINTF("%s: trans_exc_code=%016" PRIx64 "\n", __func__, tec);

    if (!exc) {

        return;

    }

    /* Code accesses have an undefined ilc.  */

    if (rw == MMU_INST_FETCH) {

        ilen = 2;

    }

    trigger_access_exception(env, type, ilen, tec);

}


static av_cold int read_specific_config(ALSDecContext *ctx)

{

    GetBitContext gb;

    uint64_t ht_size;

    int i, config_offset;

    MPEG4AudioConfig m4ac;

    ALSSpecificConfig *sconf = &ctx->sconf;

    AVCodecContext *avctx    = ctx->avctx;

    uint32_t als_id, header_size, trailer_size;

    init_get_bits(&gb, avctx->extradata, avctx->extradata_size * 8);

    config_offset = avpriv_mpeg4audio_get_config(&m4ac, avctx->extradata,

                                                 avctx->extradata_size * 8, 1);

    if (config_offset < 0)

        return -1;

    skip_bits_long(&gb, config_offset);

    if (get_bits_left(&gb) < (30 << 3))

        return -1;

    // read the fixed items

    als_id                      = get_bits_long(&gb, 32);

    avctx->sample_rate          = m4ac.sample_rate;

    skip_bits_long(&gb, 32); // sample rate already known

    sconf->samples              = get_bits_long(&gb, 32);

    avctx->channels             = m4ac.channels;

    skip_bits(&gb, 16);      // number of channels already knwon

    skip_bits(&gb, 3);       // skip file_type

    sconf->resolution           = get_bits(&gb, 3);

    sconf->floating             = get_bits1(&gb);

    sconf->msb_first            = get_bits1(&gb);

    sconf->frame_length         = get_bits(&gb, 16) + 1;

    sconf->ra_distance          = get_bits(&gb, 8);

    sconf->ra_flag              = get_bits(&gb, 2);

    sconf->adapt_order          = get_bits1(&gb);

    sconf->coef_table           = get_bits(&gb, 2);

    sconf->long_term_prediction = get_bits1(&gb);

    sconf->max_order            = get_bits(&gb, 10);

    sconf->block_switching      = get_bits(&gb, 2);

    sconf->bgmc                 = get_bits1(&gb);

    sconf->sb_part              = get_bits1(&gb);

    sconf->joint_stereo         = get_bits1(&gb);

    sconf->mc_coding            = get_bits1(&gb);

    sconf->chan_config          = get_bits1(&gb);

    sconf->chan_sort            = get_bits1(&gb);

    sconf->crc_enabled          = get_bits1(&gb);

    sconf->rlslms               = get_bits1(&gb);

    skip_bits(&gb, 5);       // skip 5 reserved bits

    skip_bits1(&gb);         // skip aux_data_enabled

    // check for ALSSpecificConfig struct

    if (als_id != MKBETAG('A','L','S','\0'))

        return -1;

    ctx->cur_frame_length = sconf->frame_length;

    // read channel config

    if (sconf->chan_config)

        sconf->chan_config_info = get_bits(&gb, 16);

    // TODO: use this to set avctx->channel_layout

    // read channel sorting

    if (sconf->chan_sort && avctx->channels > 1) {

        int chan_pos_bits = av_ceil_log2(avctx->channels);

        int bits_needed  = avctx->channels * chan_pos_bits + 7;

        if (get_bits_left(&gb) < bits_needed)

            return -1;

        if (!(sconf->chan_pos = av_malloc(avctx->channels * sizeof(*sconf->chan_pos))))

            return AVERROR(ENOMEM);

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

            sconf->chan_pos[i] = get_bits(&gb, chan_pos_bits);

            if (sconf->chan_pos[i] >= avctx->channels) {

                av_log(avctx, AV_LOG_WARNING, "Invalid original channel position.\n");

                sconf->chan_sort = 0;

                break;

            }

        }

        align_get_bits(&gb);

    } else {

        sconf->chan_sort = 0;

    }

    // read fixed header and trailer sizes,

    // if size = 0xFFFFFFFF then there is no data field!

    if (get_bits_left(&gb) < 64)

        return -1;

    header_size  = get_bits_long(&gb, 32);

    trailer_size = get_bits_long(&gb, 32);

    if (header_size  == 0xFFFFFFFF)

        header_size  = 0;

    if (trailer_size == 0xFFFFFFFF)

        trailer_size = 0;

    ht_size = ((int64_t)(header_size) + (int64_t)(trailer_size)) << 3;

    // skip the header and trailer data

    if (get_bits_left(&gb) < ht_size)

        return -1;

    if (ht_size > INT32_MAX)

        return -1;

    skip_bits_long(&gb, ht_size);

    // initialize CRC calculation

    if (sconf->crc_enabled) {

        if (get_bits_left(&gb) < 32)

            return -1;

        if (avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_CAREFUL)) {

            ctx->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);

            ctx->crc       = 0xFFFFFFFF;

            ctx->crc_org   = ~get_bits_long(&gb, 32);

        } else

            skip_bits_long(&gb, 32);

    }

    // no need to read the rest of ALSSpecificConfig (ra_unit_size & aux data)

    dprint_specific_config(ctx);

    return 0;

}


int socket_listen(SocketAddressLegacy *addr, Error **errp)

{

    int fd;

    switch (addr->type) {

    case SOCKET_ADDRESS_LEGACY_KIND_INET:

        fd = inet_listen_saddr(addr->u.inet.data, 0, false, errp);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_UNIX:

        fd = unix_listen_saddr(addr->u.q_unix.data, false, errp);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_FD:

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

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:

        fd = vsock_listen_saddr(addr->u.vsock.data, errp);

        break;

    default:

        abort();

    }

    return fd;

}


static long do_sigreturn_v1(CPUARMState *env)

{

    abi_ulong frame_addr;

    struct sigframe_v1 *frame = NULL;

    target_sigset_t set;

    sigset_t host_set;

    int i;

    /*

     * Since we stacked the signal on a 64-bit boundary,

     * then 'sp' should be word aligned here.  If it's

     * not, then the user is trying to mess with us.

     */

    frame_addr = env->regs[13];

    trace_user_do_sigreturn(env, frame_addr);

    if (frame_addr & 7) {

        goto badframe;

    }

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    __get_user(set.sig[0], &frame->sc.oldmask);

    for(i = 1; i < TARGET_NSIG_WORDS; i++) {

        __get_user(set.sig[i], &frame->extramask[i - 1]);

    }

    target_to_host_sigset_internal(&host_set, &set);

    do_sigprocmask(SIG_SETMASK, &host_set, NULL);

    if (restore_sigcontext(env, &frame->sc)) {

        goto badframe;

    }

#if 0

    /* Send SIGTRAP if we're single-stepping */

    if (ptrace_cancel_bpt(current))

        send_sig(SIGTRAP, current, 1);

#endif

    unlock_user_struct(frame, frame_addr, 0);

    return env->regs[0];

badframe:

    force_sig(TARGET_SIGSEGV /* , current */);

    return 0;

}


static int usbnet_can_receive(void *opaque)

{

    USBNetState *s = opaque;

    if (s->rndis && !s->rndis_state == RNDIS_DATA_INITIALIZED)

        return 1;

    return !s->in_len;

}


static int rtc_load(QEMUFile *f, void *opaque, int version_id)

{

    RTCState *s = opaque;

    if (version_id != 1)

        return -EINVAL;

    qemu_get_buffer(f, s->cmos_data, 128);

    qemu_get_8s(f, &s->cmos_index);

    s->current_tm.tm_sec=qemu_get_be32(f);

    s->current_tm.tm_min=qemu_get_be32(f);

    s->current_tm.tm_hour=qemu_get_be32(f);

    s->current_tm.tm_wday=qemu_get_be32(f);

    s->current_tm.tm_mday=qemu_get_be32(f);

    s->current_tm.tm_mon=qemu_get_be32(f);

    s->current_tm.tm_year=qemu_get_be32(f);

    qemu_get_timer(f, s->periodic_timer);

    s->next_periodic_time=qemu_get_be64(f);

    s->next_second_time=qemu_get_be64(f);

    qemu_get_timer(f, s->second_timer);

    qemu_get_timer(f, s->second_timer2);

    return 0;

}


void vnc_display_close(DisplayState *ds)

{

    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;

    if (!vs)

        return;

    if (vs->display) {

	qemu_free(vs->display);

	vs->display = NULL;

    }

    if (vs->lsock != -1) {

	qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);

	close(vs->lsock);

	vs->lsock = -1;

    }

    vs->auth = VNC_AUTH_INVALID;

#ifdef CONFIG_VNC_TLS

    vs->subauth = VNC_AUTH_INVALID;

    vs->x509verify = 0;

#endif

}


static void tmu2_start(MilkymistTMU2State *s)

{

    int pbuffer_attrib[6] = {

        GLX_PBUFFER_WIDTH,

        0,

        GLX_PBUFFER_HEIGHT,

        0,

        GLX_PRESERVED_CONTENTS,

        True

    };

    GLXPbuffer pbuffer;

    GLuint texture;

    void *fb;

    target_phys_addr_t fb_len;

    void *mesh;

    target_phys_addr_t mesh_len;

    float m;

    trace_milkymist_tmu2_start();

    /* Create and set up a suitable OpenGL context */

    pbuffer_attrib[1] = s->regs[R_DSTHRES];

    pbuffer_attrib[3] = s->regs[R_DSTVRES];

    pbuffer = glXCreatePbuffer(s->dpy, s->glx_fb_config, pbuffer_attrib);

    glXMakeContextCurrent(s->dpy, pbuffer, pbuffer, s->glx_context);

    /* Fixup endianness. TODO: would it work on BE hosts? */

    glPixelStorei(GL_UNPACK_SWAP_BYTES, 1);

    glPixelStorei(GL_PACK_SWAP_BYTES, 1);

    /* Row alignment */

    glPixelStorei(GL_UNPACK_ALIGNMENT, 2);

    glPixelStorei(GL_PACK_ALIGNMENT, 2);

    /* Read the QEMU source framebuffer into an OpenGL texture */

    glGenTextures(1, &texture);

    glBindTexture(GL_TEXTURE_2D, texture);

    fb_len = 2*s->regs[R_TEXHRES]*s->regs[R_TEXVRES];

    fb = cpu_physical_memory_map(s->regs[R_TEXFBUF], &fb_len, 0);

    if (fb == NULL) {

        glDeleteTextures(1, &texture);

        glXMakeContextCurrent(s->dpy, None, None, NULL);

        glXDestroyPbuffer(s->dpy, pbuffer);

        return;

    }

    glTexImage2D(GL_TEXTURE_2D, 0, 3, s->regs[R_TEXHRES], s->regs[R_TEXVRES],

            0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, fb);

    cpu_physical_memory_unmap(fb, fb_len, 0, fb_len);

    /* Set up texturing options */

    /* WARNING:

     * Many cases of TMU2 masking are not supported by OpenGL.

     * We only implement the most common ones:

     *  - full bilinear filtering vs. nearest texel

     *  - texture clamping vs. texture wrapping

     */

    if ((s->regs[R_TEXHMASK] & 0x3f) > 0x20) {

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    } else {

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    }

    if ((s->regs[R_TEXHMASK] >> 6) & s->regs[R_TEXHRES]) {

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);

    } else {

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);

    }

    if ((s->regs[R_TEXVMASK] >> 6) & s->regs[R_TEXVRES]) {

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

    } else {

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    }

    /* Translucency and decay */

    glEnable(GL_BLEND);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    m = (float)(s->regs[R_BRIGHTNESS] + 1) / 64.0f;

    glColor4f(m, m, m, (float)(s->regs[R_ALPHA] + 1) / 64.0f);

    /* Read the QEMU dest. framebuffer into the OpenGL framebuffer */

    fb_len = 2 * s->regs[R_DSTHRES] * s->regs[R_DSTVRES];

    fb = cpu_physical_memory_map(s->regs[R_DSTFBUF], &fb_len, 0);

    if (fb == NULL) {

        glDeleteTextures(1, &texture);

        glXMakeContextCurrent(s->dpy, None, None, NULL);

        glXDestroyPbuffer(s->dpy, pbuffer);

        return;

    }

    glDrawPixels(s->regs[R_DSTHRES], s->regs[R_DSTVRES], GL_RGB,

            GL_UNSIGNED_SHORT_5_6_5, fb);

    cpu_physical_memory_unmap(fb, fb_len, 0, fb_len);

    glViewport(0, 0, s->regs[R_DSTHRES], s->regs[R_DSTVRES]);

    glMatrixMode(GL_PROJECTION);

    glLoadIdentity();

    glOrtho(0.0, s->regs[R_DSTHRES], 0.0, s->regs[R_DSTVRES], -1.0, 1.0);

    glMatrixMode(GL_MODELVIEW);

    /* Map the texture */

    mesh_len = MESH_MAXSIZE*MESH_MAXSIZE*sizeof(struct vertex);

    mesh = cpu_physical_memory_map(s->regs[R_VERTICESADDR], &mesh_len, 0);

    if (mesh == NULL) {

        glDeleteTextures(1, &texture);

        glXMakeContextCurrent(s->dpy, None, None, NULL);

        glXDestroyPbuffer(s->dpy, pbuffer);

        return;

    }

    tmu2_gl_map((struct vertex *)mesh,

        s->regs[R_TEXHRES], s->regs[R_TEXVRES],

        s->regs[R_HMESHLAST], s->regs[R_VMESHLAST],

        s->regs[R_DSTHOFFSET], s->regs[R_DSTVOFFSET],

        s->regs[R_DSTSQUAREW], s->regs[R_DSTSQUAREH]);

    cpu_physical_memory_unmap(mesh, mesh_len, 0, mesh_len);

    /* Write back the OpenGL framebuffer to the QEMU framebuffer */

    fb_len = 2 * s->regs[R_DSTHRES] * s->regs[R_DSTVRES];

    fb = cpu_physical_memory_map(s->regs[R_DSTFBUF], &fb_len, 1);

    if (fb == NULL) {

        glDeleteTextures(1, &texture);

        glXMakeContextCurrent(s->dpy, None, None, NULL);

        glXDestroyPbuffer(s->dpy, pbuffer);

        return;

    }

    glReadPixels(0, 0, s->regs[R_DSTHRES], s->regs[R_DSTVRES], GL_RGB,

            GL_UNSIGNED_SHORT_5_6_5, fb);

    cpu_physical_memory_unmap(fb, fb_len, 1, fb_len);

    /* Free OpenGL allocs */

    glDeleteTextures(1, &texture);

    glXMakeContextCurrent(s->dpy, None, None, NULL);

    glXDestroyPbuffer(s->dpy, pbuffer);

    s->regs[R_CTL] &= ~CTL_START_BUSY;

    trace_milkymist_tmu2_pulse_irq();

    qemu_irq_pulse(s->irq);

}


static int colo_packet_compare_icmp(Packet *spkt, Packet *ppkt)

{

    trace_colo_compare_main("compare icmp");

    if (colo_packet_compare_common(ppkt, spkt)) {

        trace_colo_compare_icmp_miscompare("primary pkt size",

                                           ppkt->size);

        qemu_hexdump((char *)ppkt->data, stderr, "colo-compare",

                     ppkt->size);

        trace_colo_compare_icmp_miscompare("Secondary pkt size",

                                           spkt->size);

        qemu_hexdump((char *)spkt->data, stderr, "colo-compare",

                     spkt->size);

        return -1;

    } else {

        return 0;

    }

}


static void scsi_destroy(SCSIDevice *dev)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);

    scsi_disk_purge_requests(s);

    blockdev_mark_auto_del(s->qdev.conf.dinfo->bdrv);

}


void HELPER(yield)(CPUARMState *env)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    /* When running in MTTCG we don't generate jumps to the yield and

     * WFE helpers as it won't affect the scheduling of other vCPUs.

     * If we wanted to more completely model WFE/SEV so we don't busy

     * spin unnecessarily we would need to do something more involved.

     */

    g_assert(!parallel_cpus);

    /* This is a non-trappable hint instruction that generally indicates

     * that the guest is currently busy-looping. Yield control back to the

     * top level loop so that a more deserving VCPU has a chance to run.

     */

    cs->exception_index = EXCP_YIELD;

    cpu_loop_exit(cs);

}


static void gic_init(gic_state *s, int num_cpu, int num_irq)

#else

static void gic_init(gic_state *s, int num_irq)

#endif

{

    int i;

#if NCPU > 1

    s->num_cpu = num_cpu;

    if (s->num_cpu > NCPU) {

        hw_error("requested %u CPUs exceeds GIC maximum %d\n",

                 num_cpu, NCPU);

    }

#endif

    s->num_irq = num_irq + GIC_BASE_IRQ;

    if (s->num_irq > GIC_MAXIRQ) {

        hw_error("requested %u interrupt lines exceeds GIC maximum %d\n",

                 num_irq, GIC_MAXIRQ);

    }

    /* ITLinesNumber is represented as (N / 32) - 1 (see

     * gic_dist_readb) so this is an implementation imposed

     * restriction, not an architectural one:

     */

    if (s->num_irq < 32 || (s->num_irq % 32)) {

        hw_error("%d interrupt lines unsupported: not divisible by 32\n",

                 num_irq);

    }

    qdev_init_gpio_in(&s->busdev.qdev, gic_set_irq, s->num_irq - GIC_INTERNAL);

    for (i = 0; i < NUM_CPU(s); i++) {

        sysbus_init_irq(&s->busdev, &s->parent_irq[i]);

    }

    memory_region_init_io(&s->iomem, &gic_dist_ops, s, "gic_dist", 0x1000);

#ifndef NVIC

    /* Memory regions for the CPU interfaces (NVIC doesn't have these):

     * a region for "CPU interface for this core", then a region for

     * "CPU interface for core 0", "for core 1", ...

     * NB that the memory region size of 0x100 applies for the 11MPCore

     * and also cores following the GIC v1 spec (ie A9).

     * GIC v2 defines a larger memory region (0x1000) so this will need

     * to be extended when we implement A15.

     */

    memory_region_init_io(&s->cpuiomem[0], &gic_thiscpu_ops, s,

                          "gic_cpu", 0x100);

    for (i = 0; i < NUM_CPU(s); i++) {

        s->backref[i] = s;

        memory_region_init_io(&s->cpuiomem[i+1], &gic_cpu_ops, &s->backref[i],

                              "gic_cpu", 0x100);

    }

#endif

    gic_reset(s);

    register_savevm(NULL, "arm_gic", -1, 2, gic_save, gic_load, s);

}


static int dv_read_timecode(AVFormatContext *s) {

    int ret;

    char timecode[AV_TIMECODE_STR_SIZE];

    int64_t pos = avio_tell(s->pb);

    // Read 3 DIF blocks: Header block and 2 Subcode blocks.

    int partial_frame_size = 3 * 80;

    uint8_t *partial_frame = av_mallocz(sizeof(*partial_frame) *

                                        partial_frame_size);

    RawDVContext *c = s->priv_data;

    ret = avio_read(s->pb, partial_frame, partial_frame_size);

    if (ret < 0)

        goto finish;

    if (ret < partial_frame_size) {

        ret = -1;

        goto finish;

    }

    ret = dv_extract_timecode(c->dv_demux, partial_frame, timecode);

    if (ret)

        av_dict_set(&s->metadata, "timecode", timecode, 0);

    else if (ret < 0)

        av_log(s, AV_LOG_ERROR, "Detected timecode is invalid\n");

finish:

    av_free(partial_frame);

    avio_seek(s->pb, pos, SEEK_SET);

    return ret;

}


static void vt82c686b_init_ports(PCIIDEState *d) {

    int i;

    struct {

        int iobase;

        int iobase2;

        int isairq;

    } port_info[] = {

        {0x1f0, 0x3f6, 14},

        {0x170, 0x376, 15},

    };

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

        ide_bus_new(&d->bus[i], &d->dev.qdev, i);

        ide_init_ioport(&d->bus[i], port_info[i].iobase, port_info[i].iobase2);

        ide_init2(&d->bus[i], isa_reserve_irq(port_info[i].isairq));

        bmdma_init(&d->bus[i], &d->bmdma[i]);

        d->bmdma[i].bus = &d->bus[i];

        qemu_add_vm_change_state_handler(d->bus[i].dma->ops->restart_cb,

                                         &d->bmdma[i].dma);

    }

}


static void gen_tlbsx_40x(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    t0 = tcg_temp_new();

    gen_addr_reg_index(ctx, t0);

    gen_helper_4xx_tlbsx(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

    if (Rc(ctx->opcode)) {

        int l1 = gen_new_label();

        tcg_gen_trunc_tl_i32(cpu_crf[0], cpu_so);

        tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_gpr[rD(ctx->opcode)], -1, l1);

        tcg_gen_ori_i32(cpu_crf[0], cpu_crf[0], 0x02);

        gen_set_label(l1);

    }

#endif

}


static unsigned int PerformComparison(const unsigned int opcode)

{

   FPA11 *fpa11 = GET_FPA11();

   unsigned int Fn, Fm;

   floatx80 rFn, rFm;

   int e_flag = opcode & 0x400000;	/* 1 if CxFE */

   int n_flag = opcode & 0x200000;	/* 1 if CNxx */

   unsigned int flags = 0;

   //printk("PerformComparison(0x%08x)\n",opcode);

   Fn = getFn(opcode);

   Fm = getFm(opcode);

   /* Check for unordered condition and convert all operands to 80-bit

      format.

      ?? Might be some mileage in avoiding this conversion if possible.

      Eg, if both operands are 32-bit, detect this and do a 32-bit

      comparison (cheaper than an 80-bit one).  */

   switch (fpa11->fType[Fn])

   {

      case typeSingle:

        //printk("single.\n");

	if (float32_is_nan(fpa11->fpreg[Fn].fSingle))

	   goto unordered;

        rFn = float32_to_floatx80(fpa11->fpreg[Fn].fSingle, &fpa11->fp_status);

      break;

      case typeDouble:

        //printk("double.\n");

	if (float64_is_nan(fpa11->fpreg[Fn].fDouble))

	   goto unordered;

        rFn = float64_to_floatx80(fpa11->fpreg[Fn].fDouble, &fpa11->fp_status);

      break;

      case typeExtended:

        //printk("extended.\n");

	if (floatx80_is_nan(fpa11->fpreg[Fn].fExtended))

	   goto unordered;

        rFn = fpa11->fpreg[Fn].fExtended;

      break;

      default: return 0;

   }

   if (CONSTANT_FM(opcode))

   {

     //printk("Fm is a constant: #%d.\n",Fm);

     rFm = getExtendedConstant(Fm);

     if (floatx80_is_nan(rFm))

        goto unordered;

   }

   else

   {

     //printk("Fm = r%d which contains a ",Fm);

      switch (fpa11->fType[Fm])

      {

         case typeSingle:

           //printk("single.\n");

	   if (float32_is_nan(fpa11->fpreg[Fm].fSingle))

	      goto unordered;

           rFm = float32_to_floatx80(fpa11->fpreg[Fm].fSingle, &fpa11->fp_status);

         break;

         case typeDouble:

           //printk("double.\n");

	   if (float64_is_nan(fpa11->fpreg[Fm].fDouble))

	      goto unordered;

           rFm = float64_to_floatx80(fpa11->fpreg[Fm].fDouble, &fpa11->fp_status);

         break;

         case typeExtended:

           //printk("extended.\n");

	   if (floatx80_is_nan(fpa11->fpreg[Fm].fExtended))

	      goto unordered;

           rFm = fpa11->fpreg[Fm].fExtended;

         break;

         default: return 0;

      }

   }

   if (n_flag)

   {

      rFm.high ^= 0x8000;

   }

   return PerformComparisonOperation(rFn,rFm);

 unordered:

   /* ?? The FPA data sheet is pretty vague about this, in particular

      about whether the non-E comparisons can ever raise exceptions.

      This implementation is based on a combination of what it says in

      the data sheet, observation of how the Acorn emulator actually

      behaves (and how programs expect it to) and guesswork.  */

   flags |= CC_OVERFLOW;

   flags &= ~(CC_ZERO | CC_NEGATIVE);

   if (BIT_AC & readFPSR()) flags |= CC_CARRY;

   if (e_flag) float_raise(float_flag_invalid, &fpa11->fp_status);

   writeConditionCodes(flags);

   return 1;

}