static int RENAME(dct_quantize)(MpegEncContext *s,

                            int16_t *block, int n,

                            int qscale, int *overflow)

{

    x86_reg last_non_zero_p1;

    int level=0, q; //=0 is because gcc says uninitialized ...

    const uint16_t *qmat, *bias;

    LOCAL_ALIGNED_16(int16_t, temp_block, [64]);

    av_assert2((7&(int)(&temp_block[0])) == 0); //did gcc align it correctly?

    //s->fdct (block);

    RENAME_FDCT(ff_fdct)(block); // cannot be anything else ...

    if(s->dct_error_sum)

        s->denoise_dct(s, block);

    if (s->mb_intra) {

        int dummy;

        if (n < 4){

            q = s->y_dc_scale;

            bias = s->q_intra_matrix16[qscale][1];

            qmat = s->q_intra_matrix16[qscale][0];

        }else{

            q = s->c_dc_scale;

            bias = s->q_chroma_intra_matrix16[qscale][1];

            qmat = s->q_chroma_intra_matrix16[qscale][0];

        }

        /* note: block[0] is assumed to be positive */

        if (!s->h263_aic) {

        __asm__ volatile (

                "mul %%ecx                \n\t"

                : "=d" (level), "=a"(dummy)

                : "a" ((block[0]>>2) + q), "c" (ff_inverse[q<<1])

        );

        } else

            /* For AIC we skip quant/dequant of INTRADC */

            level = (block[0] + 4)>>3;

        block[0]=0; //avoid fake overflow

//        temp_block[0] = (block[0] + (q >> 1)) / q;

        last_non_zero_p1 = 1;

    } else {

        last_non_zero_p1 = 0;

        bias = s->q_inter_matrix16[qscale][1];

        qmat = s->q_inter_matrix16[qscale][0];

    }

    if((s->out_format == FMT_H263 || s->out_format == FMT_H261) && s->mpeg_quant==0){

        __asm__ volatile(

            "movd %%"FF_REG_a", "MM"3           \n\t" // last_non_zero_p1

            SPREADW(MM"3")

            "pxor "MM"7, "MM"7                  \n\t" // 0

            "pxor "MM"4, "MM"4                  \n\t" // 0

            MOVQ" (%2), "MM"5                   \n\t" // qmat[0]

            "pxor "MM"6, "MM"6                  \n\t"

            "psubw (%3), "MM"6                  \n\t" // -bias[0]

            "mov $-128, %%"FF_REG_a"            \n\t"

            ".p2align 4                         \n\t"

            "1:                                 \n\t"

            MOVQ" (%1, %%"FF_REG_a"), "MM"0     \n\t" // block[i]

            SAVE_SIGN(MM"1", MM"0")                   // ABS(block[i])

            "psubusw "MM"6, "MM"0               \n\t" // ABS(block[i]) + bias[0]

            "pmulhw "MM"5, "MM"0                \n\t" // (ABS(block[i])*qmat[0] - bias[0]*qmat[0])>>16

            "por "MM"0, "MM"4                   \n\t"

            RESTORE_SIGN(MM"1", MM"0")                // out=((ABS(block[i])*qmat[0] - bias[0]*qmat[0])>>16)*sign(block[i])

            MOVQ" "MM"0, (%5, %%"FF_REG_a")     \n\t"

            "pcmpeqw "MM"7, "MM"0               \n\t" // out==0 ? 0xFF : 0x00

            MOVQ" (%4, %%"FF_REG_a"), "MM"1     \n\t"

            MOVQ" "MM"7, (%1, %%"FF_REG_a")     \n\t" // 0

            "pandn "MM"1, "MM"0                 \n\t"

            PMAXW(MM"0", MM"3")

            "add $"MMREG_WIDTH", %%"FF_REG_a"   \n\t"

            " js 1b                             \n\t"

            PMAX(MM"3", MM"0")

            "movd "MM"3, %%"FF_REG_a"           \n\t"

            "movzbl %%al, %%eax                 \n\t" // last_non_zero_p1

            : "+a" (last_non_zero_p1)

            : "r" (block+64), "r" (qmat), "r" (bias),

              "r" (inv_zigzag_direct16 + 64), "r" (temp_block + 64)

              XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm2", "%xmm3",

                                "%xmm4", "%xmm5", "%xmm6", "%xmm7")

        );

    }else{ // FMT_H263

        __asm__ volatile(

            "movd %%"FF_REG_a", "MM"3           \n\t" // last_non_zero_p1

            SPREADW(MM"3")

            "pxor "MM"7, "MM"7                  \n\t" // 0

            "pxor "MM"4, "MM"4                  \n\t" // 0

            "mov $-128, %%"FF_REG_a"            \n\t"

            ".p2align 4                         \n\t"

            "1:                                 \n\t"

            MOVQ" (%1, %%"FF_REG_a"), "MM"0     \n\t" // block[i]

            SAVE_SIGN(MM"1", MM"0")                   // ABS(block[i])

            MOVQ" (%3, %%"FF_REG_a"), "MM"6     \n\t" // bias[0]

            "paddusw "MM"6, "MM"0               \n\t" // ABS(block[i]) + bias[0]

            MOVQ" (%2, %%"FF_REG_a"), "MM"5     \n\t" // qmat[i]

            "pmulhw "MM"5, "MM"0                \n\t" // (ABS(block[i])*qmat[0] + bias[0]*qmat[0])>>16

            "por "MM"0, "MM"4                   \n\t"

            RESTORE_SIGN(MM"1", MM"0")                // out=((ABS(block[i])*qmat[0] - bias[0]*qmat[0])>>16)*sign(block[i])

            MOVQ" "MM"0, (%5, %%"FF_REG_a")     \n\t"

            "pcmpeqw "MM"7, "MM"0               \n\t" // out==0 ? 0xFF : 0x00

            MOVQ" (%4, %%"FF_REG_a"), "MM"1     \n\t"

            MOVQ" "MM"7, (%1, %%"FF_REG_a")     \n\t" // 0

            "pandn "MM"1, "MM"0                 \n\t"

            PMAXW(MM"0", MM"3")

            "add $"MMREG_WIDTH", %%"FF_REG_a"   \n\t"

            " js 1b                             \n\t"

            PMAX(MM"3", MM"0")

            "movd "MM"3, %%"FF_REG_a"           \n\t"

            "movzbl %%al, %%eax                 \n\t" // last_non_zero_p1

            : "+a" (last_non_zero_p1)

            : "r" (block+64), "r" (qmat+64), "r" (bias+64),

              "r" (inv_zigzag_direct16 + 64), "r" (temp_block + 64)

              XMM_CLOBBERS_ONLY("%xmm0", "%xmm1", "%xmm2", "%xmm3",

                                "%xmm4", "%xmm5", "%xmm6", "%xmm7")

        );

    }

    __asm__ volatile(

        "movd %1, "MM"1                     \n\t" // max_qcoeff

        SPREADW(MM"1")

        "psubusw "MM"1, "MM"4               \n\t"

        "packuswb "MM"4, "MM"4              \n\t"

#if COMPILE_TEMPLATE_SSE2

        "packsswb "MM"4, "MM"4              \n\t"

#endif

        "movd "MM"4, %0                     \n\t" // *overflow

        : "=g" (*overflow)

        : "g" (s->max_qcoeff)

    );

    if(s->mb_intra) block[0]= level;

    else            block[0]= temp_block[0];

    if (s->idsp.perm_type == FF_IDCT_PERM_SIMPLE) {

        if(last_non_zero_p1 <= 1) goto end;

        block[0x08] = temp_block[0x01]; block[0x10] = temp_block[0x08];

        block[0x20] = temp_block[0x10];

        if(last_non_zero_p1 <= 4) goto end;

        block[0x18] = temp_block[0x09]; block[0x04] = temp_block[0x02];

        block[0x09] = temp_block[0x03];

        if(last_non_zero_p1 <= 7) goto end;

        block[0x14] = temp_block[0x0A]; block[0x28] = temp_block[0x11];

        block[0x12] = temp_block[0x18]; block[0x02] = temp_block[0x20];

        if(last_non_zero_p1 <= 11) goto end;

        block[0x1A] = temp_block[0x19]; block[0x24] = temp_block[0x12];

        block[0x19] = temp_block[0x0B]; block[0x01] = temp_block[0x04];

        block[0x0C] = temp_block[0x05];

        if(last_non_zero_p1 <= 16) goto end;

        block[0x11] = temp_block[0x0C]; block[0x29] = temp_block[0x13];

        block[0x16] = temp_block[0x1A]; block[0x0A] = temp_block[0x21];

        block[0x30] = temp_block[0x28]; block[0x22] = temp_block[0x30];

        block[0x38] = temp_block[0x29]; block[0x06] = temp_block[0x22];

        if(last_non_zero_p1 <= 24) goto end;

        block[0x1B] = temp_block[0x1B]; block[0x21] = temp_block[0x14];

        block[0x1C] = temp_block[0x0D]; block[0x05] = temp_block[0x06];

        block[0x0D] = temp_block[0x07]; block[0x15] = temp_block[0x0E];

        block[0x2C] = temp_block[0x15]; block[0x13] = temp_block[0x1C];

        if(last_non_zero_p1 <= 32) goto end;

        block[0x0B] = temp_block[0x23]; block[0x34] = temp_block[0x2A];

        block[0x2A] = temp_block[0x31]; block[0x32] = temp_block[0x38];

        block[0x3A] = temp_block[0x39]; block[0x26] = temp_block[0x32];

        block[0x39] = temp_block[0x2B]; block[0x03] = temp_block[0x24];

        if(last_non_zero_p1 <= 40) goto end;

        block[0x1E] = temp_block[0x1D]; block[0x25] = temp_block[0x16];

        block[0x1D] = temp_block[0x0F]; block[0x2D] = temp_block[0x17];

        block[0x17] = temp_block[0x1E]; block[0x0E] = temp_block[0x25];

        block[0x31] = temp_block[0x2C]; block[0x2B] = temp_block[0x33];

        if(last_non_zero_p1 <= 48) goto end;

        block[0x36] = temp_block[0x3A]; block[0x3B] = temp_block[0x3B];

        block[0x23] = temp_block[0x34]; block[0x3C] = temp_block[0x2D];

        block[0x07] = temp_block[0x26]; block[0x1F] = temp_block[0x1F];

        block[0x0F] = temp_block[0x27]; block[0x35] = temp_block[0x2E];

        if(last_non_zero_p1 <= 56) goto end;

        block[0x2E] = temp_block[0x35]; block[0x33] = temp_block[0x3C];

        block[0x3E] = temp_block[0x3D]; block[0x27] = temp_block[0x36];

        block[0x3D] = temp_block[0x2F]; block[0x2F] = temp_block[0x37];

        block[0x37] = temp_block[0x3E]; block[0x3F] = temp_block[0x3F];

    }else if(s->idsp.perm_type == FF_IDCT_PERM_LIBMPEG2){

        if(last_non_zero_p1 <= 1) goto end;

        block[0x04] = temp_block[0x01];

        block[0x08] = temp_block[0x08]; block[0x10] = temp_block[0x10];

        if(last_non_zero_p1 <= 4) goto end;

        block[0x0C] = temp_block[0x09]; block[0x01] = temp_block[0x02];

        block[0x05] = temp_block[0x03];

        if(last_non_zero_p1 <= 7) goto end;

        block[0x09] = temp_block[0x0A]; block[0x14] = temp_block[0x11];

        block[0x18] = temp_block[0x18]; block[0x20] = temp_block[0x20];

        if(last_non_zero_p1 <= 11) goto end;

        block[0x1C] = temp_block[0x19];

        block[0x11] = temp_block[0x12]; block[0x0D] = temp_block[0x0B];

        block[0x02] = temp_block[0x04]; block[0x06] = temp_block[0x05];

        if(last_non_zero_p1 <= 16) goto end;

        block[0x0A] = temp_block[0x0C]; block[0x15] = temp_block[0x13];

        block[0x19] = temp_block[0x1A]; block[0x24] = temp_block[0x21];

        block[0x28] = temp_block[0x28]; block[0x30] = temp_block[0x30];

        block[0x2C] = temp_block[0x29]; block[0x21] = temp_block[0x22];

        if(last_non_zero_p1 <= 24) goto end;

        block[0x1D] = temp_block[0x1B]; block[0x12] = temp_block[0x14];

        block[0x0E] = temp_block[0x0D]; block[0x03] = temp_block[0x06];

        block[0x07] = temp_block[0x07]; block[0x0B] = temp_block[0x0E];

        block[0x16] = temp_block[0x15]; block[0x1A] = temp_block[0x1C];

        if(last_non_zero_p1 <= 32) goto end;

        block[0x25] = temp_block[0x23]; block[0x29] = temp_block[0x2A];

        block[0x34] = temp_block[0x31]; block[0x38] = temp_block[0x38];

        block[0x3C] = temp_block[0x39]; block[0x31] = temp_block[0x32];

        block[0x2D] = temp_block[0x2B]; block[0x22] = temp_block[0x24];

        if(last_non_zero_p1 <= 40) goto end;

        block[0x1E] = temp_block[0x1D]; block[0x13] = temp_block[0x16];

        block[0x0F] = temp_block[0x0F]; block[0x17] = temp_block[0x17];

        block[0x1B] = temp_block[0x1E]; block[0x26] = temp_block[0x25];

        block[0x2A] = temp_block[0x2C]; block[0x35] = temp_block[0x33];

        if(last_non_zero_p1 <= 48) goto end;

        block[0x39] = temp_block[0x3A]; block[0x3D] = temp_block[0x3B];

        block[0x32] = temp_block[0x34]; block[0x2E] = temp_block[0x2D];

            block[0x23] = temp_block[0x26]; block[0x1F] = temp_block[0x1F];

        block[0x27] = temp_block[0x27]; block[0x2B] = temp_block[0x2E];

        if(last_non_zero_p1 <= 56) goto end;

        block[0x36] = temp_block[0x35]; block[0x3A] = temp_block[0x3C];

        block[0x3E] = temp_block[0x3D]; block[0x33] = temp_block[0x36];

        block[0x2F] = temp_block[0x2F]; block[0x37] = temp_block[0x37];

        block[0x3B] = temp_block[0x3E]; block[0x3F] = temp_block[0x3F];

    }else{

        if(last_non_zero_p1 <= 1) goto end;

        block[0x01] = temp_block[0x01];

        block[0x08] = temp_block[0x08]; block[0x10] = temp_block[0x10];

        if(last_non_zero_p1 <= 4) goto end;

        block[0x09] = temp_block[0x09]; block[0x02] = temp_block[0x02];

        block[0x03] = temp_block[0x03];

        if(last_non_zero_p1 <= 7) goto end;

        block[0x0A] = temp_block[0x0A]; block[0x11] = temp_block[0x11];

        block[0x18] = temp_block[0x18]; block[0x20] = temp_block[0x20];

        if(last_non_zero_p1 <= 11) goto end;

        block[0x19] = temp_block[0x19];

        block[0x12] = temp_block[0x12]; block[0x0B] = temp_block[0x0B];

        block[0x04] = temp_block[0x04]; block[0x05] = temp_block[0x05];

        if(last_non_zero_p1 <= 16) goto end;

        block[0x0C] = temp_block[0x0C]; block[0x13] = temp_block[0x13];

        block[0x1A] = temp_block[0x1A]; block[0x21] = temp_block[0x21];

        block[0x28] = temp_block[0x28]; block[0x30] = temp_block[0x30];

        block[0x29] = temp_block[0x29]; block[0x22] = temp_block[0x22];

        if(last_non_zero_p1 <= 24) goto end;

        block[0x1B] = temp_block[0x1B]; block[0x14] = temp_block[0x14];

        block[0x0D] = temp_block[0x0D]; block[0x06] = temp_block[0x06];

        block[0x07] = temp_block[0x07]; block[0x0E] = temp_block[0x0E];

        block[0x15] = temp_block[0x15]; block[0x1C] = temp_block[0x1C];

        if(last_non_zero_p1 <= 32) goto end;

        block[0x23] = temp_block[0x23]; block[0x2A] = temp_block[0x2A];

        block[0x31] = temp_block[0x31]; block[0x38] = temp_block[0x38];

        block[0x39] = temp_block[0x39]; block[0x32] = temp_block[0x32];

        block[0x2B] = temp_block[0x2B]; block[0x24] = temp_block[0x24];

        if(last_non_zero_p1 <= 40) goto end;

        block[0x1D] = temp_block[0x1D]; block[0x16] = temp_block[0x16];

        block[0x0F] = temp_block[0x0F]; block[0x17] = temp_block[0x17];

        block[0x1E] = temp_block[0x1E]; block[0x25] = temp_block[0x25];

        block[0x2C] = temp_block[0x2C]; block[0x33] = temp_block[0x33];

        if(last_non_zero_p1 <= 48) goto end;

        block[0x3A] = temp_block[0x3A]; block[0x3B] = temp_block[0x3B];

        block[0x34] = temp_block[0x34]; block[0x2D] = temp_block[0x2D];

        block[0x26] = temp_block[0x26]; block[0x1F] = temp_block[0x1F];

        block[0x27] = temp_block[0x27]; block[0x2E] = temp_block[0x2E];

        if(last_non_zero_p1 <= 56) goto end;

        block[0x35] = temp_block[0x35]; block[0x3C] = temp_block[0x3C];

        block[0x3D] = temp_block[0x3D]; block[0x36] = temp_block[0x36];

        block[0x2F] = temp_block[0x2F]; block[0x37] = temp_block[0x37];

        block[0x3E] = temp_block[0x3E]; block[0x3F] = temp_block[0x3F];

    }

    end:

    return last_non_zero_p1 - 1;

}


