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

    RENAMEl(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 %%"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, %%"REG_a"               \n\t"

            ".p2align 4                         \n\t"

            "1:                                 \n\t"

            MOVQ" (%1, %%"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, %%"REG_a")        \n\t"

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

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

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

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

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

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

            " js 1b                             \n\t"

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

            "movd "MM"3, %%"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 %%"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, %%"REG_a"               \n\t"

            ".p2align 4                         \n\t"

            "1:                                 \n\t"

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

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

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

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

            MOVQ" (%2, %%"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, %%"REG_a")        \n\t"

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

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

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

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

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

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

            " js 1b                             \n\t"

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

            "movd "MM"3, %%"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

        "packuswb "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->dsp.idct_permutation_type == FF_SIMPLE_IDCT_PERM){

        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->dsp.idct_permutation_type == FF_LIBMPEG2_IDCT_PERM){

        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 int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFSequence *sequence = arg;

    switch(tag) {

    case 0x0202:

        sequence->duration = avio_rb64(pb);

        break;

    case 0x0201:

        avio_read(pb, sequence->data_definition_ul, 16);

        break;

    case 0x1001:

        sequence->structural_components_count = avio_rb32(pb);

        if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))

            return -1;

        sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));

        if (!sequence->structural_components_refs)

            return -1;

        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */

        avio_read(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));

        break;

    }

    return 0;

}


World *world_alloc(Rocker *r, size_t sizeof_private,

                   enum rocker_world_type type, WorldOps *ops)

{

    World *w = g_malloc0(sizeof(World) + sizeof_private);

    if (w) {

        w->r = r;

        w->type = type;

        w->ops = ops;

        if (w->ops->init) {

            w->ops->init(w);

        }

    }

    return w;

}


void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,

                               AVCodecParserContext *pc, AVPacket *pkt)

{

    int frame_size;

    *pnum = 0;

    *pden = 0;

    switch(st->codec->codec_type) {

    case AVMEDIA_TYPE_VIDEO:

        if (st->avg_frame_rate.num) {

            *pnum = st->avg_frame_rate.den;

            *pden = st->avg_frame_rate.num;

        } else if(st->time_base.num*1000LL > st->time_base.den) {

            *pnum = st->time_base.num;

            *pden = st->time_base.den;

        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){

            *pnum = st->codec->time_base.num;

            *pden = st->codec->time_base.den;

            if (pc && pc->repeat_pict) {

                *pnum = (*pnum) * (1 + pc->repeat_pict);

            }

            //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet

            //Thus if we have no parser in such case leave duration undefined.

            if(st->codec->ticks_per_frame>1 && !pc){

                *pnum = *pden = 0;

            }

        }

        break;

    case AVMEDIA_TYPE_AUDIO:

        frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);

        if (frame_size <= 0 || st->codec->sample_rate <= 0)

            break;

        *pnum = frame_size;

        *pden = st->codec->sample_rate;

        break;

    default:

        break;

    }

}


static uint64_t serial_ioport_read(void *opaque, hwaddr addr, unsigned size)

{

    SerialState *s = opaque;

    uint32_t ret;

    addr &= 7;

    switch(addr) {

    default:

    case 0:

        if (s->lcr & UART_LCR_DLAB) {

            ret = s->divider & 0xff;

        } else {

            if(s->fcr & UART_FCR_FE) {

                ret = fifo8_is_full(&s->recv_fifo) ?

                            0 : fifo8_pop(&s->recv_fifo);

                if (s->recv_fifo.num == 0) {

                    s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);

                } else {

                    qemu_mod_timer(s->fifo_timeout_timer, qemu_get_clock_ns (vm_clock) + s->char_transmit_time * 4);

                }

                s->timeout_ipending = 0;

            } else {

                ret = s->rbr;

                s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);

            }

            serial_update_irq(s);

            if (!(s->mcr & UART_MCR_LOOP)) {

                /* in loopback mode, don't receive any data */

                qemu_chr_accept_input(s->chr);

            }

        }

        break;

    case 1:

        if (s->lcr & UART_LCR_DLAB) {

            ret = (s->divider >> 8) & 0xff;

        } else {

            ret = s->ier;

        }

        break;

    case 2:

        ret = s->iir;

        if ((ret & UART_IIR_ID) == UART_IIR_THRI) {

            s->thr_ipending = 0;

            serial_update_irq(s);

        }

        break;

    case 3:

        ret = s->lcr;

        break;

    case 4:

        ret = s->mcr;

        break;

    case 5:

        ret = s->lsr;

        /* Clear break and overrun interrupts */

        if (s->lsr & (UART_LSR_BI|UART_LSR_OE)) {

            s->lsr &= ~(UART_LSR_BI|UART_LSR_OE);

            serial_update_irq(s);

        }

        break;

    case 6:

        if (s->mcr & UART_MCR_LOOP) {

            /* in loopback, the modem output pins are connected to the

               inputs */

            ret = (s->mcr & 0x0c) << 4;

            ret |= (s->mcr & 0x02) << 3;

            ret |= (s->mcr & 0x01) << 5;

        } else {

            if (s->poll_msl >= 0)

                serial_update_msl(s);

            ret = s->msr;

            /* Clear delta bits & msr int after read, if they were set */

            if (s->msr & UART_MSR_ANY_DELTA) {

                s->msr &= 0xF0;

                serial_update_irq(s);

            }

        }

        break;

    case 7:

        ret = s->scr;

        break;

    }

    DPRINTF("read addr=0x%" HWADDR_PRIx " val=0x%02x\n", addr, ret);

    return ret;

}


create_iovec(BlockBackend *blk, QEMUIOVector *qiov, char **argv, int nr_iov,

             int pattern)

{

    size_t *sizes = g_new0(size_t, nr_iov);

    size_t count = 0;

    void *buf = NULL;

    void *p;

    int i;

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

        char *arg = argv[i];

        int64_t len;

        len = cvtnum(arg);

        if (len < 0) {

            print_cvtnum_err(len, arg);

            goto fail;

        }

        if (len > SIZE_MAX) {

            printf("Argument '%s' exceeds maximum size %llu\n", arg,

                   (unsigned long long)SIZE_MAX);

            goto fail;

        }

        sizes[i] = len;

        count += len;

    }

    qemu_iovec_init(qiov, nr_iov);

    buf = p = qemu_io_alloc(blk, count, pattern);

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

        qemu_iovec_add(qiov, p, sizes[i]);

        p += sizes[i];

    }

fail:

    g_free(sizes);

    return buf;

}


static bool main_loop_should_exit(void)

{

    RunState r;

    if (qemu_debug_requested()) {

        vm_stop(RUN_STATE_DEBUG);

    }

    if (qemu_suspend_requested()) {

        qemu_system_suspend();

    }

    if (qemu_shutdown_requested()) {

        qemu_kill_report();

        monitor_protocol_event(QEVENT_SHUTDOWN, NULL);

        if (no_shutdown) {

            vm_stop(RUN_STATE_SHUTDOWN);

        } else {

            return true;

        }

    }

    if (qemu_reset_requested()) {

        pause_all_vcpus();

        cpu_synchronize_all_states();

        qemu_system_reset(VMRESET_REPORT);

        resume_all_vcpus();

        if (runstate_check(RUN_STATE_INTERNAL_ERROR) ||

            runstate_check(RUN_STATE_SHUTDOWN)) {

            runstate_set(RUN_STATE_PAUSED);

        }

    }

    if (qemu_wakeup_requested()) {

        pause_all_vcpus();

        cpu_synchronize_all_states();

        qemu_system_reset(VMRESET_SILENT);

        resume_all_vcpus();

        monitor_protocol_event(QEVENT_WAKEUP, NULL);

    }

    if (qemu_powerdown_requested()) {

        qemu_system_powerdown();

    }

    if (qemu_vmstop_requested(&r)) {

        vm_stop(r);

    }

    return false;

}


int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)

{

    AVStream *st;

    MOVStreamContext *sc;

    int j, pseudo_stream_id;

    if (c->fc->nb_streams < 1)

        return 0;

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

    sc = st->priv_data;

    for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {

        //Parsing Sample description table

        enum CodecID id;

        int dref_id = 1;

        MOVAtom a = { AV_RL32("stsd") };

        int64_t start_pos = avio_tell(pb);

        int size = avio_rb32(pb); /* size */

        uint32_t format = avio_rl32(pb); /* data format */

        if (size >= 16) {

            avio_rb32(pb); /* reserved */

            avio_rb16(pb); /* reserved */

            dref_id = avio_rb16(pb);

        }

        if (st->codec->codec_tag &&

            st->codec->codec_tag != format &&

            (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id

                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))

           ){

            /* Multiple fourcc, we skip JPEG. This is not correct, we should

             * export it as a separate AVStream but this needs a few changes

             * in the MOV demuxer, patch welcome. */

        multiple_stsd:

            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");

            avio_skip(pb, size - (avio_tell(pb) - start_pos));

            continue;

        }

        /* we cannot demux concatenated h264 streams because of different extradata */

        if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))

            goto multiple_stsd;

        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;

        sc->dref_id= dref_id;

        st->codec->codec_tag = format;

        id = ff_codec_get_id(codec_movaudio_tags, format);

        if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))

            id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);

        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {

            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */

                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */

            id = ff_codec_get_id(codec_movvideo_tags, format);

            if (id <= 0)

                id = ff_codec_get_id(ff_codec_bmp_tags, format);

            if (id > 0)

                st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){

                id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);

                if (id > 0)

                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

            }

        }

        av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,

                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,

                (format >> 24) & 0xff, st->codec->codec_type);

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

            unsigned int color_depth, len;

            int color_greyscale;

            st->codec->codec_id = id;

            avio_rb16(pb); /* version */

            avio_rb16(pb); /* revision level */

            avio_rb32(pb); /* vendor */

            avio_rb32(pb); /* temporal quality */

            avio_rb32(pb); /* spatial quality */

            st->codec->width = avio_rb16(pb); /* width */

            st->codec->height = avio_rb16(pb); /* height */

            avio_rb32(pb); /* horiz resolution */

            avio_rb32(pb); /* vert resolution */

            avio_rb32(pb); /* data size, always 0 */

            avio_rb16(pb); /* frames per samples */

            len = avio_r8(pb); /* codec name, pascal string */

            if (len > 31)

                len = 31;

            mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);

            if (len < 31)

                avio_skip(pb, 31 - len);

            /* codec_tag YV12 triggers an UV swap in rawdec.c */

            if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))

                st->codec->codec_tag=MKTAG('I', '4', '2', '0');

            st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */

            st->codec->color_table_id = avio_rb16(pb); /* colortable id */

            av_dlog(c->fc, "depth %d, ctab id %d\n",

                   st->codec->bits_per_coded_sample, st->codec->color_table_id);

            /* figure out the palette situation */

            color_depth = st->codec->bits_per_coded_sample & 0x1F;

            color_greyscale = st->codec->bits_per_coded_sample & 0x20;

            /* if the depth is 2, 4, or 8 bpp, file is palettized */

            if ((color_depth == 2) || (color_depth == 4) ||

                (color_depth == 8)) {

                /* for palette traversal */

                unsigned int color_start, color_count, color_end;

                unsigned char r, g, b;

                if (color_greyscale) {

                    int color_index, color_dec;

                    /* compute the greyscale palette */

                    st->codec->bits_per_coded_sample = color_depth;

                    color_count = 1 << color_depth;

                    color_index = 255;

                    color_dec = 256 / (color_count - 1);

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

                        if (id == CODEC_ID_CINEPAK){

                            r = g = b = color_count - 1 - color_index;

                        }else

                        r = g = b = color_index;

                        sc->palette[j] =

                            (r << 16) | (g << 8) | (b);

                        color_index -= color_dec;

                        if (color_index < 0)

                            color_index = 0;

                    }

                } else if (st->codec->color_table_id) {

                    const uint8_t *color_table;

                    /* if flag bit 3 is set, use the default palette */

                    color_count = 1 << color_depth;

                    if (color_depth == 2)

                        color_table = ff_qt_default_palette_4;

                    else if (color_depth == 4)

                        color_table = ff_qt_default_palette_16;

                    else

                        color_table = ff_qt_default_palette_256;

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

                        r = color_table[j * 3 + 0];

                        g = color_table[j * 3 + 1];

                        b = color_table[j * 3 + 2];

                        sc->palette[j] =

                            (r << 16) | (g << 8) | (b);

                    }

                } else {

                    /* load the palette from the file */

                    color_start = avio_rb32(pb);

                    color_count = avio_rb16(pb);

                    color_end = avio_rb16(pb);

                    if ((color_start <= 255) &&

                        (color_end <= 255)) {

                        for (j = color_start; j <= color_end; j++) {

                            /* each R, G, or B component is 16 bits;

                             * only use the top 8 bits; skip alpha bytes

                             * up front */

                            avio_r8(pb);

                            avio_r8(pb);

                            r = avio_r8(pb);

                            avio_r8(pb);

                            g = avio_r8(pb);

                            avio_r8(pb);

                            b = avio_r8(pb);

                            avio_r8(pb);

                            sc->palette[j] =

                                (r << 16) | (g << 8) | (b);

                        }

                    }

                }

                sc->has_palette = 1;

            }

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

            int bits_per_sample, flags;

            uint16_t version = avio_rb16(pb);

            st->codec->codec_id = id;

            avio_rb16(pb); /* revision level */

            avio_rb32(pb); /* vendor */

            st->codec->channels = avio_rb16(pb);             /* channel count */

            av_dlog(c->fc, "audio channels %d\n", st->codec->channels);

            st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */

            sc->audio_cid = avio_rb16(pb);

            avio_rb16(pb); /* packet size = 0 */

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

            //Read QT version 1 fields. In version 0 these do not exist.

            av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);

            if (!c->isom) {

                if (version==1) {

                    sc->samples_per_frame = avio_rb32(pb);

                    avio_rb32(pb); /* bytes per packet */

                    sc->bytes_per_frame = avio_rb32(pb);

                    avio_rb32(pb); /* bytes per sample */

                } else if (version==2) {

                    avio_rb32(pb); /* sizeof struct only */

                    st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */

                    st->codec->channels = avio_rb32(pb);

                    avio_rb32(pb); /* always 0x7F000000 */

                    st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */

                    flags = avio_rb32(pb); /* lpcm format specific flag */

                    sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */

                    sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */

                    if (format == MKTAG('l','p','c','m'))

                        st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);

                }

            }

            switch (st->codec->codec_id) {

            case CODEC_ID_PCM_S8:

            case CODEC_ID_PCM_U8:

                if (st->codec->bits_per_coded_sample == 16)

                    st->codec->codec_id = CODEC_ID_PCM_S16BE;

                break;

            case CODEC_ID_PCM_S16LE:

            case CODEC_ID_PCM_S16BE:

                if (st->codec->bits_per_coded_sample == 8)

                    st->codec->codec_id = CODEC_ID_PCM_S8;

                else if (st->codec->bits_per_coded_sample == 24)

                    st->codec->codec_id =

                        st->codec->codec_id == CODEC_ID_PCM_S16BE ?

                        CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;

                break;

            /* set values for old format before stsd version 1 appeared */

            case CODEC_ID_MACE3:

                sc->samples_per_frame = 6;

                sc->bytes_per_frame = 2*st->codec->channels;

                break;

            case CODEC_ID_MACE6:

                sc->samples_per_frame = 6;

                sc->bytes_per_frame = 1*st->codec->channels;

                break;

            case CODEC_ID_ADPCM_IMA_QT:

                sc->samples_per_frame = 64;

                sc->bytes_per_frame = 34*st->codec->channels;

                break;

            case CODEC_ID_GSM:

                sc->samples_per_frame = 160;

                sc->bytes_per_frame = 33;

                break;

            default:

                break;

            }

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

            if (bits_per_sample) {

                st->codec->bits_per_coded_sample = bits_per_sample;

                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;

            }

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

            // ttxt stsd contains display flags, justification, background

            // color, fonts, and default styles, so fake an atom to read it

            MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };

            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom

                mov_read_glbl(c, pb, fake_atom);

            st->codec->codec_id= id;

            st->codec->width = sc->width;

            st->codec->height = sc->height;

        } else {

            if (st->codec->codec_tag == MKTAG('t','m','c','d')) {

                int val;

                avio_rb32(pb);       /* reserved */

                val = avio_rb32(pb); /* flags */

                if (val & 1)

                    st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;

                avio_rb32(pb);

                avio_rb32(pb);

                st->codec->time_base.den = avio_r8(pb);

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

            }

            /* other codec type, just skip (rtp, mp4s, ...) */

            avio_skip(pb, size - (avio_tell(pb) - start_pos));

        }

        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */

        a.size = size - (avio_tell(pb) - start_pos);

        if (a.size > 8) {

            if (mov_read_default(c, pb, a) < 0)

        } else if (a.size > 0)

            avio_skip(pb, a.size);

    }

    if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)

        st->codec->sample_rate= sc->time_scale;

    /* special codec parameters handling */

    switch (st->codec->codec_id) {

#if CONFIG_DV_DEMUXER

    case CODEC_ID_DVAUDIO:

        c->dv_fctx = avformat_alloc_context();

        c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);

        if (!c->dv_demux) {

            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");

        }

        sc->dv_audio_container = 1;

        st->codec->codec_id = CODEC_ID_PCM_S16LE;

        break;

#endif

    /* no ifdef since parameters are always those */

    case CODEC_ID_QCELP:

        // force sample rate for qcelp when not stored in mov

        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))

            st->codec->sample_rate = 8000;

        st->codec->frame_size= 160;

        st->codec->channels= 1; /* really needed */

        break;

    case CODEC_ID_AMR_NB:

        st->codec->channels= 1; /* really needed */

        /* force sample rate for amr, stsd in 3gp does not store sample rate */

        st->codec->sample_rate = 8000;

        /* force frame_size, too, samples_per_frame isn't always set properly */

        st->codec->frame_size  = 160;

        break;

    case CODEC_ID_AMR_WB:

        st->codec->channels    = 1;

        st->codec->sample_rate = 16000;

        st->codec->frame_size  = 320;

        break;

    case CODEC_ID_MP2:

    case CODEC_ID_MP3:

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */

        st->need_parsing = AVSTREAM_PARSE_FULL;

        break;

    case CODEC_ID_GSM:

    case CODEC_ID_ADPCM_MS:

    case CODEC_ID_ADPCM_IMA_WAV:

        st->codec->frame_size = sc->samples_per_frame;

        st->codec->block_align = sc->bytes_per_frame;

        break;

    case CODEC_ID_ALAC:

        if (st->codec->extradata_size == 36) {

            st->codec->frame_size = AV_RB32(st->codec->extradata+12);

            st->codec->channels   = AV_RB8 (st->codec->extradata+21);

            st->codec->sample_rate = AV_RB32(st->codec->extradata+32);

        }

        break;

    case CODEC_ID_AC3:

        st->need_parsing = AVSTREAM_PARSE_FULL;

        break;

    case CODEC_ID_MPEG1VIDEO:

        st->need_parsing = AVSTREAM_PARSE_FULL;

        break;

    default:

        break;

    }

    return 0;

}