static void qdm2_fft_decode_tones (QDM2Context *q, int duration, GetBitContext *gb, int b)

{

    int channel, stereo, phase, exp;

    int local_int_4,  local_int_8,  stereo_phase,  local_int_10;

    int local_int_14, stereo_exp, local_int_20, local_int_28;

    int n, offset;

    local_int_4 = 0;

    local_int_28 = 0;

    local_int_20 = 2;

    local_int_8 = (4 - duration);

    local_int_10 = 1 << (q->group_order - duration - 1);

    offset = 1;

    while (1) {

        if (q->superblocktype_2_3) {

            while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {

                offset = 1;

                if (n == 0) {

                    local_int_4 += local_int_10;

                    local_int_28 += (1 << local_int_8);

                } else {

                    local_int_4 += 8*local_int_10;

                    local_int_28 += (8 << local_int_8);

                }

            }

            offset += (n - 2);

        } else {

            offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);

            while (offset >= (local_int_10 - 1)) {

                offset += (1 - (local_int_10 - 1));

                local_int_4  += local_int_10;

                local_int_28 += (1 << local_int_8);

            }

        }

        if (local_int_4 >= q->group_size)

        local_int_14 = (offset >> local_int_8);

        if (q->nb_channels > 1) {

            channel = get_bits1(gb);

            stereo = get_bits1(gb);

        } else {

            channel = 0;

            stereo = 0;

        }

        exp = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);

        exp += q->fft_level_exp[fft_level_index_table[local_int_14]];

        exp = (exp < 0) ? 0 : exp;

        phase = get_bits(gb, 3);

        stereo_exp = 0;

        stereo_phase = 0;

        if (stereo) {

            stereo_exp = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));

            stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));

            if (stereo_phase < 0)

                stereo_phase += 8;

        }

        if (q->frequency_range > (local_int_14 + 1)) {

            int sub_packet = (local_int_20 + local_int_28);

            qdm2_fft_init_coefficient(q, sub_packet, offset, duration, channel, exp, phase);

            if (stereo)

                qdm2_fft_init_coefficient(q, sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);

        }

        offset++;

    }

}


static void cuda_receive_packet(CUDAState *s,

                                const uint8_t *data, int len)

{

    uint8_t obuf[16] = { CUDA_PACKET, 0, data[0] };

    int autopoll;

    uint32_t ti;

    switch(data[0]) {

    case CUDA_AUTOPOLL:

        autopoll = (data[1] != 0);

        if (autopoll != s->autopoll) {

            s->autopoll = autopoll;

            if (autopoll) {

                timer_mod(s->adb_poll_timer,

                               qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +

                               (get_ticks_per_sec() / CUDA_ADB_POLL_FREQ));

            } else {

                timer_del(s->adb_poll_timer);

            }

        }

        cuda_send_packet_to_host(s, obuf, 3);

        break;

    case CUDA_GET_6805_ADDR:

        cuda_send_packet_to_host(s, obuf, 3);

        break;

    case CUDA_SET_TIME:

        ti = (((uint32_t)data[1]) << 24) + (((uint32_t)data[2]) << 16) + (((uint32_t)data[3]) << 8) + data[4];

        s->tick_offset = ti - (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / get_ticks_per_sec());

        cuda_send_packet_to_host(s, obuf, 3);

        break;

    case CUDA_GET_TIME:

        ti = s->tick_offset + (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / get_ticks_per_sec());

        obuf[3] = ti >> 24;

        obuf[4] = ti >> 16;

        obuf[5] = ti >> 8;

        obuf[6] = ti;

        cuda_send_packet_to_host(s, obuf, 7);

        break;

    case CUDA_FILE_SERVER_FLAG:

    case CUDA_SET_DEVICE_LIST:

    case CUDA_SET_AUTO_RATE:

    case CUDA_SET_POWER_MESSAGES:

        cuda_send_packet_to_host(s, obuf, 3);

        break;

    case CUDA_POWERDOWN:

        cuda_send_packet_to_host(s, obuf, 3);

        qemu_system_shutdown_request();

        break;

    case CUDA_RESET_SYSTEM:

        cuda_send_packet_to_host(s, obuf, 3);

        qemu_system_reset_request();

        break;

    case CUDA_COMBINED_FORMAT_IIC:

        obuf[1] = 0x5;

        break;

    case CUDA_GET_SET_IIC:

        if (len == 4) {

            cuda_send_packet_to_host(s, obuf, 3);

        } else {

        }

        break;

    default:

        break;

    }

}


static void bitmap_free(Qcow2Bitmap *bm)
{
    g_free(bm->name);
    g_free(bm);


static int vp6_parse_coeff(VP56Context *s)

{

    VP56RangeCoder *c = s->ccp;

    VP56Model *model = s->modelp;

    uint8_t *permute = s->idct_scantable;

    uint8_t *model1, *model2, *model3;

    int coeff, sign, coeff_idx;

    int b, i, cg, idx, ctx;

    int pt = 0;    /* plane type (0 for Y, 1 for U or V) */

    if (c->end >= c->buffer && c->bits >= 0) {

        av_log(s->avctx, AV_LOG_ERROR, "End of AC stream reached in vp6_parse_coeff\n");

        return AVERROR_INVALIDDATA;

    }

    for (b=0; b<6; b++) {

        int ct = 1;    /* code type */

        int run = 1;

        if (b > 3) pt = 1;

        ctx = s->left_block[ff_vp56_b6to4[b]].not_null_dc

              + s->above_blocks[s->above_block_idx[b]].not_null_dc;

        model1 = model->coeff_dccv[pt];

        model2 = model->coeff_dcct[pt][ctx];

        coeff_idx = 0;

        for (;;) {

            if ((coeff_idx>1 && ct==0) || vp56_rac_get_prob_branchy(c, model2[0])) {

                /* parse a coeff */

                if (vp56_rac_get_prob_branchy(c, model2[2])) {

                    if (vp56_rac_get_prob_branchy(c, model2[3])) {

                        idx = vp56_rac_get_tree(c, ff_vp56_pc_tree, model1);

                        coeff = ff_vp56_coeff_bias[idx+5];

                        for (i=ff_vp56_coeff_bit_length[idx]; i>=0; i--)

                            coeff += vp56_rac_get_prob(c, ff_vp56_coeff_parse_table[idx][i]) << i;

                    } else {

                        if (vp56_rac_get_prob_branchy(c, model2[4]))

                            coeff = 3 + vp56_rac_get_prob(c, model1[5]);

                        else

                            coeff = 2;

                    }

                    ct = 2;

                } else {

                    ct = 1;

                    coeff = 1;

                }

                sign = vp56_rac_get(c);

                coeff = (coeff ^ -sign) + sign;

                if (coeff_idx)

                    coeff *= s->dequant_ac;

                idx = model->coeff_index_to_pos[coeff_idx];

                s->block_coeff[b][permute[idx]] = coeff;

                run = 1;

            } else {

                /* parse a run */

                ct = 0;

                if (coeff_idx > 0) {

                    if (!vp56_rac_get_prob_branchy(c, model2[1]))

                        break;

                    model3 = model->coeff_runv[coeff_idx >= 6];

                    run = vp56_rac_get_tree(c, vp6_pcr_tree, model3);

                    if (!run)

                        for (run=9, i=0; i<6; i++)

                            run += vp56_rac_get_prob(c, model3[i+8]) << i;

                }

            }

            coeff_idx += run;

            if (coeff_idx >= 64)

                break;

            cg = vp6_coeff_groups[coeff_idx];

            model1 = model2 = model->coeff_ract[pt][ct][cg];

        }

        s->left_block[ff_vp56_b6to4[b]].not_null_dc =

        s->above_blocks[s->above_block_idx[b]].not_null_dc = !!s->block_coeff[b][0];

    }

    return 0;

}


static int ftp_passive_mode_epsv(FTPContext *s)

{

    char *res = NULL, *start = NULL, *end = NULL;

    int i;

    static const char d = '|';

    static const char *command = "EPSV\r\n";

    static const int epsv_codes[] = {229, 0};

    if (ftp_send_command(s, command, epsv_codes, &res) != 229 || !res)

        goto fail;

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

        if (res[i] == '(') {

            start = res + i + 1;

        } else if (res[i] == ')') {

            end = res + i;

            break;

        }

    }

    if (!start || !end)

        goto fail;

    *end = '\0';

    if (strlen(start) < 5)

        goto fail;

    if (start[0] != d || start[1] != d || start[2] != d || end[-1] != d)

        goto fail;

    start += 3;

    end[-1] = '\0';

    s->server_data_port = atoi(start);

    av_dlog(s, "Server data port: %d\n", s->server_data_port);

    av_free(res);

    return 0;

  fail:

    av_free(res);

    s->server_data_port = -1;

    return AVERROR(ENOSYS);

}