static void test_tco_max_timeout(void)

{

    TestData d;

    const uint16_t ticks = 0xffff;

    uint32_t val;

    int ret;

    d.args = NULL;

    d.noreboot = true;

    test_init(&d);

    stop_tco(&d);

    clear_tco_status(&d);

    reset_on_second_timeout(false);

    set_tco_timeout(&d, ticks);

    load_tco(&d);

    start_tco(&d);

    clock_step(((ticks & TCO_TMR_MASK) - 1) * TCO_TICK_NSEC);

    val = qpci_io_readw(d.dev, d.tco_io_base + TCO_RLD);

    g_assert_cmpint(val & TCO_RLD_MASK, ==, 1);

    val = qpci_io_readw(d.dev, d.tco_io_base + TCO1_STS);

    ret = val & TCO_TIMEOUT ? 1 : 0;

    g_assert(ret == 0);

    clock_step(TCO_TICK_NSEC);

    val = qpci_io_readw(d.dev, d.tco_io_base + TCO1_STS);

    ret = val & TCO_TIMEOUT ? 1 : 0;

    g_assert(ret == 1);

    stop_tco(&d);

    qtest_end();

}


YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48be, PIX_FMT_RGB48BE)

YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48le, PIX_FMT_RGB48LE)

YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48be, PIX_FMT_BGR48BE)

YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48le, PIX_FMT_BGR48LE)

/*

 * Write out 2 RGB pixels in the target pixel format. This function takes a

 * R/G/B LUT as generated by ff_yuv2rgb_c_init_tables(), which takes care of

 * things like endianness conversion and shifting. The caller takes care of

 * setting the correct offset in these tables from the chroma (U/V) values.

 * This function then uses the luminance (Y1/Y2) values to write out the

 * correct RGB values into the destination buffer.

 */

static av_always_inline void

yuv2rgb_write(uint8_t *_dest, int i, unsigned Y1, unsigned Y2,

              unsigned A1, unsigned A2,

              const void *_r, const void *_g, const void *_b, int y,

              enum PixelFormat target, int hasAlpha)

{

    if (target == PIX_FMT_ARGB || target == PIX_FMT_RGBA ||

        target == PIX_FMT_ABGR || target == PIX_FMT_BGRA) {

        uint32_t *dest = (uint32_t *) _dest;

        const uint32_t *r = (const uint32_t *) _r;

        const uint32_t *g = (const uint32_t *) _g;

        const uint32_t *b = (const uint32_t *) _b;

#if CONFIG_SMALL

        int sh = hasAlpha ? ((target == PIX_FMT_RGB32_1 || target == PIX_FMT_BGR32_1) ? 0 : 24) : 0;

        dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1] + (hasAlpha ? A1 << sh : 0);

        dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2] + (hasAlpha ? A2 << sh : 0);

#else

        if (hasAlpha) {

            int sh = (target == PIX_FMT_RGB32_1 || target == PIX_FMT_BGR32_1) ? 0 : 24;

            dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1] + (A1 << sh);

            dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2] + (A2 << sh);

        } else {

            dest[i * 2 + 0] = r[Y1] + g[Y1] + b[Y1];

            dest[i * 2 + 1] = r[Y2] + g[Y2] + b[Y2];

        }

#endif

    } else if (target == PIX_FMT_RGB24 || target == PIX_FMT_BGR24) {

        uint8_t *dest = (uint8_t *) _dest;

        const uint8_t *r = (const uint8_t *) _r;

        const uint8_t *g = (const uint8_t *) _g;

        const uint8_t *b = (const uint8_t *) _b;

#define r_b ((target == PIX_FMT_RGB24) ? r : b)

#define b_r ((target == PIX_FMT_RGB24) ? b : r)

        dest[i * 6 + 0] = r_b[Y1];

        dest[i * 6 + 1] =   g[Y1];

        dest[i * 6 + 2] = b_r[Y1];

        dest[i * 6 + 3] = r_b[Y2];

        dest[i * 6 + 4] =   g[Y2];

        dest[i * 6 + 5] = b_r[Y2];

#undef r_b

#undef b_r

    } else if (target == PIX_FMT_RGB565 || target == PIX_FMT_BGR565 ||

               target == PIX_FMT_RGB555 || target == PIX_FMT_BGR555 ||

               target == PIX_FMT_RGB444 || target == PIX_FMT_BGR444) {

        uint16_t *dest = (uint16_t *) _dest;

        const uint16_t *r = (const uint16_t *) _r;

        const uint16_t *g = (const uint16_t *) _g;

        const uint16_t *b = (const uint16_t *) _b;

        int dr1, dg1, db1, dr2, dg2, db2;

        if (target == PIX_FMT_RGB565 || target == PIX_FMT_BGR565) {

            dr1 = dither_2x2_8[ y & 1     ][0];

            dg1 = dither_2x2_4[ y & 1     ][0];

            db1 = dither_2x2_8[(y & 1) ^ 1][0];

            dr2 = dither_2x2_8[ y & 1     ][1];

            dg2 = dither_2x2_4[ y & 1     ][1];

            db2 = dither_2x2_8[(y & 1) ^ 1][1];

        } else if (target == PIX_FMT_RGB555 || target == PIX_FMT_BGR555) {

            dr1 = dither_2x2_8[ y & 1     ][0];

            dg1 = dither_2x2_8[ y & 1     ][1];

            db1 = dither_2x2_8[(y & 1) ^ 1][0];

            dr2 = dither_2x2_8[ y & 1     ][1];

            dg2 = dither_2x2_8[ y & 1     ][0];

            db2 = dither_2x2_8[(y & 1) ^ 1][1];

        } else {

            dr1 = dither_4x4_16[ y & 3     ][0];

            dg1 = dither_4x4_16[ y & 3     ][1];

            db1 = dither_4x4_16[(y & 3) ^ 3][0];

            dr2 = dither_4x4_16[ y & 3     ][1];

            dg2 = dither_4x4_16[ y & 3     ][0];

            db2 = dither_4x4_16[(y & 3) ^ 3][1];

        }

        dest[i * 2 + 0] = r[Y1 + dr1] + g[Y1 + dg1] + b[Y1 + db1];

        dest[i * 2 + 1] = r[Y2 + dr2] + g[Y2 + dg2] + b[Y2 + db2];

    } else /* 8/4-bit */ {

        uint8_t *dest = (uint8_t *) _dest;

        const uint8_t *r = (const uint8_t *) _r;

        const uint8_t *g = (const uint8_t *) _g;

        const uint8_t *b = (const uint8_t *) _b;

        int dr1, dg1, db1, dr2, dg2, db2;

        if (target == PIX_FMT_RGB8 || target == PIX_FMT_BGR8) {

            const uint8_t * const d64 = dither_8x8_73[y & 7];

            const uint8_t * const d32 = dither_8x8_32[y & 7];

            dr1 = dg1 = d32[(i * 2 + 0) & 7];

            db1 =       d64[(i * 2 + 0) & 7];

            dr2 = dg2 = d32[(i * 2 + 1) & 7];

            db2 =       d64[(i * 2 + 1) & 7];

        } else {

            const uint8_t * const d64  = dither_8x8_73 [y & 7];

            const uint8_t * const d128 = dither_8x8_220[y & 7];

            dr1 = db1 = d128[(i * 2 + 0) & 7];

            dg1 =        d64[(i * 2 + 0) & 7];

            dr2 = db2 = d128[(i * 2 + 1) & 7];

            dg2 =        d64[(i * 2 + 1) & 7];

        }

        if (target == PIX_FMT_RGB4 || target == PIX_FMT_BGR4) {

            dest[i] = r[Y1 + dr1] + g[Y1 + dg1] + b[Y1 + db1] +

                    ((r[Y2 + dr2] + g[Y2 + dg2] + b[Y2 + db2]) << 4);

        } else {

            dest[i * 2 + 0] = r[Y1 + dr1] + g[Y1 + dg1] + b[Y1 + db1];

            dest[i * 2 + 1] = r[Y2 + dr2] + g[Y2 + dg2] + b[Y2 + db2];

        }

    }

}


int vhost_set_vring_enable(NetClientState *nc, int enable)

{

    VHostNetState *net = get_vhost_net(nc);

    const VhostOps *vhost_ops;

    nc->vring_enable = enable;

    if (!net) {

        return 0;

    }

    vhost_ops = net->dev.vhost_ops;

    if (vhost_ops->vhost_set_vring_enable) {

        return vhost_ops->vhost_set_vring_enable(&net->dev, enable);

    }

    return 0;

}


static int get_channel_idx(char **map, int *ch, char delim, int max_ch)

{

    char *next = split(*map, delim);

    int len;

    int n = 0;

    if (!next && delim == '-')

    len = strlen(*map);

    sscanf(*map, "%d%n", ch, &n);

    if (n != len)

    if (*ch < 0 || *ch > max_ch)

    *map = next;

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    dc->desc        = "ISA bridge";

    dc->vmsd        = &vmstate_piix3;

    dc->no_user     = 1;

    k->no_hotplug   = 1;

    k->init         = piix3_initfn;

    k->config_write = piix3_write_config_xen;

    k->vendor_id    = PCI_VENDOR_ID_INTEL;

    /* 82371SB PIIX3 PCI-to-ISA bridge (Step A1) */

    k->device_id    = PCI_DEVICE_ID_INTEL_82371SB_0;

    k->class_id     = PCI_CLASS_BRIDGE_ISA;

};


qio_channel_websock_source_check(GSource *source)

{

    QIOChannelWebsockSource *wsource = (QIOChannelWebsockSource *)source;

    GIOCondition cond = 0;

    if (wsource->wioc->rawinput.offset) {

        cond |= G_IO_IN;

    }

    if (wsource->wioc->rawoutput.offset < QIO_CHANNEL_WEBSOCK_MAX_BUFFER) {

        cond |= G_IO_OUT;

    }

    return cond & wsource->condition;

}


static int sad8_altivec(void *v, uint8_t *pix1, uint8_t *pix2, int line_size, int h)

{

    int i;

    int s;

    const vector unsigned int zero = (const vector unsigned int)vec_splat_u32(0);

    const vector unsigned char permclear = (vector unsigned char){255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0};

    vector unsigned char perm1 = vec_lvsl(0, pix1);

    vector unsigned char perm2 = vec_lvsl(0, pix2);

    vector unsigned char t1, t2, t3,t4, t5;

    vector unsigned int sad;

    vector signed int sumdiffs;

    sad = (vector unsigned int)vec_splat_u32(0);

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

        /* Read potentially unaligned pixels into t1 and t2

           Since we're reading 16 pixels, and actually only want 8,

           mask out the last 8 pixels. The 0s don't change the sum. */

        vector unsigned char pix1l = vec_ld( 0, pix1);

        vector unsigned char pix1r = vec_ld(15, pix1);

        vector unsigned char pix2l = vec_ld( 0, pix2);

        vector unsigned char pix2r = vec_ld(15, pix2);

        t1 = vec_and(vec_perm(pix1l, pix1r, perm1), permclear);

        t2 = vec_and(vec_perm(pix2l, pix2r, perm2), permclear);

        /* Calculate a sum of abs differences vector */

        t3 = vec_max(t1, t2);

        t4 = vec_min(t1, t2);

        t5 = vec_sub(t3, t4);

        /* Add each 4 pixel group together and put 4 results into sad */

        sad = vec_sum4s(t5, sad);

        pix1 += line_size;

        pix2 += line_size;

    }

    /* Sum up the four partial sums, and put the result into s */

    sumdiffs = vec_sums((vector signed int) sad, (vector signed int) zero);

    sumdiffs = vec_splat(sumdiffs, 3);

    vec_ste(sumdiffs, 0, &s);

    return s;

}


static void move_audio(vorbis_enc_context *venc, float **audio, int *samples, int sf_size)

{

    AVFrame *cur = NULL;

    int frame_size = 1 << (venc->log2_blocksize[1] - 1);

    int subframes = frame_size / sf_size;

    for (int sf = 0; sf < subframes; sf++) {

        cur = ff_bufqueue_get(&venc->bufqueue);

        *samples += cur->nb_samples;

        for (int ch = 0; ch < venc->channels; ch++) {

            const float *input = (float *) cur->extended_data[ch];

            const size_t len  = cur->nb_samples * sizeof(float);

            memcpy(&audio[ch][sf*sf_size], input, len);

        }

        av_frame_free(&cur);

    }

}


static void svq3_add_idct_c(uint8_t *dst, int16_t *block,

                            int stride, int qp, int dc)

{

    const int qmul = svq3_dequant_coeff[qp];

    int i;

    if (dc) {

        dc       = 13 * 13 * (dc == 1 ? 1538U* block[0]

                                      : qmul * (block[0] >> 3) / 2);

        block[0] = 0;

    }

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

        const int z0 = 13 * (block[0 + 4 * i] +      block[2 + 4 * i]);

        const int z1 = 13 * (block[0 + 4 * i] -      block[2 + 4 * i]);

        const int z2 =  7 *  block[1 + 4 * i] - 17 * block[3 + 4 * i];

        const int z3 = 17 *  block[1 + 4 * i] +  7 * block[3 + 4 * i];

        block[0 + 4 * i] = z0 + z3;

        block[1 + 4 * i] = z1 + z2;

        block[2 + 4 * i] = z1 - z2;

        block[3 + 4 * i] = z0 - z3;

    }

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

        const unsigned z0 = 13 * (block[i + 4 * 0] +      block[i + 4 * 2]);

        const unsigned z1 = 13 * (block[i + 4 * 0] -      block[i + 4 * 2]);

        const unsigned z2 =  7 *  block[i + 4 * 1] - 17 * block[i + 4 * 3];

        const unsigned z3 = 17 *  block[i + 4 * 1] +  7 * block[i + 4 * 3];

        const int rr = (dc + 0x80000);

        dst[i + stride * 0] = av_clip_uint8(dst[i + stride * 0] + ((int)((z0 + z3) * qmul + rr) >> 20));

        dst[i + stride * 1] = av_clip_uint8(dst[i + stride * 1] + ((int)((z1 + z2) * qmul + rr) >> 20));

        dst[i + stride * 2] = av_clip_uint8(dst[i + stride * 2] + ((int)((z1 - z2) * qmul + rr) >> 20));

        dst[i + stride * 3] = av_clip_uint8(dst[i + stride * 3] + ((int)((z0 - z3) * qmul + rr) >> 20));

    }

    memset(block, 0, 16 * sizeof(int16_t));

}


static char *vnc_socket_local_addr(const char *format, int fd) {

    struct sockaddr_storage sa;

    socklen_t salen;

    salen = sizeof(sa);

    if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)

        return NULL;

    return addr_to_string(format, &sa, salen);

}


static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)