static void qemu_enqueue_packet(VLANClientState *sender,

                                const uint8_t *buf, int size,

                                NetPacketSent *sent_cb)

{

    VLANPacket *packet;

    packet = qemu_malloc(sizeof(VLANPacket) + size);

    packet->sender = sender;

    packet->size = size;

    packet->sent_cb = sent_cb;

    memcpy(packet->data, buf, size);

    TAILQ_INSERT_TAIL(&sender->vlan->send_queue, packet, entry);

}


static inline uint64_t cpu_ppc_get_tb(CPUPPCState *env)

{

    /* TO FIX */

    return 0;

}


uint16_t net_checksum_tcpudp(uint16_t length, uint16_t proto,

                             uint8_t *addrs, uint8_t *buf)

{

    uint32_t sum = 0;

    sum += net_checksum_add(length, buf);         // payload

    sum += net_checksum_add(8, addrs);            // src + dst address

    sum += proto + length;                        // protocol & length

    return net_checksum_finish(sum);

}


void cpu_loop_exit(CPUState *env1)

{

    env1->current_tb = NULL;

    longjmp(env1->jmp_env, 1);

}


void ppc_hw_interrupt (CPUPPCState *env)

{

    int raised = 0;

#if 1

    if (loglevel & CPU_LOG_INT) {

        fprintf(logfile, "%s: %p pending %08x req %08x me %d ee %d\n",

                __func__, env, env->pending_interrupts,

                env->interrupt_request, msr_me, msr_ee);

    }

#endif

    /* Raise it */

    if (env->pending_interrupts & (1 << PPC_INTERRUPT_RESET)) {

        /* External reset / critical input */

        /* XXX: critical input should be handled another way.

         *      This code is not correct !

         */

        env->exception_index = EXCP_RESET;

        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_RESET);

        raised = 1;

    }

    if (raised == 0 && msr_me != 0) {

        /* Machine check exception */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_MCK)) {

            env->exception_index = EXCP_MACHINE_CHECK;

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_MCK);

            raised = 1;

        }

    }

    if (raised == 0 && msr_ee != 0) {

#if defined(TARGET_PPC64H) /* PowerPC 64 with hypervisor mode support */

        /* Hypervisor decrementer exception */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_HDECR)) {

            env->exception_index = EXCP_HDECR;

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_HDECR);

            raised = 1;

        } else

#endif

        /* Decrementer exception */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_DECR)) {

            env->exception_index = EXCP_DECR;

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DECR);

            raised = 1;

        /* Programmable interval timer on embedded PowerPC */

        } else if (env->pending_interrupts & (1 << PPC_INTERRUPT_PIT)) {

            env->exception_index = EXCP_40x_PIT;

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_PIT);

            raised = 1;

        /* Fixed interval timer on embedded PowerPC */

        } else if (env->pending_interrupts & (1 << PPC_INTERRUPT_FIT)) {

            env->exception_index = EXCP_40x_FIT;

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_FIT);

            raised = 1;

        /* Watchdog timer on embedded PowerPC */

        } else if (env->pending_interrupts & (1 << PPC_INTERRUPT_WDT)) {

            env->exception_index = EXCP_40x_WATCHDOG;

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_WDT);

            raised = 1;

        /* External interrupt */

        } else if (env->pending_interrupts & (1 << PPC_INTERRUPT_EXT)) {

            env->exception_index = EXCP_EXTERNAL;

            /* Taking an external interrupt does not clear the external

             * interrupt status

             */

#if 0

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_EXT);

#endif

            raised = 1;

#if 0 // TODO

        /* Thermal interrupt */

        } else if (env->pending_interrupts & (1 << PPC_INTERRUPT_THERM)) {

            env->exception_index = EXCP_970_THRM;

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_THERM);

            raised = 1;

#endif

        }

#if 0 // TODO

    /* External debug exception */

    } else if (env->pending_interrupts & (1 << PPC_INTERRUPT_DEBUG)) {

        env->exception_index = EXCP_xxx;

        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DEBUG);

        raised = 1;

#endif

    }

    if (raised != 0) {

        env->error_code = 0;

        do_interrupt(env);

    }

}


gen_intermediate_code_internal(CPUState *env, TranslationBlock *tb,

                               int search_pc)

{

    uint16_t *gen_opc_end;

    uint32_t pc_start;

    int j, lj;

    struct DisasContext ctx;

    struct DisasContext *dc = &ctx;

    uint32_t next_page_start, org_flags;

    target_ulong npc;

    int num_insns;

    int max_insns;

    qemu_log_try_set_file(stderr);

    pc_start = tb->pc;

    dc->env = env;

    dc->tb = tb;

    org_flags = dc->synced_flags = dc->tb_flags = tb->flags;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    dc->is_jmp = DISAS_NEXT;

    dc->jmp = 0;

    dc->delayed_branch = !!(dc->tb_flags & D_FLAG);

    dc->pc = pc_start;

    dc->singlestep_enabled = env->singlestep_enabled;

    dc->cpustate_changed = 0;

    dc->abort_at_next_insn = 0;

    dc->nr_nops = 0;

    if (pc_start & 3)

        cpu_abort(env, "Microblaze: unaligned PC=%x\n", pc_start);

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

#if !SIM_COMPAT

        qemu_log("--------------\n");

        log_cpu_state(env, 0);

#endif

    }

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    lj = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_icount_start();

    do

    {

#if SIM_COMPAT

        if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

            tcg_gen_movi_tl(cpu_SR[SR_PC], dc->pc);

            gen_helper_debug();

        }

#endif

        check_breakpoint(env, dc);

        if (search_pc) {

            j = gen_opc_ptr - gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    gen_opc_instr_start[lj++] = 0;

            }

            gen_opc_pc[lj] = dc->pc;

            gen_opc_instr_start[lj] = 1;

                        gen_opc_icount[lj] = num_insns;

        }

        /* Pretty disas.  */

        LOG_DIS("%8.8x:\t", dc->pc);

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))

            gen_io_start();

        dc->clear_imm = 1;

	decode(dc);

        if (dc->clear_imm)

            dc->tb_flags &= ~IMM_FLAG;

        dc->pc += 4;

        num_insns++;

        if (dc->delayed_branch) {

            dc->delayed_branch--;

            if (!dc->delayed_branch) {

                if (dc->tb_flags & DRTI_FLAG)

                    do_rti(dc);

                 if (dc->tb_flags & DRTB_FLAG)

                    do_rtb(dc);

                if (dc->tb_flags & DRTE_FLAG)

                    do_rte(dc);

                /* Clear the delay slot flag.  */

                dc->tb_flags &= ~D_FLAG;

                /* If it is a direct jump, try direct chaining.  */

                if (dc->jmp != JMP_DIRECT) {

                    eval_cond_jmp(dc, env_btarget, tcg_const_tl(dc->pc));

                    dc->is_jmp = DISAS_JUMP;

                }

                break;

            }

        }

        if (env->singlestep_enabled)

            break;

    } while (!dc->is_jmp && !dc->cpustate_changed

         && gen_opc_ptr < gen_opc_end

                 && !singlestep

         && (dc->pc < next_page_start)

                 && num_insns < max_insns);

    npc = dc->pc;

    if (dc->jmp == JMP_DIRECT) {

        if (dc->tb_flags & D_FLAG) {

            dc->is_jmp = DISAS_UPDATE;

            tcg_gen_movi_tl(cpu_SR[SR_PC], npc);

            sync_jmpstate(dc);

        } else

            npc = dc->jmp_pc;

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    /* Force an update if the per-tb cpu state has changed.  */

    if (dc->is_jmp == DISAS_NEXT

        && (dc->cpustate_changed || org_flags != dc->tb_flags)) {

        dc->is_jmp = DISAS_UPDATE;

        tcg_gen_movi_tl(cpu_SR[SR_PC], npc);

    }

    t_sync_flags(dc);

    if (unlikely(env->singlestep_enabled)) {

        t_gen_raise_exception(dc, EXCP_DEBUG);

        if (dc->is_jmp == DISAS_NEXT)

            tcg_gen_movi_tl(cpu_SR[SR_PC], npc);

    } else {

        switch(dc->is_jmp) {

            case DISAS_NEXT:

                gen_goto_tb(dc, 1, npc);

                break;

            default:

            case DISAS_JUMP:

            case DISAS_UPDATE:

                /* indicate that the hash table must be used

                   to find the next TB */

                tcg_gen_exit_tb(0);

                break;

            case DISAS_TB_JUMP:

                /* nothing more to generate */

                break;

        }

    }

    gen_icount_end(tb, num_insns);

    *gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = dc->pc - pc_start;

                tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

#if !SIM_COMPAT

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("\n");

#if DISAS_GNU

        log_target_disas(pc_start, dc->pc - pc_start, 0);

#endif

        qemu_log("\nisize=%d osize=%td\n",

            dc->pc - pc_start, gen_opc_ptr - gen_opc_buf);

    }

#endif

#endif

    assert(!dc->abort_at_next_insn);

}


static void add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w)

{

    long i;

    for (i = 0; i <= w - sizeof(long); i += sizeof(long)) {

        long a = *(long *)(src1 + i);

        long b = *(long *)(src2 + i);

        *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80);

    }

    for (; i < w; i++)

        dst[i] = src1[i] + src2[i];

}


static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,

                               BdrvCheckMode fix, bool *rebuild,

                               uint16_t **refcount_table, int64_t *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t i;

    QCowSnapshot *sn;

    int ret;

    if (!*refcount_table) {

        int64_t old_size = 0;

        ret = realloc_refcount_array(s, refcount_table,

                                     &old_size, *nb_clusters);

        if (ret < 0) {

            res->check_errors++;

            return ret;

        }

    }

    /* header */

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        0, s->cluster_size);

    if (ret < 0) {

        return ret;

    }

    /* current L1 table */

    ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                             s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);

    if (ret < 0) {

        return ret;

    }

    /* snapshots */

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

        sn = s->snapshots + i;

        ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                                 sn->l1_table_offset, sn->l1_size, 0);

        if (ret < 0) {

            return ret;

        }

    }

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        s->snapshots_offset, s->snapshots_size);

    if (ret < 0) {

        return ret;

    }

    /* refcount data */

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        s->refcount_table_offset,

                        s->refcount_table_size * sizeof(uint64_t));

    if (ret < 0) {

        return ret;

    }

    return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);

}


static void ne2000_ioport_write(void *opaque, uint32_t addr, uint32_t val)

{

    NE2000State *s = opaque;

    int offset, page;

    addr &= 0xf;

#ifdef DEBUG_NE2000

    printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);

#endif

    if (addr == E8390_CMD) {

        /* control register */

        s->cmd = val;

        if (val & E8390_START) {

            s->isr &= ~ENISR_RESET;

            /* test specific case: zero length transfert */

            if ((val & (E8390_RREAD | E8390_RWRITE)) &&

                s->rcnt == 0) {

                s->isr |= ENISR_RDC;

                ne2000_update_irq(s);

            }

            if (val & E8390_TRANS) {

                qemu_send_packet(s->nd, s->mem + (s->tpsr << 8), s->tcnt);

                /* signal end of transfert */

                s->tsr = ENTSR_PTX;

                s->isr |= ENISR_TX;

                ne2000_update_irq(s);

            }

        }

    } else {

        page = s->cmd >> 6;

        offset = addr | (page << 4);

        switch(offset) {

        case EN0_STARTPG:

            s->start = val << 8;

            break;

        case EN0_STOPPG:

            s->stop = val << 8;

            break;

        case EN0_BOUNDARY:

            s->boundary = val;

            break;

        case EN0_IMR:

            s->imr = val;

            ne2000_update_irq(s);

            break;

        case EN0_TPSR:

            s->tpsr = val;

            break;

        case EN0_TCNTLO:

            s->tcnt = (s->tcnt & 0xff00) | val;

            break;

        case EN0_TCNTHI:

            s->tcnt = (s->tcnt & 0x00ff) | (val << 8);

            break;

        case EN0_RSARLO:

            s->rsar = (s->rsar & 0xff00) | val;

            break;

        case EN0_RSARHI:

            s->rsar = (s->rsar & 0x00ff) | (val << 8);

            break;

        case EN0_RCNTLO:

            s->rcnt = (s->rcnt & 0xff00) | val;

            break;

        case EN0_RCNTHI:

            s->rcnt = (s->rcnt & 0x00ff) | (val << 8);

            break;

        case EN0_DCFG:

            s->dcfg = val;

            break;

        case EN0_ISR:

            s->isr &= ~(val & 0x7f);

            ne2000_update_irq(s);

            break;

        case EN1_PHYS ... EN1_PHYS + 5:

            s->phys[offset - EN1_PHYS] = val;

            break;

        case EN1_CURPAG:

            s->curpag = val;

            break;

        case EN1_MULT ... EN1_MULT + 7:

            s->mult[offset - EN1_MULT] = val;

            break;

        }

    }

}