{

    /* Primary audio coding side information */

    int j, k;

    if (get_bits_left(&s->gb) < 0)

        return AVERROR_INVALIDDATA;

    if (!base_channel) {

        s->subsubframes[s->current_subframe]    = get_bits(&s->gb, 2) + 1;

        s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);

    }

    for (j = base_channel; j < s->prim_channels; j++) {

        for (k = 0; k < s->subband_activity[j]; k++)

            s->prediction_mode[j][k] = get_bits(&s->gb, 1);

    }

    /* Get prediction codebook */

    for (j = base_channel; j < s->prim_channels; j++) {

        for (k = 0; k < s->subband_activity[j]; k++) {

            if (s->prediction_mode[j][k] > 0) {

                /* (Prediction coefficient VQ address) */

                s->prediction_vq[j][k] = get_bits(&s->gb, 12);

            }

        }

    }

    /* Bit allocation index */

    for (j = base_channel; j < s->prim_channels; j++) {

        for (k = 0; k < s->vq_start_subband[j]; k++) {

            if (s->bitalloc_huffman[j] == 6)

                s->bitalloc[j][k] = get_bits(&s->gb, 5);

            else if (s->bitalloc_huffman[j] == 5)

                s->bitalloc[j][k] = get_bits(&s->gb, 4);

            else if (s->bitalloc_huffman[j] == 7) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "Invalid bit allocation index\n");

                return AVERROR_INVALIDDATA;

            } else {

                s->bitalloc[j][k] =

                    get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);

            }

            if (s->bitalloc[j][k] > 26) {

                // av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index [%i][%i] too big (%i)\n",

                //        j, k, s->bitalloc[j][k]);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    /* Transition mode */

    for (j = base_channel; j < s->prim_channels; j++) {

        for (k = 0; k < s->subband_activity[j]; k++) {

            s->transition_mode[j][k] = 0;

            if (s->subsubframes[s->current_subframe] > 1 &&

                k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {

                s->transition_mode[j][k] =

                    get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);

            }

        }

    }

    if (get_bits_left(&s->gb) < 0)

        return AVERROR_INVALIDDATA;

    for (j = base_channel; j < s->prim_channels; j++) {

        const uint32_t *scale_table;

        int scale_sum, log_size;

        memset(s->scale_factor[j], 0,

               s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);

        if (s->scalefactor_huffman[j] == 6) {

            scale_table = scale_factor_quant7;

            log_size = 7;

        } else {

            scale_table = scale_factor_quant6;

            log_size = 6;

        }

        /* When huffman coded, only the difference is encoded */

        scale_sum = 0;

        for (k = 0; k < s->subband_activity[j]; k++) {

            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {

                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);

                s->scale_factor[j][k][0] = scale_table[scale_sum];

            }

            if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {

                /* Get second scale factor */

                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum, log_size);

                s->scale_factor[j][k][1] = scale_table[scale_sum];

            }

        }

    }

    /* Joint subband scale factor codebook select */

    for (j = base_channel; j < s->prim_channels; j++) {

        /* Transmitted only if joint subband coding enabled */

        if (s->joint_intensity[j] > 0)

            s->joint_huff[j] = get_bits(&s->gb, 3);

    }

    if (get_bits_left(&s->gb) < 0)

        return AVERROR_INVALIDDATA;

    /* Scale factors for joint subband coding */

    for (j = base_channel; j < s->prim_channels; j++) {

        int source_channel;

        /* Transmitted only if joint subband coding enabled */

        if (s->joint_intensity[j] > 0) {

            int scale = 0;

            source_channel = s->joint_intensity[j] - 1;

            /* When huffman coded, only the difference is encoded

             * (is this valid as well for joint scales ???) */

            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {

                scale = get_scale(&s->gb, s->joint_huff[j], 64 /* bias */, 7);

                s->joint_scale_factor[j][k] = scale;    /*joint_scale_table[scale]; */

            }

            if (!(s->debug_flag & 0x02)) {

                av_log(s->avctx, AV_LOG_DEBUG,

                       "Joint stereo coding not supported\n");

                s->debug_flag |= 0x02;

            }

        }

    }

    /* Stereo downmix coefficients */

    if (!base_channel && s->prim_channels > 2) {

        if (s->downmix) {

            for (j = base_channel; j < s->prim_channels; j++) {

                s->downmix_coef[j][0] = get_bits(&s->gb, 7);

                s->downmix_coef[j][1] = get_bits(&s->gb, 7);

            }

        } else {

            int am = s->amode & DCA_CHANNEL_MASK;

            if (am >= FF_ARRAY_ELEMS(dca_default_coeffs)) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "Invalid channel mode %d\n", am);

                return AVERROR_INVALIDDATA;

            }

            for (j = base_channel; j < s->prim_channels; j++) {

                s->downmix_coef[j][0] = dca_default_coeffs[am][j][0];

                s->downmix_coef[j][1] = dca_default_coeffs[am][j][1];

            }

        }

    }

    /* Dynamic range coefficient */

    if (!base_channel && s->dynrange)

        s->dynrange_coef = get_bits(&s->gb, 8);

    /* Side information CRC check word */

    if (s->crc_present) {

        get_bits(&s->gb, 16);

    }

    /*

     * Primary audio data arrays

     */

    /* VQ encoded high frequency subbands */

    for (j = base_channel; j < s->prim_channels; j++)

        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)

            /* 1 vector -> 32 samples */

            s->high_freq_vq[j][k] = get_bits(&s->gb, 10);

    /* Low frequency effect data */

    if (!base_channel && s->lfe) {

        int quant7;

        /* LFE samples */

        int lfe_samples = 2 * s->lfe * (4 + block_index);

        int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);

        float lfe_scale;

        for (j = lfe_samples; j < lfe_end_sample; j++) {

            /* Signed 8 bits int */

            s->lfe_data[j] = get_sbits(&s->gb, 8);

        }

        /* Scale factor index */

        quant7 = get_bits(&s->gb, 8);

        if (quant7 > 127) {

            av_log_ask_for_sample(s->avctx, "LFEScaleIndex larger than 127\n");

            return AVERROR_INVALIDDATA;

        }

        s->lfe_scale_factor = scale_factor_quant7[quant7];

        /* Quantization step size * scale factor */

        lfe_scale = 0.035 * s->lfe_scale_factor;

        for (j = lfe_samples; j < lfe_end_sample; j++)

            s->lfe_data[j] *= lfe_scale;

    }

#ifdef TRACE

    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n",

           s->subsubframes[s->current_subframe]);

    av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",

           s->partial_samples[s->current_subframe]);

    for (j = base_channel; j < s->prim_channels; j++) {

        av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");

        for (k = 0; k < s->subband_activity[j]; k++)

            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->prediction_mode[j][k]);

        av_log(s->avctx, AV_LOG_DEBUG, "\n");

    }

    for (j = base_channel; j < s->prim_channels; j++) {

        for (k = 0; k < s->subband_activity[j]; k++)

            av_log(s->avctx, AV_LOG_DEBUG,

                   "prediction coefs: %f, %f, %f, %f\n",

                   (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,

                   (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,

                   (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,

                   (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);

    }

    for (j = base_channel; j < s->prim_channels; j++) {

        av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");

        for (k = 0; k < s->vq_start_subband[j]; k++)

            av_log(s->avctx, AV_LOG_DEBUG, "%2.2i ", s->bitalloc[j][k]);

        av_log(s->avctx, AV_LOG_DEBUG, "\n");

    }

    for (j = base_channel; j < s->prim_channels; j++) {

        av_log(s->avctx, AV_LOG_DEBUG, "Transition mode:");

        for (k = 0; k < s->subband_activity[j]; k++)

            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->transition_mode[j][k]);

        av_log(s->avctx, AV_LOG_DEBUG, "\n");

    }

    for (j = base_channel; j < s->prim_channels; j++) {

        av_log(s->avctx, AV_LOG_DEBUG, "Scale factor:");

        for (k = 0; k < s->subband_activity[j]; k++) {

            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0)

                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->scale_factor[j][k][0]);

            if (k < s->vq_start_subband[j] && s->transition_mode[j][k])

                av_log(s->avctx, AV_LOG_DEBUG, " %i(t)", s->scale_factor[j][k][1]);

        }

        av_log(s->avctx, AV_LOG_DEBUG, "\n");

    }

    for (j = base_channel; j < s->prim_channels; j++) {

        if (s->joint_intensity[j] > 0) {

            int source_channel = s->joint_intensity[j] - 1;

            av_log(s->avctx, AV_LOG_DEBUG, "Joint scale factor index:\n");

            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++)

                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->joint_scale_factor[j][k]);

            av_log(s->avctx, AV_LOG_DEBUG, "\n");

        }

    }

    if (!base_channel && s->prim_channels > 2 && s->downmix) {

        av_log(s->avctx, AV_LOG_DEBUG, "Downmix coeffs:\n");

        for (j = 0; j < s->prim_channels; j++) {

            av_log(s->avctx, AV_LOG_DEBUG, "Channel 0, %d = %f\n", j,

                   dca_downmix_coeffs[s->downmix_coef[j][0]]);

            av_log(s->avctx, AV_LOG_DEBUG, "Channel 1, %d = %f\n", j,

                   dca_downmix_coeffs[s->downmix_coef[j][1]]);

        }

        av_log(s->avctx, AV_LOG_DEBUG, "\n");

    }

    for (j = base_channel; j < s->prim_channels; j++)

        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)

            av_log(s->avctx, AV_LOG_DEBUG, "VQ index: %i\n", s->high_freq_vq[j][k]);

    if (!base_channel && s->lfe) {

        int lfe_samples = 2 * s->lfe * (4 + block_index);

        int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);

        av_log(s->avctx, AV_LOG_DEBUG, "LFE samples:\n");

        for (j = lfe_samples; j < lfe_end_sample; j++)

            av_log(s->avctx, AV_LOG_DEBUG, " %f", s->lfe_data[j]);

        av_log(s->avctx, AV_LOG_DEBUG, "\n");

    }

#endif

    return 0;

}


static void gen_neon_dup_u8(TCGv var, int shift)

{

    TCGv tmp = new_tmp();

    if (shift)

        tcg_gen_shri_i32(var, var, shift);

    tcg_gen_ext8u_i32(var, var);

    tcg_gen_shli_i32(tmp, var, 8);

    tcg_gen_or_i32(var, var, tmp);

    tcg_gen_shli_i32(tmp, var, 16);

    tcg_gen_or_i32(var, var, tmp);

    dead_tmp(tmp);

}


static target_ulong helper_udiv_common(CPUSPARCState *env, target_ulong a,

                                       target_ulong b, int cc)

{

    SPARCCPU *cpu = sparc_env_get_cpu(env);

    int overflow = 0;

    uint64_t x0;

    uint32_t x1;

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

    x1 = (b & 0xffffffff);

    if (x1 == 0) {

        cpu_restore_state(CPU(cpu), GETPC());

        helper_raise_exception(env, TT_DIV_ZERO);

    }

    x0 = x0 / x1;

    if (x0 > 0xffffffff) {

        x0 = 0xffffffff;

        overflow = 1;

    }

    if (cc) {

        env->cc_dst = x0;

        env->cc_src2 = overflow;

        env->cc_op = CC_OP_DIV;

    }

    return x0;

}


static BlockStats *bdrv_query_stats(const BlockDriverState *bs,
                                    bool query_backing)
{
    BlockStats *s;
    s = g_malloc0(sizeof(*s));
    if (bdrv_get_device_name(bs)[0]) {
        s->has_device = true;
        s->device = g_strdup(bdrv_get_device_name(bs));
    }
    if (bdrv_get_node_name(bs)[0]) {
        s->has_node_name = true;
        s->node_name = g_strdup(bdrv_get_node_name(bs));
    }
    s->stats = g_malloc0(sizeof(*s->stats));
    if (bs->blk) {
        BlockAcctStats *stats = blk_get_stats(bs->blk);
        s->stats->rd_bytes = stats->nr_bytes[BLOCK_ACCT_READ];
        s->stats->wr_bytes = stats->nr_bytes[BLOCK_ACCT_WRITE];
        s->stats->rd_operations = stats->nr_ops[BLOCK_ACCT_READ];
        s->stats->wr_operations = stats->nr_ops[BLOCK_ACCT_WRITE];
        s->stats->failed_rd_operations = stats->failed_ops[BLOCK_ACCT_READ];
        s->stats->failed_wr_operations = stats->failed_ops[BLOCK_ACCT_WRITE];
        s->stats->failed_flush_operations = stats->failed_ops[BLOCK_ACCT_FLUSH];
        s->stats->invalid_rd_operations = stats->invalid_ops[BLOCK_ACCT_READ];
        s->stats->invalid_wr_operations = stats->invalid_ops[BLOCK_ACCT_WRITE];
        s->stats->invalid_flush_operations =
            stats->invalid_ops[BLOCK_ACCT_FLUSH];
        s->stats->rd_merged = stats->merged[BLOCK_ACCT_READ];
        s->stats->wr_merged = stats->merged[BLOCK_ACCT_WRITE];
        s->stats->flush_operations = stats->nr_ops[BLOCK_ACCT_FLUSH];
        s->stats->wr_total_time_ns = stats->total_time_ns[BLOCK_ACCT_WRITE];
        s->stats->rd_total_time_ns = stats->total_time_ns[BLOCK_ACCT_READ];
        s->stats->flush_total_time_ns = stats->total_time_ns[BLOCK_ACCT_FLUSH];
        s->stats->has_idle_time_ns = stats->last_access_time_ns > 0;
        if (s->stats->has_idle_time_ns) {
            s->stats->idle_time_ns = block_acct_idle_time_ns(stats);
        }
    }
    s->stats->wr_highest_offset = bs->wr_highest_offset;
    if (bs->file) {
        s->has_parent = true;
        s->parent = bdrv_query_stats(bs->file->bs, query_backing);
    }
    if (query_backing && bs->backing) {
        s->has_backing = true;
        s->backing = bdrv_query_stats(bs->backing->bs, query_backing);
    }
    return s;
}


static uint64_t hb_regs_read(void *opaque, hwaddr offset,

                             unsigned size)

{

    uint32_t *regs = opaque;

    uint32_t value = regs[offset/4];

    if ((offset == 0x100) || (offset == 0x108) || (offset == 0x10C)) {

        value |= 0x30000000;

    }

    return value;

}


static unsigned acpi_data_len(GArray *table)

{

#if GLIB_CHECK_VERSION(2, 14, 0)

    assert(g_array_get_element_size(table) == 1);

#endif

    return table->len;

}


static void init_excp_970 (CPUPPCState *env)

{

#if !defined(CONFIG_USER_ONLY)

    env->excp_vectors[POWERPC_EXCP_RESET]    = 0x00000100;

    env->excp_vectors[POWERPC_EXCP_MCHECK]   = 0x00000200;

    env->excp_vectors[POWERPC_EXCP_DSI]      = 0x00000300;

    env->excp_vectors[POWERPC_EXCP_DSEG]     = 0x00000380;

    env->excp_vectors[POWERPC_EXCP_ISI]      = 0x00000400;

    env->excp_vectors[POWERPC_EXCP_ISEG]     = 0x00000480;

    env->excp_vectors[POWERPC_EXCP_EXTERNAL] = 0x00000500;

    env->excp_vectors[POWERPC_EXCP_ALIGN]    = 0x00000600;

    env->excp_vectors[POWERPC_EXCP_PROGRAM]  = 0x00000700;

    env->excp_vectors[POWERPC_EXCP_FPU]      = 0x00000800;

    env->excp_vectors[POWERPC_EXCP_DECR]     = 0x00000900;

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

    env->excp_vectors[POWERPC_EXCP_HDECR]    = 0x00000980;

#endif

    env->excp_vectors[POWERPC_EXCP_SYSCALL]  = 0x00000C00;

    env->excp_vectors[POWERPC_EXCP_TRACE]    = 0x00000D00;

    env->excp_vectors[POWERPC_EXCP_PERFM]    = 0x00000F00;

    env->excp_vectors[POWERPC_EXCP_VPU]      = 0x00000F20;

    env->excp_vectors[POWERPC_EXCP_IABR]     = 0x00001300;

    env->excp_vectors[POWERPC_EXCP_MAINT]    = 0x00001600;

    env->excp_vectors[POWERPC_EXCP_VPUA]     = 0x00001700;

    env->excp_vectors[POWERPC_EXCP_THERM]    = 0x00001800;

    env->excp_prefix   = 0x00000000FFF00000ULL;

    /* Hardware reset vector */

    env->hreset_vector = 0x0000000000000100ULL;

#endif

}


static int proxy_ioc_getversion(FsContext *fs_ctx, V9fsPath *path,

                                mode_t st_mode, uint64_t *st_gen)

{

    int err;

    /* Do not try to open special files like device nodes, fifos etc

     * we can get fd for regular files and directories only

     */

    if (!S_ISREG(st_mode) && !S_ISDIR(st_mode)) {

        errno = ENOTTY;

        return -1;

    }

    err = v9fs_request(fs_ctx->private, T_GETVERSION, st_gen, "s", path);

    if (err < 0) {

        errno = -err;

        err = -1;

    }

    return err;

}


void vga_common_init(VGACommonState *s)

{

    int i, j, v, b;

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

        v = 0;

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

            v |= ((i >> j) & 1) << (j * 4);

        }

        expand4[i] = v;

        v = 0;

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

            v |= ((i >> (2 * j)) & 3) << (j * 4);

        }

        expand2[i] = v;

    }

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

        v = 0;

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

            b = ((i >> j) & 1);

            v |= b << (2 * j);

            v |= b << (2 * j + 1);

        }

        expand4to8[i] = v;

    }

    /* valid range: 1 MB -> 256 MB */

    s->vram_size = 1024 * 1024;

    while (s->vram_size < (s->vram_size_mb << 20) &&

           s->vram_size < (256 << 20)) {

        s->vram_size <<= 1;

    }

    s->vram_size_mb = s->vram_size >> 20;

    s->is_vbe_vmstate = 1;

    memory_region_init_ram(&s->vram, "vga.vram", s->vram_size);

    vmstate_register_ram_global(&s->vram);

    xen_register_framebuffer(&s->vram);

    s->vram_ptr = memory_region_get_ram_ptr(&s->vram);

    s->get_bpp = vga_get_bpp;

    s->get_offsets = vga_get_offsets;

    s->get_resolution = vga_get_resolution;

    s->update = vga_update_display;

    s->invalidate = vga_invalidate_display;

    s->screen_dump = vga_screen_dump;

    s->text_update = vga_update_text;

    switch (vga_retrace_method) {

    case VGA_RETRACE_DUMB:

        s->retrace = vga_dumb_retrace;

        s->update_retrace_info = vga_dumb_update_retrace_info;

        break;

    case VGA_RETRACE_PRECISE:

        s->retrace = vga_precise_retrace;

        s->update_retrace_info = vga_precise_update_retrace_info;

        break;

    }

    vga_dirty_log_start(s);

}


static uint32_t do_mac_read(lan9118_state *s, int reg)

{

    switch (reg) {

    case MAC_CR:

        return s->mac_cr;

    case MAC_ADDRH:

        return s->conf.macaddr.a[4] | (s->conf.macaddr.a[5] << 8);

    case MAC_ADDRL:

        return s->conf.macaddr.a[0] | (s->conf.macaddr.a[1] << 8)

               | (s->conf.macaddr.a[2] << 16) | (s->conf.macaddr.a[3] << 24);

    case MAC_HASHH:

        return s->mac_hashh;

        break;

    case MAC_HASHL:

        return s->mac_hashl;

        break;

    case MAC_MII_ACC:

        return s->mac_mii_acc;

    case MAC_MII_DATA:

        return s->mac_mii_data;

    case MAC_FLOW:

        return s->mac_flow;

    default:

        hw_error("lan9118: Unimplemented MAC register read: %d\n",

                 s->mac_cmd & 0xf);

    }

}


void visit_type_uint32(Visitor *v, uint32_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (v->type_uint32) {

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

    } else {

        value = *obj;

        v->type_int64(v, &value, name, errp);

        if (value < 0 || value > UINT32_MAX) {

            /* FIXME questionable reuse of errp if callback changed

               value on error */

            error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                       name ? name : "null", "uint32_t");

            return;

        }

        *obj = value;

    }

}


static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    int size, stream_id, flags, discard;

    int64_t pts, last_IP_pts;

    size= decode_frame_header(nut, &flags, &pts, &stream_id, frame_code);

    if(size < 0)

        return -1;

    if (flags & FLAG_KEY)

        nut->stream[stream_id].skip_until_key_frame=0;

    discard= s->streams[ stream_id ]->discard;

    last_IP_pts= s->streams[ stream_id ]->last_IP_pts;

    if(  (discard >= AVDISCARD_NONKEY && !(flags & FLAG_KEY))

       ||(discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE && last_IP_pts > pts)

       || discard >= AVDISCARD_ALL

       || nut->stream[stream_id].skip_until_key_frame){

        url_fskip(bc, size);

        return 1;

    }

    av_get_packet(bc, pkt, size);

    pkt->stream_index = stream_id;

    if (flags & FLAG_KEY)

        pkt->flags |= PKT_FLAG_KEY;

    pkt->pts = pts;

    return 0;

}


static void bdrv_assign_node_name(BlockDriverState *bs,

                                  const char *node_name,

                                  Error **errp)