static int vc1_filter_line(uint8_t* src, int stride, int pq){

    int a0, a1, a2, a3, d, clip, filt3 = 0;

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    a0     = (2*(src[-2*stride] - src[ 1*stride]) - 5*(src[-1*stride] - src[ 0*stride]) + 4) >> 3;

    if(FFABS(a0) < pq){

        a1 = (2*(src[-4*stride] - src[-1*stride]) - 5*(src[-3*stride] - src[-2*stride]) + 4) >> 3;

        a2 = (2*(src[ 0*stride] - src[ 3*stride]) - 5*(src[ 1*stride] - src[ 2*stride]) + 4) >> 3;

        a3 = FFMIN(FFABS(a1), FFABS(a2));

        if(a3 < FFABS(a0)){

            d = 5 * ((a0 >=0 ? a3 : -a3) - a0) / 8;

            clip = (src[-1*stride] - src[ 0*stride])/2;

            if(clip){

                filt3 = 1;

                if(clip > 0)

                    d = av_clip(d, 0, clip);

                else

                    d = av_clip(d, clip, 0);

                src[-1*stride] = cm[src[-1*stride] - d];

                src[ 0*stride] = cm[src[ 0*stride] + d];

            }

        }

    }

    return filt3;

}


static int rle_unpack(const unsigned char *src, unsigned char *dest,

                      int src_count, int src_size, int dest_len)

{

    unsigned char *pd;

    int i, l;

    unsigned char *dest_end = dest + dest_len;

    GetByteContext gb;

    bytestream2_init(&gb, src, src_size);

    pd = dest;

    if (src_count & 1) {

        if (bytestream2_get_bytes_left(&gb) < 1)

            return 0;

        *pd++ = bytestream2_get_byteu(&gb);

    }

    src_count >>= 1;

    i = 0;

    do {

        if (bytestream2_get_bytes_left(&gb) < 1)

            break;

        l = bytestream2_get_byteu(&gb);

        if (l & 0x80) {

            l = (l & 0x7F) * 2;

            if (dest_end - pd < l || bytestream2_get_bytes_left(&gb) < l)

                return bytestream2_tell(&gb);

            bytestream2_get_bufferu(&gb, pd, l);

            pd += l;

        } else {

            if (dest_end - pd < i || bytestream2_get_bytes_left(&gb) < 2)

                return bytestream2_tell(&gb);

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

                *pd++ = bytestream2_get_byteu(&gb);

                *pd++ = bytestream2_get_byteu(&gb);

            }

            bytestream2_skip(&gb, 2);

        }

        i += l;

    } while (i < src_count);

    return bytestream2_tell(&gb);

}


static int recheck_discard_flags(AVFormatContext *s, int first)

{

    HLSContext *c = s->priv_data;

    int i, changed = 0;

    /* Check if any new streams are needed */

    for (i = 0; i < c->n_playlists; i++)

        c->playlists[i]->cur_needed = 0;

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

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

        struct playlist *pls = c->playlists[s->streams[i]->id];

        if (st->discard < AVDISCARD_ALL)

            pls->cur_needed = 1;

    }

    for (i = 0; i < c->n_playlists; i++) {

        struct playlist *pls = c->playlists[i];

        if (pls->cur_needed && !pls->needed) {

            pls->needed = 1;

            changed = 1;

            pls->cur_seq_no = select_cur_seq_no(c, pls);

            pls->pb.eof_reached = 0;

            if (c->cur_timestamp != AV_NOPTS_VALUE) {

                /* catch up */

                pls->seek_timestamp = c->cur_timestamp;

                pls->seek_flags = AVSEEK_FLAG_ANY;

                pls->seek_stream_index = -1;

            }

            av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);

        } else if (first && !pls->cur_needed && pls->needed) {

            if (pls->input)

                ff_format_io_close(pls->parent, &pls->input);

            pls->needed = 0;

            changed = 1;

            av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);

        }

    }

    return changed;

}


static int tpm_passthrough_unix_transfer(int tpm_fd,

                                         const TPMLocality *locty_data)

{

    return tpm_passthrough_unix_tx_bufs(tpm_fd,

                                        locty_data->w_buffer.buffer,

                                        locty_data->w_offset,

                                        locty_data->r_buffer.buffer,

                                        locty_data->r_buffer.size);

}


void sh4_translate_init(void)

{

    int i;

    static const char * const gregnames[24] = {

        "R0_BANK0", "R1_BANK0", "R2_BANK0", "R3_BANK0",

        "R4_BANK0", "R5_BANK0", "R6_BANK0", "R7_BANK0",

        "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15",

        "R0_BANK1", "R1_BANK1", "R2_BANK1", "R3_BANK1",

        "R4_BANK1", "R5_BANK1", "R6_BANK1", "R7_BANK1"

    };

    static const char * const fregnames[32] = {

         "FPR0_BANK0",  "FPR1_BANK0",  "FPR2_BANK0",  "FPR3_BANK0",

         "FPR4_BANK0",  "FPR5_BANK0",  "FPR6_BANK0",  "FPR7_BANK0",

         "FPR8_BANK0",  "FPR9_BANK0", "FPR10_BANK0", "FPR11_BANK0",

        "FPR12_BANK0", "FPR13_BANK0", "FPR14_BANK0", "FPR15_BANK0",

         "FPR0_BANK1",  "FPR1_BANK1",  "FPR2_BANK1",  "FPR3_BANK1",

         "FPR4_BANK1",  "FPR5_BANK1",  "FPR6_BANK1",  "FPR7_BANK1",

         "FPR8_BANK1",  "FPR9_BANK1", "FPR10_BANK1", "FPR11_BANK1",

        "FPR12_BANK1", "FPR13_BANK1", "FPR14_BANK1", "FPR15_BANK1",

    };

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

        cpu_gregs[i] = tcg_global_mem_new_i32(cpu_env,

                                              offsetof(CPUSH4State, gregs[i]),

                                              gregnames[i]);

    }

    memcpy(cpu_gregs + 24, cpu_gregs + 8, 8 * sizeof(TCGv));

    cpu_pc = tcg_global_mem_new_i32(cpu_env,

                                    offsetof(CPUSH4State, pc), "PC");

    cpu_sr = tcg_global_mem_new_i32(cpu_env,

                                    offsetof(CPUSH4State, sr), "SR");

    cpu_sr_m = tcg_global_mem_new_i32(cpu_env,

                                      offsetof(CPUSH4State, sr_m), "SR_M");

    cpu_sr_q = tcg_global_mem_new_i32(cpu_env,

                                      offsetof(CPUSH4State, sr_q), "SR_Q");

    cpu_sr_t = tcg_global_mem_new_i32(cpu_env,

                                      offsetof(CPUSH4State, sr_t), "SR_T");

    cpu_ssr = tcg_global_mem_new_i32(cpu_env,

                                     offsetof(CPUSH4State, ssr), "SSR");

    cpu_spc = tcg_global_mem_new_i32(cpu_env,

                                     offsetof(CPUSH4State, spc), "SPC");

    cpu_gbr = tcg_global_mem_new_i32(cpu_env,

                                     offsetof(CPUSH4State, gbr), "GBR");

    cpu_vbr = tcg_global_mem_new_i32(cpu_env,

                                     offsetof(CPUSH4State, vbr), "VBR");

    cpu_sgr = tcg_global_mem_new_i32(cpu_env,

                                     offsetof(CPUSH4State, sgr), "SGR");

    cpu_dbr = tcg_global_mem_new_i32(cpu_env,

                                     offsetof(CPUSH4State, dbr), "DBR");

    cpu_mach = tcg_global_mem_new_i32(cpu_env,

                                      offsetof(CPUSH4State, mach), "MACH");

    cpu_macl = tcg_global_mem_new_i32(cpu_env,

                                      offsetof(CPUSH4State, macl), "MACL");

    cpu_pr = tcg_global_mem_new_i32(cpu_env,

                                    offsetof(CPUSH4State, pr), "PR");

    cpu_fpscr = tcg_global_mem_new_i32(cpu_env,

                                       offsetof(CPUSH4State, fpscr), "FPSCR");

    cpu_fpul = tcg_global_mem_new_i32(cpu_env,

                                      offsetof(CPUSH4State, fpul), "FPUL");

    cpu_flags = tcg_global_mem_new_i32(cpu_env,

				       offsetof(CPUSH4State, flags), "_flags_");

    cpu_delayed_pc = tcg_global_mem_new_i32(cpu_env,

					    offsetof(CPUSH4State, delayed_pc),

					    "_delayed_pc_");

    cpu_delayed_cond = tcg_global_mem_new_i32(cpu_env,

                                              offsetof(CPUSH4State,

                                                       delayed_cond),

                                              "_delayed_cond_");

    cpu_ldst = tcg_global_mem_new_i32(cpu_env,

				      offsetof(CPUSH4State, ldst), "_ldst_");

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

        cpu_fregs[i] = tcg_global_mem_new_i32(cpu_env,

                                              offsetof(CPUSH4State, fregs[i]),

                                              fregnames[i]);

}


AVStream *add_audio_stream(AVFormatContext *oc, int codec_id)

{

    AVCodec *codec;

    AVCodecContext *c;

    AVStream *st;

    st = av_new_stream(oc, 1);

    if (!st) {

        fprintf(stderr, "Could not alloc stream\n");

        exit(1);

    }

    /* find the MP2 encoder */

    codec = avcodec_find_encoder(codec_id);

    if (!codec) {

        fprintf(stderr, "codec not found\n");

        exit(1);

    }

    c = &st->codec;

    c->codec_type = CODEC_TYPE_AUDIO;

    /* put sample parameters */

    c->bit_rate = 64000;

    c->sample_rate = 44100;

    c->channels = 2;

    /* open it */

    if (avcodec_open(c, codec) < 0) {

        fprintf(stderr, "could not open codec\n");

        exit(1);

    }

    /* init signal generator */

    t = 0;

    tincr = 2 * M_PI * 440.0 / c->sample_rate;

    audio_outbuf_size = 10000;

    audio_outbuf = malloc(audio_outbuf_size);

    /* ugly hack for PCM codecs (will be removed ASAP with new PCM

       support to compute the input frame size in samples */

    if (c->frame_size <= 1) {

        audio_input_frame_size = audio_outbuf_size / c->channels;

        switch(st->codec.codec_id) {

        case CODEC_ID_PCM_S16LE:

        case CODEC_ID_PCM_S16BE:

        case CODEC_ID_PCM_U16LE:

        case CODEC_ID_PCM_U16BE:

            audio_input_frame_size >>= 1;

            break;

        default:

            break;

        }

    } else {

        audio_input_frame_size = c->frame_size;

    }

    samples = malloc(audio_input_frame_size * 2 * c->channels);

    return st;

}


static av_cold int libopenjpeg_encode_init(AVCodecContext *avctx)

{

    LibOpenJPEGContext *ctx = avctx->priv_data;

    int err = AVERROR(ENOMEM);

    opj_set_default_encoder_parameters(&ctx->enc_params);

    ctx->enc_params.cp_rsiz = ctx->profile;

    ctx->enc_params.mode = !!avctx->global_quality;

    ctx->enc_params.cp_cinema = ctx->cinema_mode;

    ctx->enc_params.prog_order = ctx->prog_order;

    ctx->enc_params.numresolution = ctx->numresolution;

    ctx->enc_params.cp_disto_alloc = ctx->disto_alloc;

    ctx->enc_params.cp_fixed_alloc = ctx->fixed_alloc;

    ctx->enc_params.cp_fixed_quality = ctx->fixed_quality;

    ctx->enc_params.tcp_numlayers = ctx->numlayers;

    ctx->enc_params.tcp_rates[0] = FFMAX(avctx->compression_level, 0) * 2;

    if (ctx->cinema_mode > 0) {

        cinema_parameters(&ctx->enc_params);

    }

    ctx->compress = opj_create_compress(ctx->format);

    if (!ctx->compress) {

        av_log(avctx, AV_LOG_ERROR, "Error creating the compressor\n");

        return AVERROR(ENOMEM);

    }

    ctx->image = mj2_create_image(avctx, &ctx->enc_params);

    if (!ctx->image) {

        av_log(avctx, AV_LOG_ERROR, "Error creating the mj2 image\n");

        err = AVERROR(EINVAL);

        goto fail;

    }

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame) {

        av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");

        goto fail;

    }

    memset(&ctx->event_mgr, 0, sizeof(opj_event_mgr_t));

    ctx->event_mgr.info_handler    = info_callback;

    ctx->event_mgr.error_handler = error_callback;

    ctx->event_mgr.warning_handler = warning_callback;

    opj_set_event_mgr((opj_common_ptr) ctx->compress, &ctx->event_mgr, avctx);

    return 0;

fail:

    opj_destroy_compress(ctx->compress);

    ctx->compress = NULL;

    opj_image_destroy(ctx->image);

    ctx->image = NULL;

    av_freep(&avctx->coded_frame);

    return err;

}


static inline unsigned int msi_nr_vectors(uint16_t flags)

{

    return 1U <<

        ((flags & PCI_MSI_FLAGS_QSIZE) >> (ffs(PCI_MSI_FLAGS_QSIZE) - 1));

}


static void openrisc_sim_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    OpenRISCCPU *cpu = NULL;

    MemoryRegion *ram;

    int n;

    if (!cpu_model) {

        cpu_model = "or1200";

    }

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

        cpu = OPENRISC_CPU(cpu_generic_init(TYPE_OPENRISC_CPU, cpu_model));

        qemu_register_reset(main_cpu_reset, cpu);

        main_cpu_reset(cpu);

    }

    ram = g_malloc(sizeof(*ram));

    memory_region_init_ram(ram, NULL, "openrisc.ram", ram_size, &error_fatal);

    memory_region_add_subregion(get_system_memory(), 0, ram);

    cpu_openrisc_pic_init(cpu);

    cpu_openrisc_clock_init(cpu);

    serial_mm_init(get_system_memory(), 0x90000000, 0, cpu->env.irq[2],

                   115200, serial_hds[0], DEVICE_NATIVE_ENDIAN);

    if (nd_table[0].used) {

        openrisc_sim_net_init(get_system_memory(), 0x92000000,

                              0x92000400, cpu->env.irq[4], nd_table);

    }

    cpu_openrisc_load_kernel(ram_size, kernel_filename, cpu);

}


static void ohci_reset(void *opaque)

{

    OHCIState *ohci = opaque;

    OHCIPort *port;

    int i;

    ohci_bus_stop(ohci);

    ohci->ctl = 0;

    ohci->old_ctl = 0;

    ohci->status = 0;

    ohci->intr_status = 0;

    ohci->intr = OHCI_INTR_MIE;

    ohci->hcca = 0;

    ohci->ctrl_head = ohci->ctrl_cur = 0;

    ohci->bulk_head = ohci->bulk_cur = 0;

    ohci->per_cur = 0;

    ohci->done = 0;

    ohci->done_count = 7;

    /* FSMPS is marked TBD in OCHI 1.0, what gives ffs?

     * I took the value linux sets ...

     */

    ohci->fsmps = 0x2778;

    ohci->fi = 0x2edf;

    ohci->fit = 0;

    ohci->frt = 0;

    ohci->frame_number = 0;

    ohci->pstart = 0;

    ohci->lst = OHCI_LS_THRESH;

    ohci->rhdesc_a = OHCI_RHA_NPS | ohci->num_ports;

    ohci->rhdesc_b = 0x0; /* Impl. specific */

    ohci->rhstatus = 0;

    for (i = 0; i < ohci->num_ports; i++)

      {

        port = &ohci->rhport[i];

        port->ctrl = 0;

        if (port->port.dev) {

            usb_attach(&port->port, port->port.dev);

        }

      }

    if (ohci->async_td) {

        usb_cancel_packet(&ohci->usb_packet);

        ohci->async_td = 0;

    }

    DPRINTF("usb-ohci: Reset %s\n", ohci->name);

}


uint64_t helper_fsub(CPUPPCState *env, uint64_t arg1, uint64_t arg2)

{

    CPU_DoubleU farg1, farg2;

    farg1.ll = arg1;

    farg2.ll = arg2;

    if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d) &&

                 float64_is_neg(farg1.d) == float64_is_neg(farg2.d))) {

        /* Magnitude subtraction of infinities */

        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);

    } else {

        if (unlikely(float64_is_signaling_nan(farg1.d) ||

                     float64_is_signaling_nan(farg2.d))) {

            /* sNaN subtraction */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

        }

        farg1.d = float64_sub(farg1.d, farg2.d, &env->fp_status);

    }

    return farg1.ll;

}


static int net_socket_connect_init(NetClientState *peer,

                                   const char *model,

                                   const char *name,

                                   const char *host_str)

{

    NetSocketState *s;

    int fd, connected, ret;

    struct sockaddr_in saddr;

    if (parse_host_port(&saddr, host_str) < 0)

        return -1;

    fd = qemu_socket(PF_INET, SOCK_STREAM, 0);

    if (fd < 0) {

        perror("socket");

        return -1;

    }

    qemu_set_nonblock(fd);

    connected = 0;

    for(;;) {

        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));

        if (ret < 0) {

            if (errno == EINTR || errno == EWOULDBLOCK) {

                /* continue */

            } else if (errno == EINPROGRESS ||

                       errno == EALREADY ||

                       errno == EINVAL) {

                break;

            } else {

                perror("connect");

                closesocket(fd);

                return -1;

            }

        } else {

            connected = 1;

            break;

        }

    }

    s = net_socket_fd_init(peer, model, name, fd, connected);

    if (!s)

        return -1;

    snprintf(s->nc.info_str, sizeof(s->nc.info_str),

             "socket: connect to %s:%d",

             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));

    return 0;

}


static int64_t load_kernel (void)

{

    int64_t kernel_entry, kernel_high;

    long initrd_size;

    ram_addr_t initrd_offset;

    int big_endian;

    uint32_t *prom_buf;

    long prom_size;

    int prom_index = 0;

    uint64_t (*xlate_to_kseg0) (void *opaque, uint64_t addr);

#ifdef TARGET_WORDS_BIGENDIAN

    big_endian = 1;

#else

    big_endian = 0;

#endif

    if (load_elf(loaderparams.kernel_filename, cpu_mips_kseg0_to_phys, NULL,

                 (uint64_t *)&kernel_entry, NULL, (uint64_t *)&kernel_high,

                 big_endian, ELF_MACHINE, 1) < 0) {

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

                loaderparams.kernel_filename);

        exit(1);

    }

    /* Sanity check where the kernel has been linked */

    if (kvm_enabled()) {

        if (kernel_entry & 0x80000000ll) {

            error_report("KVM guest kernels must be linked in useg. "

                         "Did you forget to enable CONFIG_KVM_GUEST?");

            exit(1);

        }

        xlate_to_kseg0 = cpu_mips_kvm_um_phys_to_kseg0;

    } else {

        if (!(kernel_entry & 0x80000000ll)) {

            error_report("KVM guest kernels aren't supported with TCG. "

                         "Did you unintentionally enable CONFIG_KVM_GUEST?");

            exit(1);

        }

        xlate_to_kseg0 = cpu_mips_phys_to_kseg0;

    }

    /* load initrd */

    initrd_size = 0;

    initrd_offset = 0;

    if (loaderparams.initrd_filename) {

        initrd_size = get_image_size (loaderparams.initrd_filename);

        if (initrd_size > 0) {

            initrd_offset = (kernel_high + ~INITRD_PAGE_MASK) & INITRD_PAGE_MASK;

            if (initrd_offset + initrd_size > ram_size) {

                fprintf(stderr,

                        "qemu: memory too small for initial ram disk '%s'\n",

                        loaderparams.initrd_filename);

                exit(1);

            }

            initrd_size = load_image_targphys(loaderparams.initrd_filename,

                                              initrd_offset,

                                              ram_size - initrd_offset);

        }

        if (initrd_size == (target_ulong) -1) {

            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                    loaderparams.initrd_filename);

            exit(1);

        }

    }

    /* Setup prom parameters. */

    prom_size = ENVP_NB_ENTRIES * (sizeof(int32_t) + ENVP_ENTRY_SIZE);

    prom_buf = g_malloc(prom_size);

    prom_set(prom_buf, prom_index++, "%s", loaderparams.kernel_filename);

    if (initrd_size > 0) {

        prom_set(prom_buf, prom_index++, "rd_start=0x%" PRIx64 " rd_size=%li %s",

                 xlate_to_kseg0(NULL, initrd_offset), initrd_size,

                 loaderparams.kernel_cmdline);

    } else {

        prom_set(prom_buf, prom_index++, "%s", loaderparams.kernel_cmdline);

    }

    prom_set(prom_buf, prom_index++, "memsize");

    prom_set(prom_buf, prom_index++, "%i",

             MIN(loaderparams.ram_size, 256 << 20));

    prom_set(prom_buf, prom_index++, "modetty0");

    prom_set(prom_buf, prom_index++, "38400n8r");

    prom_set(prom_buf, prom_index++, NULL);

    rom_add_blob_fixed("prom", prom_buf, prom_size,

                       cpu_mips_kseg0_to_phys(NULL, ENVP_ADDR));

    return kernel_entry;

}


static void test_validate_fail_union_anon(TestInputVisitorData *data,

                                          const void *unused)

{

    UserDefAnonUnion *tmp = NULL;

    Visitor *v;

    Error *errp = NULL;

    v = validate_test_init(data, "3.14");

    visit_type_UserDefAnonUnion(v, &tmp, NULL, &errp);

    g_assert(error_is_set(&errp));

    qapi_free_UserDefAnonUnion(tmp);

}


static int vhost_virtqueue_init(struct vhost_dev *dev,

                                struct vhost_virtqueue *vq, int n)

{

    struct vhost_vring_file file = {

        .index = n,

    };

    int r = event_notifier_init(&vq->masked_notifier, 0);

    if (r < 0) {

        return r;

    }

    file.fd = event_notifier_get_fd(&vq->masked_notifier);

    r = dev->vhost_ops->vhost_call(dev, VHOST_SET_VRING_CALL, &file);

    if (r) {

        r = -errno;

        goto fail_call;

    }

    return 0;

fail_call:

    event_notifier_cleanup(&vq->masked_notifier);

    return r;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *src_buffer)

{

    AVFilterContext  *ctx = inlink->dst;

    ATempoContext *atempo = ctx->priv;

    AVFilterLink *outlink = ctx->outputs[0];

    int ret = 0;

    int n_in = src_buffer->nb_samples;

    int n_out = (int)(0.5 + ((double)n_in) / atempo->tempo);

    const uint8_t *src = src_buffer->data[0];

    const uint8_t *src_end = src + n_in * atempo->stride;

    while (src < src_end) {

        if (!atempo->dst_buffer) {

            atempo->dst_buffer = ff_get_audio_buffer(outlink, n_out);

            if (!atempo->dst_buffer)

                return AVERROR(ENOMEM);

            av_frame_copy_props(atempo->dst_buffer, src_buffer);

            atempo->dst = atempo->dst_buffer->data[0];

            atempo->dst_end = atempo->dst + n_out * atempo->stride;

        }

        yae_apply(atempo, &src, src_end, &atempo->dst, atempo->dst_end);

        if (atempo->dst == atempo->dst_end) {

            int n_samples = ((atempo->dst - atempo->dst_buffer->data[0]) /

                             atempo->stride);

            ret = push_samples(atempo, outlink, n_samples);

            if (ret < 0)

                goto end;

        }

    }

    atempo->nsamples_in += n_in;

end:

    av_frame_free(&src_buffer);

    return ret;

}


struct vhost_net *vhost_net_init(VhostNetOptions *options)

{

    int r;

    bool backend_kernel = options->backend_type == VHOST_BACKEND_TYPE_KERNEL;

    struct vhost_net *net = g_malloc(sizeof *net);

    if (!options->net_backend) {

        fprintf(stderr, "vhost-net requires net backend to be setup\n");

        goto fail;

    }

    if (backend_kernel) {

        r = vhost_net_get_fd(options->net_backend);

        if (r < 0) {

            goto fail;

        }

        net->dev.backend_features = qemu_has_vnet_hdr(options->net_backend)

            ? 0 : (1ULL << VHOST_NET_F_VIRTIO_NET_HDR);

        net->backend = r;

    } else {

        net->dev.backend_features = 0;

        net->backend = -1;

    }

    net->nc = options->net_backend;

    net->dev.nvqs = 2;

    net->dev.vqs = net->vqs;

    net->dev.vq_index = net->nc->queue_index;

    r = vhost_dev_init(&net->dev, options->opaque,

                       options->backend_type, options->force);

    if (r < 0) {

        goto fail;

    }

    if (backend_kernel) {

        if (!qemu_has_vnet_hdr_len(options->net_backend,

                               sizeof(struct virtio_net_hdr_mrg_rxbuf))) {

            net->dev.features &= ~(1ULL << VIRTIO_NET_F_MRG_RXBUF);

        }

        if (~net->dev.features & net->dev.backend_features) {

            fprintf(stderr, "vhost lacks feature mask %" PRIu64

                   " for backend\n",

                   (uint64_t)(~net->dev.features & net->dev.backend_features));

            vhost_dev_cleanup(&net->dev);

            goto fail;

        }

    }

    /* Set sane init value. Override when guest acks. */

    vhost_net_ack_features(net, 0);

    return net;

fail:

    g_free(net);

    return NULL;

}


static USBDevice *usb_msd_init(const char *filename)