{

    if (!node_name) {

        return;

    }

    /* empty string node name is invalid */

    if (node_name[0] == '\0') {

        error_setg(errp, "Empty node name");

        return;

    }

    /* takes care of avoiding namespaces collisions */

    if (bdrv_find(node_name)) {

        error_setg(errp, "node-name=%s is conflicting with a device id",

                   node_name);

        return;

    }

    /* takes care of avoiding duplicates node names */

    if (bdrv_find_node(node_name)) {

        error_setg(errp, "Duplicate node name");

        return;

    }

    /* copy node name into the bs and insert it into the graph list */

    pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);

    QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);

}


int bdrv_can_snapshot(BlockDriverState *bs)

{

    BlockDriver *drv = bs->drv;

    if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {

        return 0;

    }

    if (!drv->bdrv_snapshot_create) {

        if (bs->file != NULL) {

            return bdrv_can_snapshot(bs->file);

        }

        return 0;

    }

    return 1;

}


int float32_le_quiet( float32 a, float32 b STATUS_PARAM )

{

    flag aSign, bSign;

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

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

       ) {

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

            float_raise( float_flag_invalid STATUS_VAR);

        }

        return 0;

    }

    aSign = extractFloat32Sign( a );

    bSign = extractFloat32Sign( b );

    if ( aSign != bSign ) return aSign || ( (bits32) ( ( a | b )<<1 ) == 0 );

    return ( a == b ) || ( aSign ^ ( a < b ) );

}


static AioContext *block_job_get_aio_context(BlockJob *job)

{

    return job->deferred_to_main_loop ?

           qemu_get_aio_context() :

           blk_get_aio_context(job->blk);

}


static int gen_jz_ecx_string(DisasContext *s, target_ulong next_eip)

{

    int l1, l2;

    l1 = gen_new_label();

    l2 = gen_new_label();

    gen_op_jnz_ecx[s->aflag](l1);

    gen_set_label(l2);

    gen_jmp_tb(s, next_eip, 1);

    gen_set_label(l1);

    return l2;

}


const char *qjson_get_str(QJSON *json)

{

    return qstring_get_str(json->str);

}


void arm_v7m_cpu_do_interrupt(CPUState *cs)

{

    ARMCPU *cpu = ARM_CPU(cs);

    CPUARMState *env = &cpu->env;

    uint32_t lr;

    arm_log_exception(cs->exception_index);

    /* For exceptions we just mark as pending on the NVIC, and let that

       handle it.  */

    switch (cs->exception_index) {

    case EXCP_UDEF:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);

        env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;

        break;

    case EXCP_NOCP:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);

        env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;

        break;

    case EXCP_INVSTATE:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);

        env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;

        break;

    case EXCP_SWI:

        /* The PC already points to the next instruction.  */

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC);

        break;

    case EXCP_PREFETCH_ABORT:

    case EXCP_DATA_ABORT:

        /* Note that for M profile we don't have a guest facing FSR, but

         * the env->exception.fsr will be populated by the code that

         * raises the fault, in the A profile short-descriptor format.

         */

        switch (env->exception.fsr & 0xf) {

        case 0x8: /* External Abort */

            switch (cs->exception_index) {

            case EXCP_PREFETCH_ABORT:

                env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;

                qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");

                break;

            case EXCP_DATA_ABORT:

                env->v7m.cfsr[M_REG_NS] |=

                    (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);

                env->v7m.bfar = env->exception.vaddress;

                qemu_log_mask(CPU_LOG_INT,

                              "...with CFSR.PRECISERR and BFAR 0x%x\n",

                              env->v7m.bfar);

                break;

            }

            armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS);

            break;

        default:

            /* All other FSR values are either MPU faults or "can't happen

             * for M profile" cases.

             */

            switch (cs->exception_index) {

            case EXCP_PREFETCH_ABORT:

                env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;

                qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");

                break;

            case EXCP_DATA_ABORT:

                env->v7m.cfsr[env->v7m.secure] |=

                    (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);

                env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;

                qemu_log_mask(CPU_LOG_INT,

                              "...with CFSR.DACCVIOL and MMFAR 0x%x\n",

                              env->v7m.mmfar[env->v7m.secure]);

                break;

            }

            armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM);

            break;

        }

        break;

    case EXCP_BKPT:

        if (semihosting_enabled()) {

            int nr;

            nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;

            if (nr == 0xab) {

                env->regs[15] += 2;

                qemu_log_mask(CPU_LOG_INT,

                              "...handling as semihosting call 0x%x\n",

                              env->regs[0]);

                env->regs[0] = do_arm_semihosting(env);

                return;

            }

        }

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG);

        break;

    case EXCP_IRQ:

        break;

    case EXCP_EXCEPTION_EXIT:

        do_v7m_exception_exit(cpu);

        return;

    default:

        cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);

        return; /* Never happens.  Keep compiler happy.  */

    }

    lr = 0xfffffff1;

    if (env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK) {

        lr |= 4;

    }

    if (!arm_v7m_is_handler_mode(env)) {

        lr |= 8;

    }

    v7m_push_stack(cpu);

    v7m_exception_taken(cpu, lr);

    qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);

}


static av_cold int find_component(OMXContext *omx_context, void *logctx,

                                  const char *role, char *str, int str_size)

{

    OMX_U32 i, num = 0;

    char **components;

    int ret = 0;

#if CONFIG_OMX_RPI

    if (av_strstart(role, "video_encoder.", NULL)) {

        av_strlcpy(str, "OMX.broadcom.video_encode", str_size);

        return 0;

    }

#endif

    omx_context->ptr_GetComponentsOfRole((OMX_STRING) role, &num, NULL);

    if (!num) {

        av_log(logctx, AV_LOG_WARNING, "No component for role %s found\n", role);

        return AVERROR_ENCODER_NOT_FOUND;

    }

    components = av_mallocz(sizeof(char*) * num);

    if (!components)

        return AVERROR(ENOMEM);

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

        components[i] = av_mallocz(OMX_MAX_STRINGNAME_SIZE);

        if (!components) {

            ret = AVERROR(ENOMEM);

            goto end;

        }

    }

    omx_context->ptr_GetComponentsOfRole((OMX_STRING) role, &num, (OMX_U8**) components);

    av_strlcpy(str, components[0], str_size);

end:

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

        av_free(components[i]);

    av_free(components);

    return ret;

}


set_mdic(E1000State *s, int index, uint32_t val)

{

    uint32_t data = val & E1000_MDIC_DATA_MASK;

    uint32_t addr = ((val & E1000_MDIC_REG_MASK) >> E1000_MDIC_REG_SHIFT);

    if ((val & E1000_MDIC_PHY_MASK) >> E1000_MDIC_PHY_SHIFT != 1) // phy #

        val = s->mac_reg[MDIC] | E1000_MDIC_ERROR;

    else if (val & E1000_MDIC_OP_READ) {

        DBGOUT(MDIC, "MDIC read reg 0x%x\n", addr);

        if (!(phy_regcap[addr] & PHY_R)) {

            DBGOUT(MDIC, "MDIC read reg %x unhandled\n", addr);

            val |= E1000_MDIC_ERROR;

        } else

            val = (val ^ data) | s->phy_reg[addr];

    } else if (val & E1000_MDIC_OP_WRITE) {

        DBGOUT(MDIC, "MDIC write reg 0x%x, value 0x%x\n", addr, data);

        if (!(phy_regcap[addr] & PHY_W)) {

            DBGOUT(MDIC, "MDIC write reg %x unhandled\n", addr);

            val |= E1000_MDIC_ERROR;

        } else {

            if (addr < NPHYWRITEOPS && phyreg_writeops[addr]) {

                phyreg_writeops[addr](s, index, data);

            }

            s->phy_reg[addr] = data;

        }

    }

    s->mac_reg[MDIC] = val | E1000_MDIC_READY;

    if (val & E1000_MDIC_INT_EN) {

        set_ics(s, 0, E1000_ICR_MDAC);

    }

}


void phys_mem_set_alloc(void *(*alloc)(size_t))

{

    phys_mem_alloc = alloc;

}


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

 {

    V9fsState *s;

    int i, len;

    struct stat stat;

    FsTypeEntry *fse;

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

                                    VIRTIO_ID_9P,

                                    sizeof(struct virtio_9p_config)+

                                    MAX_TAG_LEN,

                                    sizeof(V9fsState));

    /* initialize pdu allocator */

    QLIST_INIT(&s->free_list);

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

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

    }

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

    fse = get_fsdev_fsentry(conf->fsdev_id);

    if (!fse) {

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

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

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

        exit(1);

    }

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

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

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

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

                conf->fsdev_id);

        exit(1);

    }

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

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

        s->ctx.fs_sm = SM_PASSTHROUGH;

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

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

         * Client user credentials are saved in extended attributes.

         */

        s->ctx.fs_sm = SM_MAPPED;

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

        /*

         * Files on the fileserver are set to QEMU credentials.

         */

        s->ctx.fs_sm = SM_NONE;

    } else {

        fprintf(stderr, "Default to security_model=none. You may want"

                " enable advanced security model using "

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

                "security_model=mapped\n");

        s->ctx.fs_sm = SM_NONE;

    }

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

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

        exit(1);

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

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

        exit(1);

    }

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

    len = strlen(conf->tag);

    if (len > MAX_TAG_LEN) {

        len = MAX_TAG_LEN;

    }

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

    s->tag = qemu_malloc(len);

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

    s->tag_len = len;

    s->ctx.uid = -1;

    s->ops = fse->ops;

    s->vdev.get_features = virtio_9p_get_features;

    s->config_size = sizeof(struct virtio_9p_config) +

                        s->tag_len;

    s->vdev.get_config = virtio_9p_get_config;

    return &s->vdev;

}