{

    static int nr=0;

    char id[8];

    QemuOpts *opts;

    DriveInfo *dinfo;

    USBDevice *dev;

    int fatal_error;

    const char *p1;

    char fmt[32];

    /* parse -usbdevice disk: syntax into drive opts */

    snprintf(id, sizeof(id), "usb%d", nr++);

    opts = qemu_opts_create(&qemu_drive_opts, id, 0);

    p1 = strchr(filename, ':');

    if (p1++) {

        const char *p2;

        if (strstart(filename, "format=", &p2)) {

            int len = MIN(p1 - p2, sizeof(fmt));

            pstrcpy(fmt, len, p2);

            qemu_opt_set(opts, "format", fmt);

        } else if (*filename != ':') {

            printf("unrecognized USB mass-storage option %s\n", filename);

        filename = p1;

    if (!*filename) {

        printf("block device specification needed\n");

    qemu_opt_set(opts, "file", filename);

    qemu_opt_set(opts, "if", "none");

    /* create host drive */

    dinfo = drive_init(opts, NULL, &fatal_error);

    if (!dinfo) {

        qemu_opts_del(opts);

    /* create guest device */

    dev = usb_create(NULL /* FIXME */, "usb-storage");

    qdev_prop_set_drive(&dev->qdev, "drive", dinfo);

    if (qdev_init(&dev->qdev) < 0)

    return dev;


static inline void rv34_mc(RV34DecContext *r, const int block_type,

                          const int xoff, const int yoff, int mv_off,

                          const int width, const int height, int dir,

                          const int thirdpel, int weighted,

                          qpel_mc_func (*qpel_mc)[16],

                          h264_chroma_mc_func (*chroma_mc))

{

    MpegEncContext *s = &r->s;

    uint8_t *Y, *U, *V, *srcY, *srcU, *srcV;

    int dxy, mx, my, umx, umy, lx, ly, uvmx, uvmy, src_x, src_y, uvsrc_x, uvsrc_y;

    int mv_pos = s->mb_x * 2 + s->mb_y * 2 * s->b8_stride + mv_off;

    int is16x16 = 1;

    if(thirdpel){

        int chroma_mx, chroma_my;

        mx = (s->current_picture_ptr->f.motion_val[dir][mv_pos][0] + (3 << 24)) / 3 - (1 << 24);

        my = (s->current_picture_ptr->f.motion_val[dir][mv_pos][1] + (3 << 24)) / 3 - (1 << 24);

        lx = (s->current_picture_ptr->f.motion_val[dir][mv_pos][0] + (3 << 24)) % 3;

        ly = (s->current_picture_ptr->f.motion_val[dir][mv_pos][1] + (3 << 24)) % 3;

        chroma_mx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] / 2;

        chroma_my = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] / 2;

        umx = (chroma_mx + (3 << 24)) / 3 - (1 << 24);

        umy = (chroma_my + (3 << 24)) / 3 - (1 << 24);

        uvmx = chroma_coeffs[(chroma_mx + (3 << 24)) % 3];

        uvmy = chroma_coeffs[(chroma_my + (3 << 24)) % 3];

    }else{

        int cx, cy;

        mx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] >> 2;

        my = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] >> 2;

        lx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] & 3;

        ly = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] & 3;

        cx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] / 2;

        cy = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] / 2;

        umx = cx >> 2;

        umy = cy >> 2;

        uvmx = (cx & 3) << 1;

        uvmy = (cy & 3) << 1;

        //due to some flaw RV40 uses the same MC compensation routine for H2V2 and H3V3

        if(uvmx == 6 && uvmy == 6)

            uvmx = uvmy = 4;

    }

    dxy = ly*4 + lx;

    srcY = dir ? s->next_picture_ptr->f.data[0] : s->last_picture_ptr->f.data[0];

    srcU = dir ? s->next_picture_ptr->f.data[1] : s->last_picture_ptr->f.data[1];

    srcV = dir ? s->next_picture_ptr->f.data[2] : s->last_picture_ptr->f.data[2];

    src_x = s->mb_x * 16 + xoff + mx;

    src_y = s->mb_y * 16 + yoff + my;

    uvsrc_x = s->mb_x * 8 + (xoff >> 1) + umx;

    uvsrc_y = s->mb_y * 8 + (yoff >> 1) + umy;

    srcY += src_y * s->linesize + src_x;

    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;

    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;

    if(   (unsigned)(src_x - !!lx*2) > s->h_edge_pos - !!lx*2 - (width <<3) - 4

       || (unsigned)(src_y - !!ly*2) > s->v_edge_pos - !!ly*2 - (height<<3) - 4){

        uint8_t *uvbuf = s->edge_emu_buffer + 22 * s->linesize;

        srcY -= 2 + 2*s->linesize;

        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, (width<<3)+6, (height<<3)+6,

                            src_x - 2, src_y - 2, s->h_edge_pos, s->v_edge_pos);

        srcY = s->edge_emu_buffer + 2 + 2*s->linesize;

        s->dsp.emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, (width<<2)+1, (height<<2)+1,

                            uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);

        s->dsp.emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, (width<<2)+1, (height<<2)+1,

                            uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);

        srcU = uvbuf;

        srcV = uvbuf + 16;

    }

    if(!weighted){

        Y = s->dest[0] + xoff      + yoff     *s->linesize;

        U = s->dest[1] + (xoff>>1) + (yoff>>1)*s->uvlinesize;

        V = s->dest[2] + (xoff>>1) + (yoff>>1)*s->uvlinesize;

    }else{

        Y = r->tmp_b_block_y [dir]     +  xoff     +  yoff    *s->linesize;

        U = r->tmp_b_block_uv[dir*2]   + (xoff>>1) + (yoff>>1)*s->uvlinesize;

        V = r->tmp_b_block_uv[dir*2+1] + (xoff>>1) + (yoff>>1)*s->uvlinesize;

    }

    if(block_type == RV34_MB_P_16x8){

        qpel_mc[1][dxy](Y, srcY, s->linesize);

        Y    += 8;

        srcY += 8;

    }else if(block_type == RV34_MB_P_8x16){

        qpel_mc[1][dxy](Y, srcY, s->linesize);

        Y    += 8 * s->linesize;

        srcY += 8 * s->linesize;

    }

    is16x16 = (block_type != RV34_MB_P_8x8) && (block_type != RV34_MB_P_16x8) && (block_type != RV34_MB_P_8x16);

    qpel_mc[!is16x16][dxy](Y, srcY, s->linesize);

    chroma_mc[2-width]   (U, srcU, s->uvlinesize, height*4, uvmx, uvmy);

    chroma_mc[2-width]   (V, srcV, s->uvlinesize, height*4, uvmx, uvmy);

}


void migrate_fd_connect(MigrationState *s)

{

    s->state = MIG_STATE_SETUP;

    trace_migrate_set_state(MIG_STATE_SETUP);

    /* This is a best 1st approximation. ns to ms */

    s->expected_downtime = max_downtime/1000000;

    s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);

    qemu_file_set_rate_limit(s->file,

                             s->bandwidth_limit / XFER_LIMIT_RATIO);

    qemu_thread_create(&s->thread, migration_thread, s,

                       QEMU_THREAD_JOINABLE);

    notifier_list_notify(&migration_state_notifiers, s);

}


static void ppc405cr_clk_setup (ppc405cr_cpc_t *cpc)

{

    uint64_t VCO_out, PLL_out;

    uint32_t CPU_clk, TMR_clk, SDRAM_clk, PLB_clk, OPB_clk, EXT_clk, UART_clk;

    int M, D0, D1, D2;

    D0 = ((cpc->pllmr >> 26) & 0x3) + 1; /* CBDV */

    if (cpc->pllmr & 0x80000000) {

        D1 = (((cpc->pllmr >> 20) - 1) & 0xF) + 1; /* FBDV */

        D2 = 8 - ((cpc->pllmr >> 16) & 0x7); /* FWDVA */

        M = D0 * D1 * D2;

        VCO_out = cpc->sysclk * M;

        if (VCO_out < 400000000 || VCO_out > 800000000) {

            /* PLL cannot lock */

            cpc->pllmr &= ~0x80000000;

            goto bypass_pll;

        }

        PLL_out = VCO_out / D2;

    } else {

        /* Bypass PLL */

    bypass_pll:

        M = D0;

        PLL_out = cpc->sysclk * M;

    }

    CPU_clk = PLL_out;

    if (cpc->cr1 & 0x00800000)

        TMR_clk = cpc->sysclk; /* Should have a separate clock */

    else

        TMR_clk = CPU_clk;

    PLB_clk = CPU_clk / D0;

    SDRAM_clk = PLB_clk;

    D0 = ((cpc->pllmr >> 10) & 0x3) + 1;

    OPB_clk = PLB_clk / D0;

    D0 = ((cpc->pllmr >> 24) & 0x3) + 2;

    EXT_clk = PLB_clk / D0;

    D0 = ((cpc->cr0 >> 1) & 0x1F) + 1;

    UART_clk = CPU_clk / D0;

    /* Setup CPU clocks */

    clk_setup(&cpc->clk_setup[PPC405CR_CPU_CLK], CPU_clk);

    /* Setup time-base clock */

    clk_setup(&cpc->clk_setup[PPC405CR_TMR_CLK], TMR_clk);

    /* Setup PLB clock */

    clk_setup(&cpc->clk_setup[PPC405CR_PLB_CLK], PLB_clk);

    /* Setup SDRAM clock */

    clk_setup(&cpc->clk_setup[PPC405CR_SDRAM_CLK], SDRAM_clk);

    /* Setup OPB clock */

    clk_setup(&cpc->clk_setup[PPC405CR_OPB_CLK], OPB_clk);

    /* Setup external clock */

    clk_setup(&cpc->clk_setup[PPC405CR_EXT_CLK], EXT_clk);

    /* Setup UART clock */

    clk_setup(&cpc->clk_setup[PPC405CR_UART_CLK], UART_clk);

}


static uint64_t cmd646_cmd_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

    CMD646BAR *cmd646bar = opaque;

    if (addr != 2 || size != 1) {

        return ((uint64_t)1 << (size * 8)) - 1;

    }

    return ide_status_read(cmd646bar->bus, addr + 2);

}


static uint64_t hpet_ram_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

    HPETState *s = opaque;

    uint64_t cur_tick, index;

    DPRINTF("qemu: Enter hpet_ram_readl at %" PRIx64 "\n", addr);

    index = addr;

    /*address range of all TN regs*/

    if (index >= 0x100 && index <= 0x3ff) {

        uint8_t timer_id = (addr - 0x100) / 0x20;

        HPETTimer *timer = &s->timer[timer_id];

        if (timer_id > s->num_timers) {

            DPRINTF("qemu: timer id out of range\n");

            return 0;

        }

        switch ((addr - 0x100) % 0x20) {

        case HPET_TN_CFG:

            return timer->config;

        case HPET_TN_CFG + 4: // Interrupt capabilities

            return timer->config >> 32;

        case HPET_TN_CMP: // comparator register

            return timer->cmp;

        case HPET_TN_CMP + 4:

            return timer->cmp >> 32;

        case HPET_TN_ROUTE:

            return timer->fsb;

        case HPET_TN_ROUTE + 4:

            return timer->fsb >> 32;

        default:

            DPRINTF("qemu: invalid hpet_ram_readl\n");

            break;

        }

    } else {

        switch (index) {

        case HPET_ID:

            return s->capability;

        case HPET_PERIOD:

            return s->capability >> 32;

        case HPET_CFG:

            return s->config;

        case HPET_CFG + 4:

            DPRINTF("qemu: invalid HPET_CFG + 4 hpet_ram_readl\n");

            return 0;

        case HPET_COUNTER:

            if (hpet_enabled(s)) {

                cur_tick = hpet_get_ticks(s);

            } else {

                cur_tick = s->hpet_counter;

            }

            DPRINTF("qemu: reading counter  = %" PRIx64 "\n", cur_tick);

            return cur_tick;

        case HPET_COUNTER + 4:

            if (hpet_enabled(s)) {

                cur_tick = hpet_get_ticks(s);

            } else {

                cur_tick = s->hpet_counter;

            }

            DPRINTF("qemu: reading counter + 4  = %" PRIx64 "\n", cur_tick);

            return cur_tick >> 32;

        case HPET_STATUS:

            return s->isr;

        default:

            DPRINTF("qemu: invalid hpet_ram_readl\n");

            break;

        }

    }

    return 0;

}


static void virtio_init_pci(VirtIOPCIProxy *proxy, VirtIODevice *vdev,

                            uint16_t vendor, uint16_t device,

                            uint16_t class_code, uint8_t pif)

{

    uint8_t *config;

    uint32_t size;

    proxy->vdev = vdev;

    config = proxy->pci_dev.config;

    pci_config_set_vendor_id(config, vendor);

    pci_config_set_device_id(config, device);

    config[0x08] = VIRTIO_PCI_ABI_VERSION;

    config[0x09] = pif;

    pci_config_set_class(config, class_code);

    config[0x2c] = vendor & 0xFF;

    config[0x2d] = (vendor >> 8) & 0xFF;

    config[0x2e] = vdev->device_id & 0xFF;

    config[0x2f] = (vdev->device_id >> 8) & 0xFF;

    config[0x3d] = 1;

    if (vdev->nvectors && !msix_init(&proxy->pci_dev, vdev->nvectors, 1, 0)) {

        pci_register_bar(&proxy->pci_dev, 1,

                         msix_bar_size(&proxy->pci_dev),

                         PCI_BASE_ADDRESS_SPACE_MEMORY,

                         msix_mmio_map);

    } else

        vdev->nvectors = 0;

    proxy->pci_dev.config_write = virtio_write_config;

    size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev) + vdev->config_len;

    if (size & (size-1))

        size = 1 << qemu_fls(size);

    pci_register_bar(&proxy->pci_dev, 0, size, PCI_BASE_ADDRESS_SPACE_IO,

                           virtio_map);

    if (!kvm_has_many_ioeventfds()) {

        proxy->flags &= ~VIRTIO_PCI_FLAG_USE_IOEVENTFD;

    }

    virtio_bind_device(vdev, &virtio_pci_bindings, proxy);

    proxy->host_features |= 0x1 << VIRTIO_F_NOTIFY_ON_EMPTY;

    proxy->host_features |= 0x1 << VIRTIO_F_BAD_FEATURE;

    proxy->host_features = vdev->get_features(vdev, proxy->host_features);

}


static int usb_device_add(const char *devname, int is_hotplug)

{

    const char *p;

    USBDevice *dev;

    if (!free_usb_ports)

        return -1;

    if (strstart(devname, "host:", &p)) {

        dev = usb_host_device_open(p);

    } else if (!strcmp(devname, "mouse")) {

        dev = usb_mouse_init();

    } else if (!strcmp(devname, "tablet")) {

        dev = usb_tablet_init();

    } else if (!strcmp(devname, "keyboard")) {

        dev = usb_keyboard_init();

    } else if (strstart(devname, "disk:", &p)) {

        BlockDriverState *bs;

        dev = usb_msd_init(p, &bs);

        if (!dev)

            return -1;

        if (bdrv_key_required(bs)) {

            autostart = 0;

            if (is_hotplug && monitor_read_bdrv_key(bs) < 0) {

                dev->handle_destroy(dev);

                return -1;

            }

        }

    } else if (!strcmp(devname, "wacom-tablet")) {

        dev = usb_wacom_init();

    } else if (strstart(devname, "serial:", &p)) {

        dev = usb_serial_init(p);

#ifdef CONFIG_BRLAPI

    } else if (!strcmp(devname, "braille")) {

        dev = usb_baum_init();

#endif

    } else if (strstart(devname, "net:", &p)) {

        int nic = nb_nics;

        if (net_client_init("nic", p) < 0)

            return -1;

        nd_table[nic].model = "usb";

        dev = usb_net_init(&nd_table[nic]);

    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {

        dev = usb_bt_init(devname[2] ? hci_init(p) :

                        bt_new_hci(qemu_find_bt_vlan(0)));

    } else {

        return -1;

    }

    if (!dev)

        return -1;

    return usb_device_add_dev(dev);

}


void ioinst_handle_msch(S390CPU *cpu, uint64_t reg1, uint32_t ipb)

{

    int cssid, ssid, schid, m;

    SubchDev *sch;

    SCHIB schib;

    uint64_t addr;

    int ret = -ENODEV;

    int cc;

    CPUS390XState *env = &cpu->env;

    uint8_t ar;

    addr = decode_basedisp_s(env, ipb, &ar);

    if (addr & 3) {

        program_interrupt(env, PGM_SPECIFICATION, 2);

        return;

    }

    if (s390_cpu_virt_mem_read(cpu, addr, ar, &schib, sizeof(schib))) {

        return;

    }

    if (ioinst_disassemble_sch_ident(reg1, &m, &cssid, &ssid, &schid) ||

        !ioinst_schib_valid(&schib)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return;

    }

    trace_ioinst_sch_id("msch", cssid, ssid, schid);

    sch = css_find_subch(m, cssid, ssid, schid);

    if (sch && css_subch_visible(sch)) {

        ret = css_do_msch(sch, &schib);

    }

    switch (ret) {

    case -ENODEV:

        cc = 3;

        break;

    case -EBUSY:

        cc = 2;

        break;

    case 0:

        cc = 0;

        break;

    default:

        cc = 1;

        break;

    }

    setcc(cpu, cc);

}


int load_uimage(const char *filename, target_ulong *ep, target_ulong *loadaddr,

                int *is_linux)

{

    int fd;

    int size;

    uboot_image_header_t h;

    uboot_image_header_t *hdr = &h;

    uint8_t *data = NULL;

    int ret = -1;

    fd = open(filename, O_RDONLY | O_BINARY);

    if (fd < 0)

        return -1;

    size = read(fd, hdr, sizeof(uboot_image_header_t));

    if (size < 0)

        goto out;

    bswap_uboot_header(hdr);

    if (hdr->ih_magic != IH_MAGIC)

        goto out;

    /* TODO: Implement Multi-File images.  */

    if (hdr->ih_type == IH_TYPE_MULTI) {

        fprintf(stderr, "Unable to load multi-file u-boot images\n");

        goto out;

    }

    switch (hdr->ih_comp) {

    case IH_COMP_NONE:

    case IH_COMP_GZIP:

        break;

    default:

        fprintf(stderr,

                "Unable to load u-boot images with compression type %d\n",

                hdr->ih_comp);

        goto out;

    }

    /* TODO: Check CPU type.  */

    if (is_linux) {

        if (hdr->ih_type == IH_TYPE_KERNEL && hdr->ih_os == IH_OS_LINUX)

            *is_linux = 1;

        else

            *is_linux = 0;

    }

    *ep = hdr->ih_ep;

    data = qemu_malloc(hdr->ih_size);

    if (!data)

        goto out;

    if (read(fd, data, hdr->ih_size) != hdr->ih_size) {

        fprintf(stderr, "Error reading file\n");

        goto out;

    }

    if (hdr->ih_comp == IH_COMP_GZIP) {

        uint8_t *compressed_data;

        size_t max_bytes;

        ssize_t bytes;

        compressed_data = data;

        max_bytes = UBOOT_MAX_GUNZIP_BYTES;

        data = qemu_malloc(max_bytes);

        bytes = gunzip(data, max_bytes, compressed_data, hdr->ih_size);

        qemu_free(compressed_data);

        if (bytes < 0) {

            fprintf(stderr, "Unable to decompress gzipped image!\n");

            goto out;

        }

        hdr->ih_size = bytes;

    }

    cpu_physical_memory_write_rom(hdr->ih_load, data, hdr->ih_size);

    if (loadaddr)

        *loadaddr = hdr->ih_load;

    ret = hdr->ih_size;

out:

    if (data)

        qemu_free(data);

    close(fd);

    return ret;

}


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

{

    MPCContext *c = s->priv_data;

    int ret, size, size2, curbits, cur = c->curframe;

    int64_t tmp, pos;

    if (c->curframe >= c->fcount)

        return -1;

    if(c->curframe != c->lastframe + 1){

        url_fseek(s->pb, c->frames[c->curframe].pos, SEEK_SET);

        c->curbits = c->frames[c->curframe].skip;

    }

    c->lastframe = c->curframe;

    c->curframe++;

    curbits = c->curbits;

    pos = url_ftell(s->pb);

    tmp = get_le32(s->pb);

    if(curbits <= 12){

        size2 = (tmp >> (12 - curbits)) & 0xFFFFF;

    }else{

        tmp = (tmp << 32) | get_le32(s->pb);

        size2 = (tmp >> (44 - curbits)) & 0xFFFFF;

    }

    curbits += 20;

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

    size = ((size2 + curbits + 31) & ~31) >> 3;

    if(cur == c->frames_noted){

        c->frames[cur].pos = pos;

        c->frames[cur].size = size;

        c->frames[cur].skip = curbits - 20;

        av_add_index_entry(s->streams[0], cur, cur, size, 0, AVINDEX_KEYFRAME);

        c->frames_noted++;

    }

    c->curbits = (curbits + size2) & 0x1F;

    if (av_new_packet(pkt, size) < 0)

        return AVERROR(EIO);

    pkt->data[0] = curbits;

    pkt->data[1] = (c->curframe > c->fcount);

    pkt->stream_index = 0;

    pkt->pts = cur;

    ret = get_buffer(s->pb, pkt->data + 4, size);

    if(c->curbits)

        url_fseek(s->pb, -4, SEEK_CUR);

    if(ret < size){

        av_free_packet(pkt);

        return AVERROR(EIO);

    }

    pkt->size = ret + 4;

    return 0;

}


static void hpet_ram_writel(void *opaque, target_phys_addr_t addr,

                            uint32_t value)

{

    int i;

    HPETState *s = (HPETState *)opaque;

    uint64_t old_val, new_val, val, index;

    DPRINTF("qemu: Enter hpet_ram_writel at %" PRIx64 " = %#x\n", addr, value);

    index = addr;

    old_val = hpet_ram_readl(opaque, addr);

    new_val = value;

    /*address range of all TN regs*/

    if (index >= 0x100 && index <= 0x3ff) {

        uint8_t timer_id = (addr - 0x100) / 0x20;

        DPRINTF("qemu: hpet_ram_writel timer_id = %#x \n", timer_id);

        HPETTimer *timer = &s->timer[timer_id];

        if (timer_id > HPET_NUM_TIMERS - 1) {

            DPRINTF("qemu: timer id out of range\n");

            return;

        }

        switch ((addr - 0x100) % 0x20) {

            case HPET_TN_CFG:

                DPRINTF("qemu: hpet_ram_writel HPET_TN_CFG\n");

                val = hpet_fixup_reg(new_val, old_val, HPET_TN_CFG_WRITE_MASK);

                timer->config = (timer->config & 0xffffffff00000000ULL) | val;

                if (new_val & HPET_TN_32BIT) {

                    timer->cmp = (uint32_t)timer->cmp;

                    timer->period = (uint32_t)timer->period;

                }

                if (new_val & HPET_TIMER_TYPE_LEVEL) {

                    printf("qemu: level-triggered hpet not supported\n");

                    exit (-1);

                }

                break;

            case HPET_TN_CFG + 4: // Interrupt capabilities

                DPRINTF("qemu: invalid HPET_TN_CFG+4 write\n");

                break;

            case HPET_TN_CMP: // comparator register

                DPRINTF("qemu: hpet_ram_writel HPET_TN_CMP \n");

                if (timer->config & HPET_TN_32BIT)

                    new_val = (uint32_t)new_val;

                if (!timer_is_periodic(timer) ||

                           (timer->config & HPET_TN_SETVAL))

                    timer->cmp = (timer->cmp & 0xffffffff00000000ULL)

                                  | new_val;

                if (timer_is_periodic(timer)) {

                    /*

                     * FIXME: Clamp period to reasonable min value?

                     * Clamp period to reasonable max value

                     */

                    new_val &= (timer->config & HPET_TN_32BIT ? ~0u : ~0ull) >> 1;

                    timer->period = (timer->period & 0xffffffff00000000ULL)

                                     | new_val;

                }

                timer->config &= ~HPET_TN_SETVAL;

                if (hpet_enabled())

                    hpet_set_timer(timer);

                break;

            case HPET_TN_CMP + 4: // comparator register high order

                DPRINTF("qemu: hpet_ram_writel HPET_TN_CMP + 4\n");

                if (!timer_is_periodic(timer) ||

                           (timer->config & HPET_TN_SETVAL))

                    timer->cmp = (timer->cmp & 0xffffffffULL)

                                  | new_val << 32;

                else {

                    /*

                     * FIXME: Clamp period to reasonable min value?

                     * Clamp period to reasonable max value

                     */

                    new_val &= (timer->config

                                & HPET_TN_32BIT ? ~0u : ~0ull) >> 1;

                    timer->period = (timer->period & 0xffffffffULL)

                                     | new_val << 32;

                }

                timer->config &= ~HPET_TN_SETVAL;

                if (hpet_enabled())

                    hpet_set_timer(timer);

                break;

            case HPET_TN_ROUTE + 4:

                DPRINTF("qemu: hpet_ram_writel HPET_TN_ROUTE + 4\n");

                break;

            default:

                DPRINTF("qemu: invalid hpet_ram_writel\n");

                break;

        }

        return;

    } else {

        switch (index) {

            case HPET_ID:

                return;

            case HPET_CFG:

                val = hpet_fixup_reg(new_val, old_val, HPET_CFG_WRITE_MASK);

                s->config = (s->config & 0xffffffff00000000ULL) | val;

                if (activating_bit(old_val, new_val, HPET_CFG_ENABLE)) {

                    /* Enable main counter and interrupt generation. */

                    s->hpet_offset = ticks_to_ns(s->hpet_counter)

                                     - qemu_get_clock(vm_clock);

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

                        if ((&s->timer[i])->cmp != ~0ULL)

                            hpet_set_timer(&s->timer[i]);

                }

                else if (deactivating_bit(old_val, new_val, HPET_CFG_ENABLE)) {

                    /* Halt main counter and disable interrupt generation. */

                    s->hpet_counter = hpet_get_ticks();

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

                        hpet_del_timer(&s->timer[i]);

                }

                /* i8254 and RTC are disabled when HPET is in legacy mode */

                if (activating_bit(old_val, new_val, HPET_CFG_LEGACY)) {

                    hpet_pit_disable();

                } else if (deactivating_bit(old_val, new_val, HPET_CFG_LEGACY)) {

                    hpet_pit_enable();

                }

                break;

            case HPET_CFG + 4:

                DPRINTF("qemu: invalid HPET_CFG+4 write \n");

                break;

            case HPET_STATUS:

                /* FIXME: need to handle level-triggered interrupts */

                break;

            case HPET_COUNTER:

               if (hpet_enabled())

                   printf("qemu: Writing counter while HPET enabled!\n");

               s->hpet_counter = (s->hpet_counter & 0xffffffff00000000ULL)

                                  | value;

               DPRINTF("qemu: HPET counter written. ctr = %#x -> %" PRIx64 "\n",

                        value, s->hpet_counter);

               break;

            case HPET_COUNTER + 4:

               if (hpet_enabled())

                   printf("qemu: Writing counter while HPET enabled!\n");

               s->hpet_counter = (s->hpet_counter & 0xffffffffULL)

                                  | (((uint64_t)value) << 32);

               DPRINTF("qemu: HPET counter + 4 written. ctr = %#x -> %" PRIx64 "\n",

                        value, s->hpet_counter);

               break;

            default:

               DPRINTF("qemu: invalid hpet_ram_writel\n");

               break;

        }

    }

}


void cpu_dump_state(CPUState *env, FILE *f, fprintf_function cpu_fprintf,

        int flags)

{

    int i;

    cpu_fprintf(f, "PC=%08x\n", env->pc);

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

        cpu_fprintf(f, "A%02d=%08x%c", i, env->regs[i],

                (i % 4) == 3 ? '\n' : ' ');

    }

}