static void coroutine_fn aio_read_response(void *opaque)

{

    SheepdogObjRsp rsp;

    BDRVSheepdogState *s = opaque;

    int fd = s->fd;

    int ret;

    AIOReq *aio_req = NULL;

    SheepdogAIOCB *acb;

    uint64_t idx;

    if (QLIST_EMPTY(&s->inflight_aio_head)) {

        goto out;

    }

    /* read a header */

    ret = qemu_co_recv(fd, &rsp, sizeof(rsp));

    if (ret < 0) {

        error_report("failed to get the header, %s", strerror(errno));

        goto out;

    }

    /* find the right aio_req from the inflight aio list */

    QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {

        if (aio_req->id == rsp.id) {

            break;

        }

    }

    if (!aio_req) {

        error_report("cannot find aio_req %x", rsp.id);

        goto out;

    }

    acb = aio_req->aiocb;

    switch (acb->aiocb_type) {

    case AIOCB_WRITE_UDATA:

        /* this coroutine context is no longer suitable for co_recv

         * because we may send data to update vdi objects */

        s->co_recv = NULL;

        if (!is_data_obj(aio_req->oid)) {

            break;

        }

        idx = data_oid_to_idx(aio_req->oid);

        if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {

            /*

             * If the object is newly created one, we need to update

             * the vdi object (metadata object).  min_dirty_data_idx

             * and max_dirty_data_idx are changed to include updated

             * index between them.

             */

            if (rsp.result == SD_RES_SUCCESS) {

                s->inode.data_vdi_id[idx] = s->inode.vdi_id;

                s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);

                s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);

            }

            /*

             * Some requests may be blocked because simultaneous

             * create requests are not allowed, so we search the

             * pending requests here.

             */

            send_pending_req(s, aio_req->oid);

        }

        break;

    case AIOCB_READ_UDATA:

        ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,

                            aio_req->iov_offset, rsp.data_length);

        if (ret < 0) {

            error_report("failed to get the data, %s", strerror(errno));

            goto out;

        }

        break;

    case AIOCB_FLUSH_CACHE:

        if (rsp.result == SD_RES_INVALID_PARMS) {

            DPRINTF("disable cache since the server doesn't support it\n");

            s->cache_flags = SD_FLAG_CMD_DIRECT;

            rsp.result = SD_RES_SUCCESS;

        }

        break;

    case AIOCB_DISCARD_OBJ:

        switch (rsp.result) {

        case SD_RES_INVALID_PARMS:

            error_report("sheep(%s) doesn't support discard command",

                         s->host_spec);

            rsp.result = SD_RES_SUCCESS;

            s->discard_supported = false;

            break;

        case SD_RES_SUCCESS:

            idx = data_oid_to_idx(aio_req->oid);

            s->inode.data_vdi_id[idx] = 0;

            break;

        default:

            break;

        }

    }

    switch (rsp.result) {

    case SD_RES_SUCCESS:

        break;

    case SD_RES_READONLY:

        ret = resend_aioreq(s, aio_req);

        if (ret == SD_RES_SUCCESS) {

            goto out;

        }

        /* fall through */

    default:

        acb->ret = -EIO;

        error_report("%s", sd_strerror(rsp.result));

        break;

    }

    free_aio_req(s, aio_req);

    if (!acb->nr_pending) {

        /*

         * We've finished all requests which belong to the AIOCB, so

         * we can switch back to sd_co_readv/writev now.

         */

        acb->aio_done_func(acb);

    }

out:

    s->co_recv = NULL;

}


static void add_flagname_to_bitmaps(char *flagname, uint32_t *features,

                                    uint32_t *ext_features,

                                    uint32_t *ext2_features,

                                    uint32_t *ext3_features)

{

    int i;

    int found = 0;

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

        if (feature_name[i] && !strcmp (flagname, feature_name[i])) {

            *features |= 1 << i;

            found = 1;

        }

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

        if (ext_feature_name[i] && !strcmp (flagname, ext_feature_name[i])) {

            *ext_features |= 1 << i;

            found = 1;

        }

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

        if (ext2_feature_name[i] && !strcmp (flagname, ext2_feature_name[i])) {

            *ext2_features |= 1 << i;

            found = 1;

        }

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

        if (ext3_feature_name[i] && !strcmp (flagname, ext3_feature_name[i])) {

            *ext3_features |= 1 << i;

            found = 1;

        }

    if (!found) {

        fprintf(stderr, "CPU feature %s not found\n", flagname);

    }

}


static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,

                             const char *replaces,

                             int64_t speed, uint32_t granularity,

                             int64_t buf_size,

                             BlockdevOnError on_source_error,

                             BlockdevOnError on_target_error,

                             bool unmap,

                             BlockCompletionFunc *cb,

                             void *opaque, Error **errp,

                             const BlockJobDriver *driver,

                             bool is_none_mode, BlockDriverState *base)

{

    MirrorBlockJob *s;

    BlockDriverState *replaced_bs;

    if (granularity == 0) {

        granularity = bdrv_get_default_bitmap_granularity(target);

    }

    assert ((granularity & (granularity - 1)) == 0);

    if (buf_size < 0) {

        error_setg(errp, "Invalid parameter 'buf-size'");

        return;

    }

    if (buf_size == 0) {

        buf_size = DEFAULT_MIRROR_BUF_SIZE;

    }

    /* We can't support this case as long as the block layer can't handle

     * multiple BlockBackends per BlockDriverState. */

    if (replaces) {

        replaced_bs = bdrv_lookup_bs(replaces, replaces, errp);

        if (replaced_bs == NULL) {

            return;

        }

    } else {

        replaced_bs = bs;

    }

    if (replaced_bs->blk && target->blk) {

        error_setg(errp, "Can't create node with two BlockBackends");

        return;

    }

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

    if (!s) {

        return;

    }

    s->replaces = g_strdup(replaces);

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->target = target;

    s->is_none_mode = is_none_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = ROUND_UP(buf_size, granularity);

    s->unmap = unmap;

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);

    if (!s->dirty_bitmap) {

        g_free(s->replaces);

        block_job_unref(&s->common);

        return;

    }

    bdrv_op_block_all(s->target, s->common.blocker);

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

    trace_mirror_start(bs, s, s->common.co, opaque);

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

}


DisplaySurface *qemu_create_displaysurface_from(int width, int height, int bpp,

                                                int linesize, uint8_t *data)

{

    DisplaySurface *surface = g_new0(DisplaySurface, 1);

    surface->pf = qemu_default_pixelformat(bpp);

    surface->format = qemu_pixman_get_format(&surface->pf);

    assert(surface->format != 0);

    surface->image = pixman_image_create_bits(surface->format,

                                              width, height,

                                              (void *)data, linesize);

    assert(surface->image != NULL);

#ifdef HOST_WORDS_BIGENDIAN

    surface->flags = QEMU_BIG_ENDIAN_FLAG;

#endif

    return surface;

}


static void spapr_phb_reset(DeviceState *qdev)

{

    SysBusDevice *s = SYS_BUS_DEVICE(qdev);

    sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);

    /* Reset the IOMMU state */

    spapr_tce_reset(sphb->tcet);

}


static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs,

	int64_t sector_num, int nb_sectors, int* n)

{

    BDRVVVFATState* s = bs->opaque;

    *n = s->sector_count - sector_num;

    if (*n > nb_sectors) {

        *n = nb_sectors;

    } else if (*n < 0) {

        return 0;

    }

    return BDRV_BLOCK_DATA;

}


static av_cold int nvenc_check_cuda(AVCodecContext *avctx)

{

    int device_count = 0;

    CUdevice cu_device = 0;

    char gpu_name[128];

    int smminor = 0, smmajor = 0;

    int i, smver, target_smver;

    NvencContext *ctx = avctx->priv_data;

    NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;

    switch (avctx->codec->id) {

    case AV_CODEC_ID_H264:

        target_smver = ctx->data_pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;

        break;

    case AV_CODEC_ID_H265:

        target_smver = 0x52;

        break;

    default:

        av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");

        goto error;

    }

    if (ctx->preset >= PRESET_LOSSLESS_DEFAULT)

        target_smver = 0x52;

    if (!nvenc_dyload_cuda(avctx))

        return 0;

    if (dl_fn->nvenc_device_count > 0)

        return 1;

    check_cuda_errors(dl_fn->cu_init(0));

    check_cuda_errors(dl_fn->cu_device_get_count(&device_count));

    if (!device_count) {

        av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");

        goto error;

    }

    av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);

    dl_fn->nvenc_device_count = 0;

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

        check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));

        check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));

        check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));

        smver = (smmajor << 4) | smminor;

        av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= target_smver) ? "Available" : "Not Available");

        if (smver >= target_smver)

            dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;

    }

    if (!dl_fn->nvenc_device_count) {

        av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");

        goto error;

    }

    return 1;

error:

    dl_fn->nvenc_device_count = 0;

    return 0;

}