int net_init_socket(const NetClientOptions *opts, const char *name,

                    NetClientState *peer, Error **errp)

{

    /* FIXME error_setg(errp, ...) on failure */

    Error *err = NULL;

    const NetdevSocketOptions *sock;

    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_SOCKET);

    sock = opts->socket;

    if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +

        sock->has_udp != 1) {

        error_report("exactly one of fd=, listen=, connect=, mcast= or udp="

                     " is required");

        return -1;

    }

    if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {

        error_report("localaddr= is only valid with mcast= or udp=");

        return -1;

    }

    if (sock->has_fd) {

        int fd;

        fd = monitor_fd_param(cur_mon, sock->fd, &err);

        if (fd == -1) {

            error_report_err(err);

            return -1;

        }

        qemu_set_nonblock(fd);

        if (!net_socket_fd_init(peer, "socket", name, fd, 1)) {

            return -1;

        }

        return 0;

    }

    if (sock->has_listen) {

        if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {

            return -1;

        }

        return 0;

    }

    if (sock->has_connect) {

        if (net_socket_connect_init(peer, "socket", name, sock->connect) ==

            -1) {

            return -1;

        }

        return 0;

    }

    if (sock->has_mcast) {

        /* if sock->localaddr is missing, it has been initialized to "all bits

         * zero" */

        if (net_socket_mcast_init(peer, "socket", name, sock->mcast,

            sock->localaddr) == -1) {

            return -1;

        }

        return 0;

    }

    assert(sock->has_udp);

    if (!sock->has_localaddr) {

        error_report("localaddr= is mandatory with udp=");

        return -1;

    }

    if (net_socket_udp_init(peer, "socket", name, sock->udp, sock->localaddr) ==

        -1) {

        return -1;

    }

    return 0;

}


void visit_type_bool(Visitor *v, bool *obj, const char *name, Error **errp)

{

    if (!error_is_set(errp)) {

        v->type_bool(v, obj, name, errp);

    }

}


static av_always_inline av_flatten void h264_loop_filter_chroma_intra_c(uint8_t *pix, int xstride, int ystride, int alpha, int beta)

{

    int d;

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

        const int p0 = pix[-1*xstride];

        const int p1 = pix[-2*xstride];

        const int q0 = pix[0];

        const int q1 = pix[1*xstride];

        if( FFABS( p0 - q0 ) < alpha &&

            FFABS( p1 - p0 ) < beta &&

            FFABS( q1 - q0 ) < beta ) {

            pix[-xstride] = ( 2*p1 + p0 + q1 + 2 ) >> 2;   /* p0' */

            pix[0]        = ( 2*q1 + q0 + p1 + 2 ) >> 2;   /* q0' */

        }

        pix += ystride;

    }

}


static int protocol_version(VncState *vs, uint8_t *version, size_t len)

{

    char local[13];

    memcpy(local, version, 12);

    local[12] = 0;

    if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {

        VNC_DEBUG("Malformed protocol version %s\n", local);

        vnc_client_error(vs);

        return 0;

    }

    VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);

    if (vs->major != 3 ||

        (vs->minor != 3 &&

         vs->minor != 4 &&

         vs->minor != 5 &&

         vs->minor != 7 &&

         vs->minor != 8)) {

        VNC_DEBUG("Unsupported client version\n");

        vnc_write_u32(vs, VNC_AUTH_INVALID);

        vnc_flush(vs);

        vnc_client_error(vs);

        return 0;

    }

    /* Some broken clients report v3.4 or v3.5, which spec requires to be treated

     * as equivalent to v3.3 by servers

     */

    if (vs->minor == 4 || vs->minor == 5)

        vs->minor = 3;

    if (vs->minor == 3) {

        if (vs->auth == VNC_AUTH_NONE) {

            VNC_DEBUG("Tell client auth none\n");

            vnc_write_u32(vs, vs->auth);

            vnc_flush(vs);

            start_client_init(vs);

       } else if (vs->auth == VNC_AUTH_VNC) {

            VNC_DEBUG("Tell client VNC auth\n");

            vnc_write_u32(vs, vs->auth);

            vnc_flush(vs);

            start_auth_vnc(vs);

       } else {

            VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);

            vnc_write_u32(vs, VNC_AUTH_INVALID);

            vnc_flush(vs);

            vnc_client_error(vs);

       }

    } else {

        VNC_DEBUG("Telling client we support auth %d\n", vs->auth);

        vnc_write_u8(vs, 1); /* num auth */

        vnc_write_u8(vs, vs->auth);

        vnc_read_when(vs, protocol_client_auth, 1);

        vnc_flush(vs);

    }

    return 0;

}


qemu_irq *pxa2xx_pic_init(target_phys_addr_t base, CPUState *env)

{

    struct pxa2xx_pic_state_s *s;

    int iomemtype;

    qemu_irq *qi;

    s = (struct pxa2xx_pic_state_s *)

            qemu_mallocz(sizeof(struct pxa2xx_pic_state_s));

    if (!s)

        return NULL;

    s->cpu_env = env;

    s->base = base;

    s->int_pending[0] = 0;

    s->int_pending[1] = 0;

    s->int_enabled[0] = 0;

    s->int_enabled[1] = 0;

    s->is_fiq[0] = 0;

    s->is_fiq[1] = 0;

    qi = qemu_allocate_irqs(pxa2xx_pic_set_irq, s, PXA2XX_PIC_SRCS);

    /* Enable IC memory-mapped registers access.  */

    iomemtype = cpu_register_io_memory(0, pxa2xx_pic_readfn,

                    pxa2xx_pic_writefn, s);

    cpu_register_physical_memory(base, 0x000fffff, iomemtype);

    /* Enable IC coprocessor access.  */

    cpu_arm_set_cp_io(env, 6, pxa2xx_pic_cp_read, pxa2xx_pic_cp_write, s);

    register_savevm("pxa2xx_pic", 0, 0, pxa2xx_pic_save, pxa2xx_pic_load, s);

    return qi;

}


static int mp_decode_frame(MPADecodeContext *s, OUT_INT **samples,

                           const uint8_t *buf, int buf_size)

{

    int i, nb_frames, ch, ret;

    OUT_INT *samples_ptr;

    init_get_bits(&s->gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE) * 8);

    /* skip error protection field */

    if (s->error_protection)

        skip_bits(&s->gb, 16);

    switch(s->layer) {

    case 1:

        s->avctx->frame_size = 384;

        nb_frames = mp_decode_layer1(s);

        break;

    case 2:

        s->avctx->frame_size = 1152;

        nb_frames = mp_decode_layer2(s);

        break;

    case 3:

        s->avctx->frame_size = s->lsf ? 576 : 1152;

    default:

        nb_frames = mp_decode_layer3(s);

        if (nb_frames < 0)

            return nb_frames;

        s->last_buf_size=0;

        if (s->in_gb.buffer) {

            align_get_bits(&s->gb);

            i = get_bits_left(&s->gb)>>3;

            if (i >= 0 && i <= BACKSTEP_SIZE) {

                memmove(s->last_buf, s->gb.buffer + (get_bits_count(&s->gb)>>3), i);

                s->last_buf_size=i;

            } else

                av_log(s->avctx, AV_LOG_ERROR, "invalid old backstep %d\n", i);

            s->gb           = s->in_gb;

            s->in_gb.buffer = NULL;

        }

        align_get_bits(&s->gb);

        assert((get_bits_count(&s->gb) & 7) == 0);

        i = get_bits_left(&s->gb) >> 3;

        if (i < 0 || i > BACKSTEP_SIZE || nb_frames < 0) {

            if (i < 0)

                av_log(s->avctx, AV_LOG_ERROR, "invalid new backstep %d\n", i);

            i = FFMIN(BACKSTEP_SIZE, buf_size - HEADER_SIZE);

        }

        assert(i <= buf_size - HEADER_SIZE && i >= 0);

        memcpy(s->last_buf + s->last_buf_size, s->gb.buffer + buf_size - HEADER_SIZE - i, i);

        s->last_buf_size += i;

    }

    /* get output buffer */

    if (!samples) {

        av_assert0(s->frame != NULL);

        s->frame->nb_samples = s->avctx->frame_size;

        if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0) {

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

            return ret;

        }

        samples = (OUT_INT **)s->frame->extended_data;

    }

    /* apply the synthesis filter */

    for (ch = 0; ch < s->nb_channels; ch++) {

        int sample_stride;

        if (s->avctx->sample_fmt == OUT_FMT_P) {

            samples_ptr   = samples[ch];

            sample_stride = 1;

        } else {

            samples_ptr   = samples[0] + ch;

            sample_stride = s->nb_channels;

        }

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

            RENAME(ff_mpa_synth_filter)(&s->mpadsp, s->synth_buf[ch],

                                        &(s->synth_buf_offset[ch]),

                                        RENAME(ff_mpa_synth_window),

                                        &s->dither_state, samples_ptr,

                                        sample_stride, s->sb_samples[ch][i]);

            samples_ptr += 32 * sample_stride;

        }

    }

    return nb_frames * 32 * sizeof(OUT_INT) * s->nb_channels;

}


static InetSocketAddress *ssh_config(QDict *options, Error **errp)

{

    InetSocketAddress *inet = NULL;

    QDict *addr = NULL;

    QObject *crumpled_addr = NULL;

    Visitor *iv = NULL;

    Error *local_error = NULL;

    qdict_extract_subqdict(options, &addr, "server.");

    if (!qdict_size(addr)) {

        error_setg(errp, "SSH server address missing");

        goto out;

    }

    crumpled_addr = qdict_crumple(addr, errp);

    if (!crumpled_addr) {

        goto out;

    }

    iv = qobject_input_visitor_new(crumpled_addr);

    visit_type_InetSocketAddress(iv, NULL, &inet, &local_error);

    if (local_error) {

        error_propagate(errp, local_error);

        goto out;

    }

out:

    QDECREF(addr);

    qobject_decref(crumpled_addr);

    visit_free(iv);

    return inet;

}


sdhci_buff_access_is_sequential(SDHCIState *s, unsigned byte_num)

{

    if ((s->data_count & 0x3) != byte_num) {

        ERRPRINT("Non-sequential access to Buffer Data Port register"

                "is prohibited\n");

        return false;

    }

    return true;

}


static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size)

{

    ssize_t ret;

    guint watch;

    assert(qemu_in_coroutine());

    /* Negotiation are always in main loop. */

    watch = qio_channel_add_watch(ioc,

                                  G_IO_OUT,

                                  nbd_negotiate_continue,

                                  qemu_coroutine_self(),

                                  NULL);

    ret = write_sync(ioc, buffer, size, NULL);

    g_source_remove(watch);

    return ret;

}


static void aio_read_done(void *opaque, int ret)

{

    struct aio_ctx *ctx = opaque;

    struct timeval t2;

    gettimeofday(&t2, NULL);

    if (ret < 0) {

        printf("readv failed: %s\n", strerror(-ret));

        goto out;

    }

    if (ctx->Pflag) {

        void *cmp_buf = malloc(ctx->qiov.size);

        memset(cmp_buf, ctx->pattern, ctx->qiov.size);

        if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {

            printf("Pattern verification failed at offset %"

                   PRId64 ", %zd bytes\n", ctx->offset, ctx->qiov.size);

        }

        free(cmp_buf);

    }

    if (ctx->qflag) {

        goto out;

    }

    if (ctx->vflag) {

        dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, ctx->t1);

    print_report("read", &t2, ctx->offset, ctx->qiov.size,

                 ctx->qiov.size, 1, ctx->Cflag);

out:

    qemu_io_free(ctx->buf);

    free(ctx);

}