static sd_rsp_type_t sd_normal_command(SDState *sd,
                                       SDRequest req)
{
    uint32_t rca = 0x0000;
    uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;
    if (sd_cmd_type[req.cmd] == sd_ac || sd_cmd_type[req.cmd] == sd_adtc)
        rca = req.arg >> 16;
    DPRINTF("CMD%d 0x%08x state %d\n", req.cmd, req.arg, sd->state);
    switch (req.cmd) {
    /* Basic commands (Class 0 and Class 1) */
    case 0:	/* CMD0:   GO_IDLE_STATE */
        switch (sd->state) {
        case sd_inactive_state:
            return sd->spi ? sd_r1 : sd_r0;
        default:
            sd->state = sd_idle_state;
            sd_reset(sd, sd->bdrv);
            return sd->spi ? sd_r1 : sd_r0;
        }
        break;
    case 1:	/* CMD1:   SEND_OP_CMD */
        if (!sd->spi)
            goto bad_cmd;
        sd->state = sd_transfer_state;
        return sd_r1;
    case 2:	/* CMD2:   ALL_SEND_CID */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->state) {
        case sd_ready_state:
            sd->state = sd_identification_state;
            return sd_r2_i;
        default:
            break;
        }
        break;
    case 3:	/* CMD3:   SEND_RELATIVE_ADDR */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->state) {
        case sd_identification_state:
        case sd_standby_state:
            sd->state = sd_standby_state;
            sd_set_rca(sd);
            return sd_r6;
        default:
            break;
        }
        break;
    case 4:	/* CMD4:   SEND_DSR */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->state) {
        case sd_standby_state:
            break;
        default:
            break;
        }
        break;
    case 5: /* CMD5: reserved for SDIO cards */
    case 6:	/* CMD6:   SWITCH_FUNCTION */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->mode) {
        case sd_data_transfer_mode:
            sd_function_switch(sd, req.arg);
            sd->state = sd_sendingdata_state;
            sd->data_start = 0;
            sd->data_offset = 0;
            return sd_r1;
        default:
            break;
        }
        break;
    case 7:	/* CMD7:   SELECT/DESELECT_CARD */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->state) {
        case sd_standby_state:
            if (sd->rca != rca)
            sd->state = sd_transfer_state;
            return sd_r1b;
        case sd_transfer_state:
        case sd_sendingdata_state:
            if (sd->rca == rca)
                break;
            sd->state = sd_standby_state;
            return sd_r1b;
        case sd_disconnect_state:
            if (sd->rca != rca)
            sd->state = sd_programming_state;
            return sd_r1b;
        case sd_programming_state:
            if (sd->rca == rca)
                break;
            sd->state = sd_disconnect_state;
            return sd_r1b;
        default:
            break;
        }
        break;
    case 8:	/* CMD8:   SEND_IF_COND */
        /* Physical Layer Specification Version 2.00 command */
        switch (sd->state) {
        case sd_idle_state:
            sd->vhs = 0;
            /* No response if not exactly one VHS bit is set.  */
            if (!(req.arg >> 8) || (req.arg >> ffs(req.arg & ~0xff)))
                return sd->spi ? sd_r7 : sd_r0;
            /* Accept.  */
            sd->vhs = req.arg;
            return sd_r7;
        default:
            break;
        }
        break;
    case 9:	/* CMD9:   SEND_CSD */
        switch (sd->state) {
        case sd_standby_state:
            if (sd->rca != rca)
            return sd_r2_s;
        case sd_transfer_state:
            if (!sd->spi)
                break;
            sd->state = sd_sendingdata_state;
            memcpy(sd->data, sd->csd, 16);
            sd->data_start = addr;
            sd->data_offset = 0;
            return sd_r1;
        default:
            break;
        }
        break;
    case 10:	/* CMD10:  SEND_CID */
        switch (sd->state) {
        case sd_standby_state:
            if (sd->rca != rca)
            return sd_r2_i;
        case sd_transfer_state:
            if (!sd->spi)
                break;
            sd->state = sd_sendingdata_state;
            memcpy(sd->data, sd->cid, 16);
            sd->data_start = addr;
            sd->data_offset = 0;
            return sd_r1;
        default:
            break;
        }
        break;
    case 11:	/* CMD11:  READ_DAT_UNTIL_STOP */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->state) {
        case sd_transfer_state:
            sd->state = sd_sendingdata_state;
            sd->data_start = req.arg;
            sd->data_offset = 0;
            if (sd->data_start + sd->blk_len > sd->size)
                sd->card_status |= ADDRESS_ERROR;
        default:
            break;
        }
        break;
    case 12:	/* CMD12:  STOP_TRANSMISSION */
        switch (sd->state) {
        case sd_sendingdata_state:
            sd->state = sd_transfer_state;
            return sd_r1b;
        case sd_receivingdata_state:
            sd->state = sd_programming_state;
            /* Bzzzzzzztt .... Operation complete.  */
            sd->state = sd_transfer_state;
            return sd_r1b;
        default:
            break;
        }
        break;
    case 13:	/* CMD13:  SEND_STATUS */
        switch (sd->mode) {
        case sd_data_transfer_mode:
            if (sd->rca != rca)
            return sd_r1;
        default:
            break;
        }
        break;
    case 15:	/* CMD15:  GO_INACTIVE_STATE */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->mode) {
        case sd_data_transfer_mode:
            if (sd->rca != rca)
            sd->state = sd_inactive_state;
        default:
            break;
        }
        break;
    /* Block read commands (Classs 2) */
    case 16:	/* CMD16:  SET_BLOCKLEN */
        switch (sd->state) {
        case sd_transfer_state:
            if (req.arg > (1 << HWBLOCK_SHIFT))
                sd->card_status |= BLOCK_LEN_ERROR;
            else
                sd->blk_len = req.arg;
            return sd_r1;
        default:
            break;
        }
        break;
    case 17:	/* CMD17:  READ_SINGLE_BLOCK */
        switch (sd->state) {
        case sd_transfer_state:
            sd->state = sd_sendingdata_state;
            sd->data_start = addr;
            sd->data_offset = 0;
            if (sd->data_start + sd->blk_len > sd->size)
                sd->card_status |= ADDRESS_ERROR;
            return sd_r1;
        default:
            break;
        }
        break;
    case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */
        switch (sd->state) {
        case sd_transfer_state:
            sd->state = sd_sendingdata_state;
            sd->data_start = addr;
            sd->data_offset = 0;
            if (sd->data_start + sd->blk_len > sd->size)
                sd->card_status |= ADDRESS_ERROR;
            return sd_r1;
        default:
            break;
        }
        break;
    /* Block write commands (Class 4) */
    case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */
        if (sd->spi)
            goto unimplemented_cmd;
        switch (sd->state) {
        case sd_transfer_state:
            /* Writing in SPI mode not implemented.  */
            if (sd->spi)
                break;
            sd->state = sd_receivingdata_state;
            sd->data_start = addr;
            sd->data_offset = 0;
            sd->blk_written = 0;
            if (sd->data_start + sd->blk_len > sd->size)
                sd->card_status |= ADDRESS_ERROR;
            if (sd_wp_addr(sd, sd->data_start))
                sd->card_status |= WP_VIOLATION;
            if (sd->csd[14] & 0x30)
                sd->card_status |= WP_VIOLATION;
            return sd_r1;
        default:
            break;
        }
        break;
    case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */
        if (sd->spi)
            goto unimplemented_cmd;
        switch (sd->state) {
        case sd_transfer_state:
            /* Writing in SPI mode not implemented.  */
            if (sd->spi)
                break;
            sd->state = sd_receivingdata_state;
            sd->data_start = addr;
            sd->data_offset = 0;
            sd->blk_written = 0;
            if (sd->data_start + sd->blk_len > sd->size)
                sd->card_status |= ADDRESS_ERROR;
            if (sd_wp_addr(sd, sd->data_start))
                sd->card_status |= WP_VIOLATION;
            if (sd->csd[14] & 0x30)
                sd->card_status |= WP_VIOLATION;
            return sd_r1;
        default:
            break;
        }
        break;
    case 26:	/* CMD26:  PROGRAM_CID */
        if (sd->spi)
            goto bad_cmd;
        switch (sd->state) {
        case sd_transfer_state:
            sd->state = sd_receivingdata_state;
            sd->data_start = 0;
            sd->data_offset = 0;
            return sd_r1;
        default:
            break;
        }
        break;
    case 27:	/* CMD27:  PROGRAM_CSD */
        if (sd->spi)
            goto unimplemented_cmd;
        switch (sd->state) {
        case sd_transfer_state:
            sd->state = sd_receivingdata_state;
            sd->data_start = 0;
            sd->data_offset = 0;
            return sd_r1;
        default:
            break;
        }
        break;
    /* Write protection (Class 6) */
    case 28:	/* CMD28:  SET_WRITE_PROT */
        switch (sd->state) {
        case sd_transfer_state:
            if (addr >= sd->size) {
                sd->card_status = ADDRESS_ERROR;
                return sd_r1b;
            }
            sd->state = sd_programming_state;
            sd->wp_groups[addr >> (HWBLOCK_SHIFT +
                            SECTOR_SHIFT + WPGROUP_SHIFT)] = 1;
            /* Bzzzzzzztt .... Operation complete.  */
            sd->state = sd_transfer_state;
            return sd_r1b;
        default:
            break;
        }
        break;
    case 29:	/* CMD29:  CLR_WRITE_PROT */
        switch (sd->state) {
        case sd_transfer_state:
            if (addr >= sd->size) {
                sd->card_status = ADDRESS_ERROR;
                return sd_r1b;
            }
            sd->state = sd_programming_state;
            sd->wp_groups[addr >> (HWBLOCK_SHIFT +
                            SECTOR_SHIFT + WPGROUP_SHIFT)] = 0;
            /* Bzzzzzzztt .... Operation complete.  */
            sd->state = sd_transfer_state;
            return sd_r1b;
        default:
            break;
        }
        break;
    case 30:	/* CMD30:  SEND_WRITE_PROT */
        switch (sd->state) {
        case sd_transfer_state:
            sd->state = sd_sendingdata_state;
            *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);
            sd->data_start = addr;
            sd->data_offset = 0;
            return sd_r1b;
        default:
            break;
        }
        break;
    /* Erase commands (Class 5) */
    case 32:	/* CMD32:  ERASE_WR_BLK_START */
        switch (sd->state) {
        case sd_transfer_state:
            sd->erase_start = req.arg;
            return sd_r1;
        default:
            break;
        }
        break;
    case 33:	/* CMD33:  ERASE_WR_BLK_END */
        switch (sd->state) {
        case sd_transfer_state:
            sd->erase_end = req.arg;
            return sd_r1;
        default:
            break;
        }
        break;
    case 38:	/* CMD38:  ERASE */
        switch (sd->state) {
        case sd_transfer_state:
            if (sd->csd[14] & 0x30) {
                sd->card_status |= WP_VIOLATION;
                return sd_r1b;
            }
            sd->state = sd_programming_state;
            sd_erase(sd);
            /* Bzzzzzzztt .... Operation complete.  */
            sd->state = sd_transfer_state;
            return sd_r1b;
        default:
            break;
        }
        break;
    /* Lock card commands (Class 7) */
    case 42:	/* CMD42:  LOCK_UNLOCK */
        if (sd->spi)
            goto unimplemented_cmd;
        switch (sd->state) {
        case sd_transfer_state:
            sd->state = sd_receivingdata_state;
            sd->data_start = 0;
            sd->data_offset = 0;
            return sd_r1;
        default:
            break;
        }
        break;
    /* Application specific commands (Class 8) */
    case 55:	/* CMD55:  APP_CMD */
        if (sd->rca != rca)
        sd->card_status |= APP_CMD;
        return sd_r1;
    case 56:	/* CMD56:  GEN_CMD */
        fprintf(stderr, "SD: GEN_CMD 0x%08x\n", req.arg);
        switch (sd->state) {
        case sd_transfer_state:
            sd->data_offset = 0;
            if (req.arg & 1)
                sd->state = sd_sendingdata_state;
            else
                sd->state = sd_receivingdata_state;
            return sd_r1;
        default:
            break;
        }
        break;
    default:
    bad_cmd:
        fprintf(stderr, "SD: Unknown CMD%i\n", req.cmd);
    unimplemented_cmd:
        /* Commands that are recognised but not yet implemented in SPI mode.  */
        fprintf(stderr, "SD: CMD%i not implemented in SPI mode\n", req.cmd);
    }
    fprintf(stderr, "SD: CMD%i in a wrong state\n", req.cmd);
}


static int32_t tag_tree_size(uint16_t w, uint16_t h)

{

    uint32_t res = 0;

    while (w > 1 || h > 1) {

        res += w * h;

        if (res + 1 >= INT32_MAX)

            return -1;

        w = (w + 1) >> 1;

        h = (h + 1) >> 1;

    }

    return (int32_t)(res + 1);

}


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

{

    MOVContext *mov = s->priv_data;

    ByteIOContext *pb = s->pb;

    MOVTrack *trk = &mov->tracks[pkt->stream_index];

    AVCodecContext *enc = trk->enc;

    unsigned int samplesInChunk = 0;

    int size= pkt->size;

    if (url_is_streamed(s->pb)) return 0; /* Can't handle that */

    if (!size) return 0; /* Discard 0 sized packets */

    if (enc->codec_id == CODEC_ID_AMR_NB) {

        /* We must find out how many AMR blocks there are in one packet */

        static uint16_t packed_size[16] =

            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};

        int len = 0;

        while (len < size && samplesInChunk < 100) {

            len += packed_size[(pkt->data[len] >> 3) & 0x0F];

            samplesInChunk++;

        }

        if(samplesInChunk > 1){

            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");

            return -1;

        }

    } else if (trk->sampleSize)

        samplesInChunk = size/trk->sampleSize;

    else

        samplesInChunk = 1;

    /* copy extradata if it exists */

    if (trk->vosLen == 0 && enc->extradata_size > 0) {

        trk->vosLen = enc->extradata_size;

        trk->vosData = av_malloc(trk->vosLen);

        memcpy(trk->vosData, enc->extradata, trk->vosLen);

    }

    if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {

        /* from x264 or from bytestream h264 */

        /* nal reformating needed */

        int ret = ff_avc_parse_nal_units(pkt->data, &pkt->data, &pkt->size);

        if (ret < 0)

            return ret;

        assert(pkt->size);

        size = pkt->size;

    } else if (enc->codec_id == CODEC_ID_DNXHD && !trk->vosLen) {

        /* copy frame header to create needed atoms */

        if (size < 640)

            return -1;

        trk->vosLen = 640;

        trk->vosData = av_malloc(trk->vosLen);

        memcpy(trk->vosData, pkt->data, 640);

    }

    if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {

        trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));

        if (!trk->cluster)

            return -1;

    }

    trk->cluster[trk->entry].pos = url_ftell(pb);

    trk->cluster[trk->entry].samplesInChunk = samplesInChunk;

    trk->cluster[trk->entry].size = size;

    trk->cluster[trk->entry].entries = samplesInChunk;

    trk->cluster[trk->entry].dts = pkt->dts;

    trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;

    if(enc->codec_type == CODEC_TYPE_VIDEO) {

        if (pkt->dts != pkt->pts)

            trk->hasBframes = 1;

        trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;

        trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);

        if(trk->cluster[trk->entry].key_frame)

            trk->hasKeyframes++;

    }

    trk->entry++;

    trk->sampleCount += samplesInChunk;

    mov->mdat_size += size;

    put_buffer(pb, pkt->data, size);

    put_flush_packet(pb);

    return 0;

}


static inline void RENAME(rgb24tobgr24)(const uint8_t *src, uint8_t *dst, long src_size)

{

    unsigned i;

#if COMPILE_TEMPLATE_MMX

    x86_reg mmx_size= 23 - src_size;

    __asm__ volatile (

        "test             %%"REG_a", %%"REG_a"          \n\t"

        "jns                     2f                     \n\t"

        "movq     "MANGLE(mask24r)", %%mm5              \n\t"

        "movq     "MANGLE(mask24g)", %%mm6              \n\t"

        "movq     "MANGLE(mask24b)", %%mm7              \n\t"

        ".p2align                 4                     \n\t"

        "1:                                             \n\t"

        PREFETCH" 32(%1, %%"REG_a")                     \n\t"

        "movq       (%1, %%"REG_a"), %%mm0              \n\t" // BGR BGR BG

        "movq       (%1, %%"REG_a"), %%mm1              \n\t" // BGR BGR BG

        "movq      2(%1, %%"REG_a"), %%mm2              \n\t" // R BGR BGR B

        "psllq                  $16, %%mm0              \n\t" // 00 BGR BGR

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

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

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

        "por                  %%mm0, %%mm1              \n\t"

        "por                  %%mm2, %%mm1              \n\t"

        "movq      6(%1, %%"REG_a"), %%mm0              \n\t" // BGR BGR BG

        MOVNTQ"               %%mm1,   (%2, %%"REG_a")  \n\t" // RGB RGB RG

        "movq      8(%1, %%"REG_a"), %%mm1              \n\t" // R BGR BGR B

        "movq     10(%1, %%"REG_a"), %%mm2              \n\t" // GR BGR BGR

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

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

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

        "por                  %%mm0, %%mm1              \n\t"

        "por                  %%mm2, %%mm1              \n\t"

        "movq     14(%1, %%"REG_a"), %%mm0              \n\t" // R BGR BGR B

        MOVNTQ"               %%mm1,  8(%2, %%"REG_a")  \n\t" // B RGB RGB R

        "movq     16(%1, %%"REG_a"), %%mm1              \n\t" // GR BGR BGR

        "movq     18(%1, %%"REG_a"), %%mm2              \n\t" // BGR BGR BG

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

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

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

        "por                  %%mm0, %%mm1              \n\t"

        "por                  %%mm2, %%mm1              \n\t"

        MOVNTQ"               %%mm1, 16(%2, %%"REG_a")  \n\t"

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

        " js                     1b                     \n\t"

        "2:                                             \n\t"

        : "+a" (mmx_size)

        : "r" (src-mmx_size), "r"(dst-mmx_size)

    );

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

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

    if (mmx_size==23) return; //finished, was multiple of 8

    src+= src_size;

    dst+= src_size;

    src_size= 23-mmx_size;

    src-= src_size;

    dst-= src_size;

#endif

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

        register uint8_t x;

        x          = src[i + 2];

        dst[i + 1] = src[i + 1];

        dst[i + 2] = src[i + 0];

        dst[i + 0] = x;

    }

}


static inline void mix_2f_2r_to_mono(AC3DecodeContext *ctx)

{

    int i;

    float (*output)[256] = ctx->audio_block.block_output;

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

        output[1][i] = (output[2][i] + output[3][i] + output[4][i]);

    memset(output[2], 0, sizeof(output[2]));

    memset(output[3], 0, sizeof(output[3]));

    memset(output[4], 0, sizeof(output[4]));

}


void OPPROTO op_405_check_ov (void)

{

    do_405_check_ov();

    RETURN();

}


static void put_int32(QEMUFile *f, void *pv, size_t size)

{

    int32_t *v = pv;

    qemu_put_sbe32s(f, v);

}


static ExitStatus trans_fop_wew_0c(DisasContext *ctx, uint32_t insn,

                                   const DisasInsn *di)

{

    unsigned rt = extract32(insn, 0, 5);

    unsigned ra = extract32(insn, 21, 5);

    return do_fop_wew(ctx, rt, ra, di->f_wew);

}


static void ebml_free(EbmlSyntax *syntax, void *data)

{

    int i, j;

    for (i = 0; syntax[i].id; i++) {

        void *data_off = (char *) data + syntax[i].data_offset;

        switch (syntax[i].type) {

        case EBML_STR:

        case EBML_UTF8:

            av_freep(data_off);

            break;

        case EBML_BIN:

            av_freep(&((EbmlBin *) data_off)->data);

            break;

        case EBML_LEVEL1:

        case EBML_NEST:

            if (syntax[i].list_elem_size) {

                EbmlList *list = data_off;

                char *ptr = list->elem;

                for (j = 0; j < list->nb_elem;

                     j++, ptr += syntax[i].list_elem_size)

                    ebml_free(syntax[i].def.n, ptr);

                av_freep(&list->elem);

            } else

                ebml_free(syntax[i].def.n, data_off);

        default:

            break;

        }

    }

}


static int common_bind(struct common *c)

{

    uint64_t mfn;

    if (xenstore_read_fe_uint64(&c->xendev, "page-ref", &mfn) == -1)

	return -1;

    assert(mfn == (xen_pfn_t)mfn);

    if (xenstore_read_fe_int(&c->xendev, "event-channel", &c->xendev.remote_port) == -1)

	return -1;

    c->page = xc_map_foreign_range(xen_xc, c->xendev.dom,

				   XC_PAGE_SIZE,

				   PROT_READ | PROT_WRITE, mfn);

    if (c->page == NULL)

	return -1;

    xen_be_bind_evtchn(&c->xendev);

    xen_be_printf(&c->xendev, 1, "ring mfn %"PRIx64", remote-port %d, local-port %d\n",

		  mfn, c->xendev.remote_port, c->xendev.local_port);

    return 0;

}


int av_thread_message_queue_alloc(AVThreadMessageQueue **mq,

                                  unsigned nelem,

                                  unsigned elsize)

{

#if HAVE_THREADS

    AVThreadMessageQueue *rmq;

    int ret = 0;

    if (nelem > INT_MAX / elsize)

        return AVERROR(EINVAL);

    if (!(rmq = av_mallocz(sizeof(*rmq))))

        return AVERROR(ENOMEM);

    if ((ret = pthread_mutex_init(&rmq->lock, NULL))) {

        av_free(rmq);

        return AVERROR(ret);

    }

    if ((ret = pthread_cond_init(&rmq->cond, NULL))) {

        pthread_mutex_destroy(&rmq->lock);

        av_free(rmq);

        return AVERROR(ret);

    }

    if (!(rmq->fifo = av_fifo_alloc(elsize * nelem))) {

        pthread_cond_destroy(&rmq->cond);

        pthread_mutex_destroy(&rmq->lock);

        av_free(rmq);

        return AVERROR(ret);

    }

    rmq->elsize = elsize;

    *mq = rmq;

    return 0;

#else

    *mq = NULL;

    return AVERROR(ENOSYS);

#endif /* HAVE_THREADS */

}


static void xvid_idct_put(uint8_t *dest, ptrdiff_t line_size, int16_t *block)

{

    ff_xvid_idct(block);

    ff_put_pixels_clamped(block, dest, line_size);

}


int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,

                                              AVPacket *avpkt,

                                              const AVFrame *frame,

                                              int *got_packet_ptr)

{

    int ret;

    int user_packet = !!avpkt->data;

    *got_packet_ptr = 0;

    if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {

        av_free_packet(avpkt);

        av_init_packet(avpkt);

        avpkt->size     = 0;

        return 0;

    }

    if (av_image_check_size(avctx->width, avctx->height, 0, avctx))

        return AVERROR(EINVAL);

    av_assert0(avctx->codec->encode2);

    ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);

    if (!ret) {

        if (!*got_packet_ptr)

            avpkt->size = 0;

        else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))

            avpkt->pts = avpkt->dts = frame->pts;

        if (!user_packet && avpkt->data) {

            uint8_t *new_data = av_realloc(avpkt->data, avpkt->size);

            if (new_data)

                avpkt->data = new_data;

        }

        avctx->frame_number++;

    }

    if (ret < 0 || !*got_packet_ptr)

        av_free_packet(avpkt);

    emms_c();

    return ret;

}


static int get_str(ByteIOContext *bc, char *string, int maxlen){

    int len= get_v(bc);

    if(len && maxlen)

        get_buffer(bc, string, FFMIN(len, maxlen));

    while(len > maxlen){

        get_byte(bc);

        len--;

    }

    if(maxlen)

        string[FFMIN(len, maxlen-1)]= 0;

    if(maxlen == len)

        return -1;

    else

        return 0;

}


static int dvbsub_decode(AVCodecContext *avctx,

                         void *data, int *data_size,

                         AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    DVBSubContext *ctx = avctx->priv_data;

    AVSubtitle *sub = data;

    const uint8_t *p, *p_end;

    int segment_type;

    int page_id;

    int segment_length;

#ifdef DEBUG_PACKET_CONTENTS

    int i;

    av_log(avctx, AV_LOG_INFO, "DVB sub packet:\n");

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

        av_log(avctx, AV_LOG_INFO, "%02x ", buf[i]);

        if (i % 16 == 15)

            av_log(avctx, AV_LOG_INFO, "\n");

    }

    if (i % 16)

        av_log(avctx, AV_LOG_INFO, "\n");

#endif

    if (buf_size <= 2 || *buf != 0x0f)

        return -1;

    p = buf;

    p_end = buf + buf_size;

    while (p < p_end && *p == 0x0f) {

        p += 1;

        segment_type = *p++;

        page_id = AV_RB16(p);

        p += 2;

        segment_length = AV_RB16(p);

        p += 2;

        if (page_id == ctx->composition_id || page_id == ctx->ancillary_id ||

            ctx->composition_id == -1 || ctx->ancillary_id == -1) {

            switch (segment_type) {

            case DVBSUB_PAGE_SEGMENT:

                dvbsub_parse_page_segment(avctx, p, segment_length);

                break;

            case DVBSUB_REGION_SEGMENT:

                dvbsub_parse_region_segment(avctx, p, segment_length);

                break;

            case DVBSUB_CLUT_SEGMENT:

                dvbsub_parse_clut_segment(avctx, p, segment_length);

                break;

            case DVBSUB_OBJECT_SEGMENT:

                dvbsub_parse_object_segment(avctx, p, segment_length);

                break;

            case DVBSUB_DISPLAYDEFINITION_SEGMENT:

                dvbsub_parse_display_definition_segment(avctx, p, segment_length);

            case DVBSUB_DISPLAY_SEGMENT:

                *data_size = dvbsub_display_end_segment(avctx, p, segment_length, sub);

                break;

            default:

                av_dlog(avctx, "Subtitling segment type 0x%x, page id %d, length %d\n",

                        segment_type, page_id, segment_length);

                break;

            }

        }

        p += segment_length;

    }

    return p - buf;

}


static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
                           int threshold)
{
    Jpeg2000TgtNode *stack[30];
    int sp = -1, curval = 0;
    while (node && !node->vis) {
        stack[++sp] = node;
        node        = node->parent;
    }
    if (node)
        curval = node->val;
    else
        curval = stack[sp]->val;
    while (curval < threshold && sp >= 0) {
        if (curval < stack[sp]->val)
            curval = stack[sp]->val;
        while (curval < threshold) {
            int ret;
            if ((ret = get_bits(s, 1)) > 0) {
                stack[sp]->vis++;
                break;
            } else if (!ret)
                curval++;
            else
                return ret;
        }
        stack[sp]->val = curval;
        sp--;
    }
    return curval;
}


static int output_configure(AACContext *ac,

                            uint8_t layout_map[MAX_ELEM_ID * 4][3], int tags,

                            enum OCStatus oc_type, int get_new_frame)

{

    AVCodecContext *avctx = ac->avctx;

    int i, channels = 0, ret;

    uint64_t layout = 0;

    uint8_t id_map[TYPE_END][MAX_ELEM_ID] = {{ 0 }};

    uint8_t type_counts[TYPE_END] = { 0 };

    if (ac->oc[1].layout_map != layout_map) {

        memcpy(ac->oc[1].layout_map, layout_map, tags * sizeof(layout_map[0]));

        ac->oc[1].layout_map_tags = tags;

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

        int type =         layout_map[i][0];

        int id =           layout_map[i][1];

        id_map[type][id] = type_counts[type]++;

    // Try to sniff a reasonable channel order, otherwise output the

    // channels in the order the PCE declared them.

    if (avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE)

        layout = sniff_channel_order(layout_map, tags);

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

        int type =     layout_map[i][0];

        int id =       layout_map[i][1];

        int iid =      id_map[type][id];

        int position = layout_map[i][2];

        // Allocate or free elements depending on if they are in the

        // current program configuration.

        ret = che_configure(ac, position, type, iid, &channels);

        if (ret < 0)

            return ret;

        ac->tag_che_map[type][id] = ac->che[type][iid];

    if (ac->oc[1].m4ac.ps == 1 && channels == 2) {

        if (layout == AV_CH_FRONT_CENTER) {

            layout = AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT;

        } else {

            layout = 0;

    if (layout) avctx->channel_layout = layout;

                            ac->oc[1].channel_layout = layout;

    avctx->channels       = ac->oc[1].channels       = channels;

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

    if (get_new_frame) {

        if ((ret = frame_configure_elements(ac->avctx)) < 0)

            return ret;

    return 0;


static int qemu_paio_submit(struct qemu_paiocb *aiocb, int type)

{

    aiocb->aio_type = type;

    aiocb->ret = -EINPROGRESS;

    aiocb->active = 0;

    mutex_lock(&lock);

    if (idle_threads == 0 && cur_threads < max_threads)

        spawn_thread();

    TAILQ_INSERT_TAIL(&request_list, aiocb, node);

    mutex_unlock(&lock);

    cond_signal(&cond);

    return 0;

}


uint64_t helper_fnmadd(CPUPPCState *env, uint64_t arg1, uint64_t arg2,

                       uint64_t arg3)

{

    CPU_DoubleU farg1, farg2, farg3;

    farg1.ll = arg1;

    farg2.ll = arg2;

    farg3.ll = arg3;

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

                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {

        /* Multiplication of zero by infinity */

        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);

    } else {

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

                     float64_is_signaling_nan(farg2.d) ||

                     float64_is_signaling_nan(farg3.d))) {

            /* sNaN operation */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

        }

        /* This is the way the PowerPC specification defines it */

        float128 ft0_128, ft1_128;

        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);

        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);

        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);

        if (unlikely(float128_is_infinity(ft0_128) &&

                     float64_is_infinity(farg3.d) &&

                     float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {

            /* Magnitude subtraction of infinities */

            farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);

        } else {

            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);

            ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);

            farg1.d = float128_to_float64(ft0_128, &env->fp_status);

        }

        if (likely(!float64_is_any_nan(farg1.d))) {

            farg1.d = float64_chs(farg1.d);

        }

    }

    return farg1.ll;

}


static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockCompletionFunc *cb, void *opaque)

{

    return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);

}


static void attach_storage_element(SCLPDevice *sclp, SCCB *sccb,

                                   uint16_t element)

{

    int i, assigned, subincrement_id;

    AttachStorageElement *attach_info = (AttachStorageElement *) sccb;

    sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev();

    assert(mhd);

    if (element != 1) {

        sccb->h.response_code = cpu_to_be16(SCLP_RC_INVALID_SCLP_COMMAND);

        return;

    }

    assigned = mhd->standby_mem_size >> mhd->increment_size;

    attach_info->assigned = cpu_to_be16(assigned);

    subincrement_id = ((ram_size >> mhd->increment_size) << 16)

                      + SCLP_STARTING_SUBINCREMENT_ID;

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

        attach_info->entries[i] = cpu_to_be32(subincrement_id);

        subincrement_id += SCLP_INCREMENT_UNIT;

    }

    sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_COMPLETION);

}


static void kvmppc_pivot_hpt_cpu(CPUState *cs, run_on_cpu_data arg)

{

    target_ulong sdr1 = arg.target_ptr;

    PowerPCCPU *cpu = POWERPC_CPU(cs);

    CPUPPCState *env = &cpu->env;

    /* This is just for the benefit of PR KVM */

    cpu_synchronize_state(cs);

    env->spr[SPR_SDR1] = sdr1;

    if (kvmppc_put_books_sregs(cpu) < 0) {

        error_report("Unable to update SDR1 in KVM");

        exit(1);

    }

}


static int send_rect_simple(VncState *vs, int x, int y, int w, int h)

{

    int max_size, max_width;

    int max_sub_width, max_sub_height;

    int dx, dy;

    int rw, rh;

    int n = 0;

    max_size = tight_conf[vs->tight_compression].max_rect_size;

    max_width = tight_conf[vs->tight_compression].max_rect_width;

    if (w > max_width || w * h > max_size) {

        max_sub_width = (w > max_width) ? max_width : w;

        max_sub_height = max_size / max_sub_width;

        for (dy = 0; dy < h; dy += max_sub_height) {

            for (dx = 0; dx < w; dx += max_width) {

                rw = MIN(max_sub_width, w - dx);

                rh = MIN(max_sub_height, h - dy);

                n += send_sub_rect(vs, x+dx, y+dy, rw, rh);

            }

        }

    } else {

        n += send_sub_rect(vs, x, y, w, h);

    }

    return n;

}


static int decompress_i(AVCodecContext *avctx, uint32_t *dst, int linesize)

{

    SCPRContext *s = avctx->priv_data;

    GetByteContext *gb = &s->gb;

    int cx = 0, cx1 = 0, k = 0, clr = 0;

    int run, r, g, b, off, y = 0, x = 0, ret;

    const int cxshift = s->cxshift;

    unsigned lx, ly, ptype;

    reinit_tables(s);

    bytestream2_skip(gb, 2);

    init_rangecoder(&s->rc, gb);

    while (k < avctx->width + 1) {

        ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);

        if (ret < 0)

            return ret;

        cx1 = (cx << 6) & 0xFC0;

        cx = r >> cxshift;

        ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);

        if (ret < 0)

            return ret;

        cx1 = (cx << 6) & 0xFC0;

        cx = g >> cxshift;

        ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);

        if (ret < 0)

            return ret;

        cx1 = (cx << 6) & 0xFC0;

        cx = b >> cxshift;

        ret = decode_value(s, s->run_model[0], 256, 400, &run);

        if (ret < 0)

            return ret;

        clr = (b << 16) + (g << 8) + r;

        k += run;

        while (run-- > 0) {

            dst[y * linesize + x] = clr;

            lx = x;

            ly = y;

            x++;

            if (x >= avctx->width) {

                x = 0;

                y++;

            }

        }

    }

    off = -linesize - 1;

    ptype = 0;

    while (x < avctx->width && y < avctx->height) {

        ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype);

        if (ret < 0)

            return ret;

        if (ptype == 0) {

            ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);

            if (ret < 0)

                return ret;

            cx1 = (cx << 6) & 0xFC0;

            cx = r >> cxshift;

            ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);

            if (ret < 0)

                return ret;

            cx1 = (cx << 6) & 0xFC0;

            cx = g >> cxshift;

            ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);

            if (ret < 0)

                return ret;

            cx1 = (cx << 6) & 0xFC0;

            cx = b >> cxshift;

            clr = (b << 16) + (g << 8) + r;

        }

        if (ptype > 5)

            return AVERROR_INVALIDDATA;

        ret = decode_value(s, s->run_model[ptype], 256, 400, &run);

        if (ret < 0)

            return ret;

        switch (ptype) {

        case 0:

            while (run-- > 0) {

                dst[y * linesize + x] = clr;

                lx = x;

                ly = y;

                x++;

                if (x >= avctx->width) {

                    x = 0;

                    y++;

                }

            }

            break;

        case 1:

            while (run-- > 0) {

                dst[y * linesize + x] = dst[ly * linesize + lx];

                lx = x;

                ly = y;

                x++;

                if (x >= avctx->width) {

                    x = 0;

                    y++;

                }

            }

            clr = dst[ly * linesize + lx];

            break;

        case 2:

            while (run-- > 0) {

                clr = dst[y * linesize + x + off + 1];

                dst[y * linesize + x] = clr;

                lx = x;

                ly = y;

                x++;

                if (x >= avctx->width) {

                    x = 0;

                    y++;

                }

            }

            break;

        case 4:

            while (run-- > 0) {

                uint8_t *odst = (uint8_t *)dst;

                r = odst[(ly * linesize + lx) * 4] +

                    odst[((y * linesize + x) + off) * 4 + 4] -

                    odst[((y * linesize + x) + off) * 4];

                g = odst[(ly * linesize + lx) * 4 + 1] +

                    odst[((y * linesize + x) + off) * 4 + 5] -

                    odst[((y * linesize + x) + off) * 4 + 1];

                b = odst[(ly * linesize + lx) * 4 + 2] +

                    odst[((y * linesize + x) + off) * 4 + 6] -

                    odst[((y * linesize + x) + off) * 4 + 2];

                clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF);

                dst[y * linesize + x] = clr;

                lx = x;

                ly = y;

                x++;

                if (x >= avctx->width) {

                    x = 0;

                    y++;

                }

            }

            break;

        case 5:

            while (run-- > 0) {

                clr = dst[y * linesize + x + off];

                dst[y * linesize + x] = clr;

                lx = x;

                ly = y;

                x++;

                if (x >= avctx->width) {

                    x = 0;

                    y++;

                }

            }

            break;

        }

        if (avctx->bits_per_coded_sample == 16) {

            cx1 = (clr & 0xFF00) >> 2;

            cx = (clr & 0xFFFFFF) >> 16;

        } else {

            cx1 = (clr & 0xFC00) >> 4;

            cx = (clr & 0xFFFFFF) >> 18;

        }

    }

    return 0;

}


static void gen_extu(int ot, TCGv reg)

{

    switch(ot) {

    case OT_BYTE:

        tcg_gen_ext8u_tl(reg, reg);

        break;

    case OT_WORD:

        tcg_gen_ext16u_tl(reg, reg);

        break;

    case OT_LONG:

        tcg_gen_ext32u_tl(reg, reg);

        break;

    default:

        break;

    }

}


ssize_t read_targphys(const char *name,

                      int fd, target_phys_addr_t dst_addr, size_t nbytes)

{

    uint8_t *buf;

    ssize_t did;

    buf = g_malloc(nbytes);

    did = read(fd, buf, nbytes);

    if (did > 0)

        rom_add_blob_fixed("read", buf, did, dst_addr);

    g_free(buf);

    return did;

}


DeviceState *qdev_device_add(QemuOpts *opts)

{

    DeviceClass *k;

    const char *driver, *path, *id;

    DeviceState *qdev;

    BusState *bus;

    driver = qemu_opt_get(opts, "driver");

    if (!driver) {

        qerror_report(QERR_MISSING_PARAMETER, "driver");

        return NULL;

    }

    /* find driver */

    k = DEVICE_CLASS(object_class_by_name(driver));

    /* find bus */

    path = qemu_opt_get(opts, "bus");

    if (path != NULL) {

        bus = qbus_find(path);

        if (!bus) {

            return NULL;

        }

        if (bus->info != k->bus_info) {

            qerror_report(QERR_BAD_BUS_FOR_DEVICE,

                           driver, bus->info->name);

            return NULL;

        }

    } else {

        bus = qbus_find_recursive(main_system_bus, NULL, k->bus_info);

        if (!bus) {

            qerror_report(QERR_NO_BUS_FOR_DEVICE,

                          driver, k->bus_info->name);

            return NULL;

        }

    }

    if (qdev_hotplug && !bus->allow_hotplug) {

        qerror_report(QERR_BUS_NO_HOTPLUG, bus->name);

        return NULL;

    }

    /* create device, set properties */

    qdev = qdev_create_from_info(bus, driver);

    id = qemu_opts_id(opts);

    if (id) {

        qdev->id = id;

        qdev_property_add_child(qdev_get_peripheral(), qdev->id, qdev, NULL);

    } else {

        static int anon_count;

        gchar *name = g_strdup_printf("device[%d]", anon_count++);

        qdev_property_add_child(qdev_get_peripheral_anon(), name,

                                qdev, NULL);

        g_free(name);

    }

    if (qemu_opt_foreach(opts, set_property, qdev, 1) != 0) {

        qdev_free(qdev);

        return NULL;

    }

    if (qdev_init(qdev) < 0) {

        qerror_report(QERR_DEVICE_INIT_FAILED, driver);

        return NULL;

    }

    qdev->opts = opts;

    return qdev;

}


static void qdict_teardown(void)

{

    QDECREF(tests_dict);

    tests_dict = NULL;

}


static void tcg_out_brcond(TCGContext *s, TCGCond cond,

                           TCGArg arg1, TCGArg arg2, int const_arg2,

                           int label_index, TCGType type)

{

    tcg_out_cmp(s, cond, arg1, arg2, const_arg2, 7, type);

    tcg_out_bc(s, tcg_to_bc[cond], label_index);

}


static void qxl_track_command(PCIQXLDevice *qxl, struct QXLCommandExt *ext)

{

    switch (le32_to_cpu(ext->cmd.type)) {

    case QXL_CMD_SURFACE:

    {

        QXLSurfaceCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);

        uint32_t id = le32_to_cpu(cmd->surface_id);

        PANIC_ON(id >= NUM_SURFACES);

        qemu_mutex_lock(&qxl->track_lock);

        if (cmd->type == QXL_SURFACE_CMD_CREATE) {

            qxl->guest_surfaces.cmds[id] = ext->cmd.data;

            qxl->guest_surfaces.count++;

            if (qxl->guest_surfaces.max < qxl->guest_surfaces.count)

                qxl->guest_surfaces.max = qxl->guest_surfaces.count;

        }

        if (cmd->type == QXL_SURFACE_CMD_DESTROY) {

            qxl->guest_surfaces.cmds[id] = 0;

            qxl->guest_surfaces.count--;

        }

        qemu_mutex_unlock(&qxl->track_lock);

        break;

    }

    case QXL_CMD_CURSOR:

    {

        QXLCursorCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);

        if (cmd->type == QXL_CURSOR_SET) {

            qemu_mutex_lock(&qxl->track_lock);

            qxl->guest_cursor = ext->cmd.data;

            qemu_mutex_unlock(&qxl->track_lock);

        }

        break;

    }

    }

}


static void nvdimm_dsm_label_size(NVDIMMDevice *nvdimm, hwaddr dsm_mem_addr)

{

    NvdimmFuncGetLabelSizeOut label_size_out = {

        .len = cpu_to_le32(sizeof(label_size_out)),

    };

    uint32_t label_size, mxfer;

    label_size = nvdimm->label_size;

    mxfer = nvdimm_get_max_xfer_label_size();

    nvdimm_debug("label_size %#x, max_xfer %#x.\n", label_size, mxfer);

    label_size_out.func_ret_status = cpu_to_le32(0 /* Success */);

    label_size_out.label_size = cpu_to_le32(label_size);

    label_size_out.max_xfer = cpu_to_le32(mxfer);

    cpu_physical_memory_write(dsm_mem_addr, &label_size_out,

                              sizeof(label_size_out));

}


qemu_irq *armv7m_init(int flash_size, int sram_size,

                      const char *kernel_filename, const char *cpu_model)

{

    CPUState *env;

    DeviceState *nvic;

    /* FIXME: make this local state.  */

    static qemu_irq pic[64];

    qemu_irq *cpu_pic;

    uint32_t pc;

    int image_size;

    uint64_t entry;

    uint64_t lowaddr;

    int i;

    flash_size *= 1024;

    sram_size *= 1024;

    if (!cpu_model)

	cpu_model = "cortex-m3";

    env = cpu_init(cpu_model);

    if (!env) {

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

        exit(1);

    }

#if 0

    /* > 32Mb SRAM gets complicated because it overlaps the bitband area.

       We don't have proper commandline options, so allocate half of memory

       as SRAM, up to a maximum of 32Mb, and the rest as code.  */

    if (ram_size > (512 + 32) * 1024 * 1024)

        ram_size = (512 + 32) * 1024 * 1024;

    sram_size = (ram_size / 2) & TARGET_PAGE_MASK;

    if (sram_size > 32 * 1024 * 1024)

        sram_size = 32 * 1024 * 1024;

    code_size = ram_size - sram_size;

#endif

    /* Flash programming is done via the SCU, so pretend it is ROM.  */

    cpu_register_physical_memory(0, flash_size,

                                 qemu_ram_alloc(flash_size) | IO_MEM_ROM);

    cpu_register_physical_memory(0x20000000, sram_size,

                                 qemu_ram_alloc(sram_size) | IO_MEM_RAM);

    armv7m_bitband_init();

    nvic = qdev_create(NULL, "armv7m_nvic");

    qdev_set_prop_ptr(nvic, "cpu", env);

    qdev_init(nvic);

    cpu_pic = arm_pic_init_cpu(env);

    sysbus_connect_irq(sysbus_from_qdev(nvic), 0, cpu_pic[ARM_PIC_CPU_IRQ]);

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

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

    }

    image_size = load_elf(kernel_filename, 0, &entry, &lowaddr, NULL);

    if (image_size < 0) {

        image_size = load_image_targphys(kernel_filename, 0, flash_size);

	lowaddr = 0;

    }

    if (image_size < 0) {

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

                kernel_filename);

        exit(1);

    }

    /* If the image was loaded at address zero then assume it is a

       regular ROM image and perform the normal CPU reset sequence.

       Otherwise jump directly to the entry point.  */

    if (lowaddr == 0) {

	env->regs[13] = ldl_phys(0);

	pc = ldl_phys(4);

    } else {

	pc = entry;

    }

    env->thumb = pc & 1;

    env->regs[15] = pc & ~1;

    /* Hack to map an additional page of ram at the top of the address

       space.  This stops qemu complaining about executing code outside RAM

       when returning from an exception.  */

    cpu_register_physical_memory(0xfffff000, 0x1000,

                                 qemu_ram_alloc(0x1000) | IO_MEM_RAM);

    return pic;

}


int monitor_get_fd(Monitor *mon, const char *fdname)

{

    mon_fd_t *monfd;

    LIST_FOREACH(monfd, &mon->fds, next) {

        int fd;

        if (strcmp(monfd->name, fdname) != 0) {

            continue;

        }

        fd = monfd->fd;

        /* caller takes ownership of fd */

        LIST_REMOVE(monfd, next);

        qemu_free(monfd->name);

        qemu_free(monfd);

        return fd;

    }

    return -1;

}


static int count_cow_clusters(BDRVQcow2State *s, int nb_clusters,

    uint64_t *l2_table, int l2_index)

{

    int i;

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

        uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);

        QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);

        switch(cluster_type) {

        case QCOW2_CLUSTER_NORMAL:

            if (l2_entry & QCOW_OFLAG_COPIED) {

                goto out;

            }

            break;

        case QCOW2_CLUSTER_UNALLOCATED:

        case QCOW2_CLUSTER_COMPRESSED:

        case QCOW2_CLUSTER_ZERO:

            break;

        default:

            abort();

        }

    }

out:

    assert(i <= nb_clusters);

    return i;

}


VirtIOS390Device *s390_virtio_bus_find_vring(VirtIOS390Bus *bus,

                                             ram_addr_t mem,

                                             int *vq_num)

{

    BusChild *kid;

    int i;

    QTAILQ_FOREACH(kid, &bus->bus.children, sibling) {

        VirtIOS390Device *dev = (VirtIOS390Device *)kid->child;

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

            if (!virtio_queue_get_addr(dev->vdev, i))

                break;

            if (virtio_queue_get_addr(dev->vdev, i) == mem) {

                if (vq_num) {

                    *vq_num = i;

                }

                return dev;

            }

        }

    }

    return NULL;

}


static inline int parse_nal_units(AVCodecParserContext *s, const uint8_t *buf,

                           int buf_size, AVCodecContext *avctx)

{

    HEVCParserContext *ctx = s->priv_data;

    HEVCContext       *h   = &ctx->h;

    GetBitContext      *gb;

    SliceHeader        *sh = &h->sh;

    HEVCParamSets *ps = &h->ps;

    HEVCSEIContext *sei = &h->sei;

    int is_global = buf == avctx->extradata;

    int i, ret;

    if (!h->HEVClc)

        h->HEVClc = av_mallocz(sizeof(HEVCLocalContext));

    if (!h->HEVClc)

        return AVERROR(ENOMEM);

    gb = &h->HEVClc->gb;

    /* set some sane default values */

    s->pict_type         = AV_PICTURE_TYPE_I;

    s->key_frame         = 0;

    s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;

    h->avctx = avctx;

    ff_hevc_reset_sei(sei);

    ret = ff_h2645_packet_split(&ctx->pkt, buf, buf_size, avctx, 0, 0,

                                AV_CODEC_ID_HEVC, 1);

    if (ret < 0)

        return ret;

    for (i = 0; i < ctx->pkt.nb_nals; i++) {

        H2645NAL *nal = &ctx->pkt.nals[i];

        int num = 0, den = 0;

        h->nal_unit_type = nal->type;

        h->temporal_id   = nal->temporal_id;

        *gb = nal->gb;

        switch (h->nal_unit_type) {

        case HEVC_NAL_VPS:

            ff_hevc_decode_nal_vps(gb, avctx, ps);

            break;

        case HEVC_NAL_SPS:

            ff_hevc_decode_nal_sps(gb, avctx, ps, 1);

            break;

        case HEVC_NAL_PPS:

            ff_hevc_decode_nal_pps(gb, avctx, ps);

            break;

        case HEVC_NAL_SEI_PREFIX:

        case HEVC_NAL_SEI_SUFFIX:

            ff_hevc_decode_nal_sei(gb, avctx, sei, ps, h->nal_unit_type);

            break;

        case HEVC_NAL_TRAIL_N:

        case HEVC_NAL_TRAIL_R:

        case HEVC_NAL_TSA_N:

        case HEVC_NAL_TSA_R:

        case HEVC_NAL_STSA_N:

        case HEVC_NAL_STSA_R:

        case HEVC_NAL_RADL_N:

        case HEVC_NAL_RADL_R:

        case HEVC_NAL_RASL_N:

        case HEVC_NAL_RASL_R:

        case HEVC_NAL_BLA_W_LP:

        case HEVC_NAL_BLA_W_RADL:

        case HEVC_NAL_BLA_N_LP:

        case HEVC_NAL_IDR_W_RADL:

        case HEVC_NAL_IDR_N_LP:

        case HEVC_NAL_CRA_NUT:

            if (is_global) {

                av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit: %d\n", h->nal_unit_type);

                return AVERROR_INVALIDDATA;

            }

            sh->first_slice_in_pic_flag = get_bits1(gb);

            s->picture_structure = h->sei.picture_timing.picture_struct;

            s->field_order = h->sei.picture_timing.picture_struct;

            if (IS_IRAP(h)) {

                s->key_frame = 1;

                sh->no_output_of_prior_pics_flag = get_bits1(gb);

            }

            sh->pps_id = get_ue_golomb(gb);

            if (sh->pps_id >= HEVC_MAX_PPS_COUNT || !ps->pps_list[sh->pps_id]) {

                av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);

                return AVERROR_INVALIDDATA;

            }

            ps->pps = (HEVCPPS*)ps->pps_list[sh->pps_id]->data;

            if (ps->pps->sps_id >= HEVC_MAX_SPS_COUNT || !ps->sps_list[ps->pps->sps_id]) {

                av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", ps->pps->sps_id);

                return AVERROR_INVALIDDATA;

            }

            if (ps->sps != (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data) {

                ps->sps = (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data;

                ps->vps = (HEVCVPS*)ps->vps_list[ps->sps->vps_id]->data;

            }

            s->coded_width  = ps->sps->width;

            s->coded_height = ps->sps->height;

            s->width        = ps->sps->output_width;

            s->height       = ps->sps->output_height;

            s->format       = ps->sps->pix_fmt;

            avctx->profile  = ps->sps->ptl.general_ptl.profile_idc;

            avctx->level    = ps->sps->ptl.general_ptl.level_idc;

            if (ps->vps->vps_timing_info_present_flag) {

                num = ps->vps->vps_num_units_in_tick;

                den = ps->vps->vps_time_scale;

            } else if (ps->sps->vui.vui_timing_info_present_flag) {

                num = ps->sps->vui.vui_num_units_in_tick;

                den = ps->sps->vui.vui_time_scale;

            }

            if (num != 0 && den != 0)

                av_reduce(&avctx->framerate.den, &avctx->framerate.num,

                          num, den, 1 << 30);

            if (!sh->first_slice_in_pic_flag) {

                int slice_address_length;

                if (ps->pps->dependent_slice_segments_enabled_flag)

                    sh->dependent_slice_segment_flag = get_bits1(gb);

                else

                    sh->dependent_slice_segment_flag = 0;

                slice_address_length = av_ceil_log2_c(ps->sps->ctb_width *

                                                      ps->sps->ctb_height);

                sh->slice_segment_addr = get_bitsz(gb, slice_address_length);

                if (sh->slice_segment_addr >= ps->sps->ctb_width * ps->sps->ctb_height) {

                    av_log(avctx, AV_LOG_ERROR, "Invalid slice segment address: %u.\n",

                           sh->slice_segment_addr);

                    return AVERROR_INVALIDDATA;

                }

            } else

                sh->dependent_slice_segment_flag = 0;

            if (sh->dependent_slice_segment_flag)

                break;

            for (i = 0; i < ps->pps->num_extra_slice_header_bits; i++)

                skip_bits(gb, 1); // slice_reserved_undetermined_flag[]

            sh->slice_type = get_ue_golomb(gb);

            if (!(sh->slice_type == HEVC_SLICE_I || sh->slice_type == HEVC_SLICE_P ||

                  sh->slice_type == HEVC_SLICE_B)) {

                av_log(avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",

                       sh->slice_type);

                return AVERROR_INVALIDDATA;

            }

            s->pict_type = sh->slice_type == HEVC_SLICE_B ? AV_PICTURE_TYPE_B :

                           sh->slice_type == HEVC_SLICE_P ? AV_PICTURE_TYPE_P :

                                                       AV_PICTURE_TYPE_I;

            if (ps->pps->output_flag_present_flag)

                sh->pic_output_flag = get_bits1(gb);

            if (ps->sps->separate_colour_plane_flag)

                sh->colour_plane_id = get_bits(gb, 2);

            if (!IS_IDR(h)) {

                sh->pic_order_cnt_lsb = get_bits(gb, ps->sps->log2_max_poc_lsb);

                s->output_picture_number = h->poc = ff_hevc_compute_poc(h->ps.sps, h->pocTid0, sh->pic_order_cnt_lsb, h->nal_unit_type);

            } else

                s->output_picture_number = h->poc = 0;

            if (h->temporal_id == 0 &&

                h->nal_unit_type != HEVC_NAL_TRAIL_N &&

                h->nal_unit_type != HEVC_NAL_TSA_N &&

                h->nal_unit_type != HEVC_NAL_STSA_N &&

                h->nal_unit_type != HEVC_NAL_RADL_N &&

                h->nal_unit_type != HEVC_NAL_RASL_N &&

                h->nal_unit_type != HEVC_NAL_RADL_R &&

                h->nal_unit_type != HEVC_NAL_RASL_R)

                h->pocTid0 = h->poc;

            return 0; /* no need to evaluate the rest */

        }

    }

    /* didn't find a picture! */

    if (!is_global)

        av_log(h->avctx, AV_LOG_ERROR, "missing picture in access unit\n");

    return -1;

}


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

                                ptrdiff_t stride)

{

    avc_luma_mid_4w_msa(src - (2 * stride) - 2, stride, dst, stride, 4);

}


int ff_h2645_packet_split(H2645Packet *pkt, const uint8_t *buf, int length,

                          void *logctx, int is_nalff, int nal_length_size,

                          enum AVCodecID codec_id)

{

    int consumed, ret = 0;

    const uint8_t *next_avc = buf + (is_nalff ? 0 : length);

    pkt->nb_nals = 0;

    while (length >= 4) {

        H2645NAL *nal;

        int extract_length = 0;

        int skip_trailing_zeros = 1;

        /*

         * Only parse an AVC1 length field if one is expected at the current

         * buffer position. There are unfortunately streams with multiple

         * NAL units covered by the length field. Those NAL units are delimited

         * by Annex B start code prefixes. ff_h2645_extract_rbsp() detects it

         * correctly and consumes only the first NAL unit. The additional NAL

         * units are handled here in the Annex B parsing code.

         */

        if (buf == next_avc) {

            int i;

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

                extract_length = (extract_length << 8) | buf[i];

            if (extract_length > length) {

                av_log(logctx, AV_LOG_ERROR, "Invalid NAL unit size.\n");

                return AVERROR_INVALIDDATA;

            }

            buf     += nal_length_size;

            length  -= nal_length_size;

            // keep track of the next AVC1 length field

            next_avc = buf + extract_length;

        } else {

            /*

             * expected to return immediately except for streams with mixed

             * NAL unit coding

             */

            int buf_index = find_next_start_code(buf, next_avc);

            buf    += buf_index;

            length -= buf_index;

            /*

             * break if an AVC1 length field is expected at the current buffer

             * position

             */

            if (buf == next_avc)

                continue;

            if (length > 0) {

                extract_length = length;

            } else if (pkt->nb_nals == 0) {

                av_log(logctx, AV_LOG_ERROR, "No NAL unit found\n");

                return AVERROR_INVALIDDATA;

            } else {

                break;

            }

        }

        if (pkt->nals_allocated < pkt->nb_nals + 1) {

            int new_size = pkt->nals_allocated + 1;

            H2645NAL *tmp = av_realloc_array(pkt->nals, new_size, sizeof(*tmp));

            if (!tmp)

                return AVERROR(ENOMEM);

            pkt->nals = tmp;

            memset(pkt->nals + pkt->nals_allocated, 0,

                   (new_size - pkt->nals_allocated) * sizeof(*tmp));

            pkt->nals_allocated = new_size;

        }

        nal = &pkt->nals[pkt->nb_nals++];

        consumed = ff_h2645_extract_rbsp(buf, extract_length, nal);

        if (consumed < 0)

            return consumed;

        /* see commit 3566042a0 */

        if (consumed < length - 3 &&

            buf[consumed]     == 0x00 && buf[consumed + 1] == 0x00 &&

            buf[consumed + 2] == 0x01 && buf[consumed + 3] == 0xE0)

            skip_trailing_zeros = 0;

        nal->size_bits = get_bit_length(nal, skip_trailing_zeros);

        ret = init_get_bits(&nal->gb, nal->data, nal->size_bits);

        if (ret < 0)

            return ret;

        if (codec_id == AV_CODEC_ID_HEVC)

            ret = hevc_parse_nal_header(nal, logctx);

        else

            ret = h264_parse_nal_header(nal, logctx);

        if (ret <= 0) {

            if (ret < 0) {

                av_log(logctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n",

                       nal->type);

            }

            pkt->nb_nals--;

        }

        buf    += consumed;

        length -= consumed;

    }

    return 0;

}


static int output_packet(AVInputStream *ist, int ist_index,

                         AVOutputStream **ost_table, int nb_ostreams,

                         const AVPacket *pkt)

{

    AVFormatContext *os;

    AVOutputStream *ost;

    uint8_t *ptr;

    int len, ret, i;

    uint8_t *data_buf;

    int data_size, got_picture;

    AVFrame picture;

    short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];

    void *buffer_to_free;

    if (pkt && pkt->pts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too

        ist->next_pts = ist->pts = pkt->dts;

    } else {

        ist->pts = ist->next_pts;

    }

    if (pkt == NULL) {

        /* EOF handling */

        ptr = NULL;

        len = 0;

        goto handle_eof;

    }

    len = pkt->size;

    ptr = pkt->data;

    while (len > 0) {

    handle_eof:

        /* decode the packet if needed */

        data_buf = NULL; /* fail safe */

        data_size = 0;

        if (ist->decoding_needed) {

            switch(ist->st->codec.codec_type) {

            case CODEC_TYPE_AUDIO:

                    /* XXX: could avoid copy if PCM 16 bits with same

                       endianness as CPU */

                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,

                                           ptr, len);

                if (ret < 0)

                    goto fail_decode;

                ptr += ret;

                len -= ret;

                /* Some bug in mpeg audio decoder gives */

                /* data_size < 0, it seems they are overflows */

                if (data_size <= 0) {

                    /* no audio frame */

                    continue;

                }

                data_buf = (uint8_t *)samples;

                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /

                    (ist->st->codec.sample_rate * ist->st->codec.channels);

                break;

            case CODEC_TYPE_VIDEO:

                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;

                    /* XXX: allocate picture correctly */

                    avcodec_get_frame_defaults(&picture);

                    ret = avcodec_decode_video(&ist->st->codec,

                                               &picture, &got_picture, ptr, len);

                    ist->st->quality= picture.quality;

                    if (ret < 0)

                        goto fail_decode;

                    if (!got_picture) {

                        /* no picture yet */

                        goto discard_packet;

                    }

                    if (ist->st->codec.frame_rate_base != 0) {

                        ist->next_pts += ((int64_t)AV_TIME_BASE *

                                          ist->st->codec.frame_rate_base) /

                            ist->st->codec.frame_rate;

                    }

                    len = 0;

                    break;

                default:

                    goto fail_decode;

                }

            } else {

                data_buf = ptr;

                data_size = len;

                ret = len;

                len = 0;

            }

            buffer_to_free = NULL;

            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {

                pre_process_video_frame(ist, (AVPicture *)&picture,

                                        &buffer_to_free);

            }

            /* frame rate emulation */

            if (ist->st->codec.rate_emu) {

                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);

                int64_t now = av_gettime() - ist->start;

                if (pts > now)

                    usleep(pts - now);

                ist->frame++;

            }

#if 0

            /* mpeg PTS deordering : if it is a P or I frame, the PTS

               is the one of the next displayed one */

            /* XXX: add mpeg4 too ? */

            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {

                if (ist->st->codec.pict_type != B_TYPE) {

                    int64_t tmp;

                    tmp = ist->last_ip_pts;

                    ist->last_ip_pts  = ist->frac_pts.val;

                    ist->frac_pts.val = tmp;

                }

            }

#endif

            /* if output time reached then transcode raw format,

	       encode packets and output them */

            if (start_time == 0 || ist->pts >= start_time)

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

                    int frame_size;

                    ost = ost_table[i];

                    if (ost->source_index == ist_index) {

                        os = output_files[ost->file_index];

#if 0

                        printf("%d: got pts=%0.3f %0.3f\n", i,

                               (double)pkt->pts / AV_TIME_BASE,

                               ((double)ist->pts / AV_TIME_BASE) -

                               ((double)ost->st->pts.val * ost->time_base.num / ost->time_base.den));

#endif

                        /* set the input output pts pairs */

                        ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;

                        if (ost->encoding_needed) {

                            switch(ost->st->codec.codec_type) {

                            case CODEC_TYPE_AUDIO:

                                do_audio_out(os, ost, ist, data_buf, data_size);

                                break;

                            case CODEC_TYPE_VIDEO:

                                /* find an audio stream for synchro */

                                {

                                    int i;

                                    AVOutputStream *audio_sync, *ost1;

                                    audio_sync = NULL;

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

                                        ost1 = ost_table[i];

                                        if (ost1->file_index == ost->file_index &&

                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {

                                            audio_sync = ost1;

                                            break;

                                        }

                                    }

                                    do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);

                                    video_size += frame_size;

                                    if (do_vstats && frame_size)

                                        do_video_stats(os, ost, frame_size);

                                }

                                break;

                            default:

                                av_abort();

                            }

                        } else {

                            AVFrame avframe; //FIXME/XXX remove this

                            AVPacket opkt;

                            av_init_packet(&opkt);

                            /* no reencoding needed : output the packet directly */

                            /* force the input stream PTS */

                            avcodec_get_frame_defaults(&avframe);

                            ost->st->codec.coded_frame= &avframe;

                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY;

                            if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO)

                                audio_size += data_size;

                            else if (ost->st->codec.codec_type == CODEC_TYPE_VIDEO)

                                video_size += data_size;

                            opkt.stream_index= ost->index;

                            opkt.data= data_buf;

                            opkt.size= data_size;

                            opkt.pts= ist->pts; //FIXME dts vs. pts

                            opkt.flags= pkt->flags;

                            av_write_frame(os, &opkt);

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

                            ost->frame_number++;

                        }

                    }

                }

            av_free(buffer_to_free);

        }

 discard_packet:

    return 0;

 fail_decode:

    return -1;

}


static void count_frame_bits(AC3EncodeContext *s)

{

    AC3EncOptions *opt = &s->options;

    int blk, ch;

    int frame_bits = 0;

    /* header */

    if (s->eac3) {

        /* coupling */

        if (s->channel_mode > AC3_CHMODE_MONO) {

            frame_bits++;

            for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {

                AC3Block *block = &s->blocks[blk];

                frame_bits++;

                if (block->new_cpl_strategy)

                    frame_bits++;

            }

        }

        /* coupling exponent strategy */

        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)

            frame_bits += 2 * s->blocks[blk].cpl_in_use;

    } else {

        if (opt->audio_production_info)

            frame_bits += 7;

        if (s->bitstream_id == 6) {

            if (opt->extended_bsi_1)

                frame_bits += 14;

            if (opt->extended_bsi_2)

                frame_bits += 14;

        }

    }

    /* audio blocks */

    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {

        AC3Block *block = &s->blocks[blk];

        /* coupling strategy */

        if (!s->eac3)

            frame_bits++;

        if (block->new_cpl_strategy) {

            if (!s->eac3)

                frame_bits++;

            if (block->cpl_in_use) {

                if (s->eac3)

                    frame_bits++;

                if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)

                    frame_bits += s->fbw_channels;

                if (s->channel_mode == AC3_CHMODE_STEREO)

                    frame_bits++;

                frame_bits += 4 + 4;

                if (s->eac3)

                    frame_bits++;

                else

                    frame_bits += s->num_cpl_subbands - 1;

            }

        }

        /* coupling coordinates */

        if (block->cpl_in_use) {

            for (ch = 1; ch <= s->fbw_channels; ch++) {

                if (block->channel_in_cpl[ch]) {

                    if (!s->eac3 || block->new_cpl_coords != 2)

                        frame_bits++;

                    if (block->new_cpl_coords) {

                        frame_bits += 2;

                        frame_bits += (4 + 4) * s->num_cpl_bands;

                    }

                }

            }

        }

        /* stereo rematrixing */

        if (s->channel_mode == AC3_CHMODE_STEREO) {

            if (!s->eac3 || blk > 0)

                frame_bits++;

            if (s->blocks[blk].new_rematrixing_strategy)

                frame_bits += block->num_rematrixing_bands;

        }

        /* bandwidth codes & gain range */

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            if (s->exp_strategy[ch][blk] != EXP_REUSE) {

                if (!block->channel_in_cpl[ch])

                    frame_bits += 6;

                frame_bits += 2;

            }

        }

        /* coupling exponent strategy */

        if (!s->eac3 && block->cpl_in_use)

            frame_bits += 2;

        /* snr offsets and fast gain codes */

        if (!s->eac3) {

            frame_bits++;

            if (block->new_snr_offsets)

                frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);

        }

        /* coupling leak info */

        if (block->cpl_in_use) {

            if (!s->eac3 || block->new_cpl_leak != 2)

                frame_bits++;

            if (block->new_cpl_leak)

                frame_bits += 3 + 3;

        }

    }

    s->frame_bits = s->frame_bits_fixed + frame_bits;

}


void sp804_init(uint32_t base, qemu_irq irq)

{

    int iomemtype;

    sp804_state *s;

    qemu_irq *qi;

    s = (sp804_state *)qemu_mallocz(sizeof(sp804_state));

    qi = qemu_allocate_irqs(sp804_set_irq, s, 2);

    s->base = base;

    s->irq = irq;

    /* ??? The timers are actually configurable between 32kHz and 1MHz, but

       we don't implement that.  */

    s->timer[0] = arm_timer_init(1000000, qi[0]);

    s->timer[1] = arm_timer_init(1000000, qi[1]);

    iomemtype = cpu_register_io_memory(0, sp804_readfn,

                                       sp804_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    /* ??? Save/restore.  */

}


static void network_init(void)

{

    int i;

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

        NICInfo *nd = &nd_table[i];

        const char *default_devaddr = NULL;

        if (i == 0 && (!nd->model || strcmp(nd->model, "pcnet") == 0))

            /* The malta board has a PCNet card using PCI SLOT 11 */

            default_devaddr = "0b";

        pci_nic_init(nd, "pcnet", default_devaddr);

    }

}


static uint8_t *buffer_end(Buffer *buffer)

{

    return buffer->buffer + buffer->offset;

}


PXA2xxState *pxa270_init(MemoryRegion *address_space,

                         unsigned int sdram_size, const char *revision)

{

    PXA2xxState *s;

    int i;

    DriveInfo *dinfo;

    s = (PXA2xxState *) g_malloc0(sizeof(PXA2xxState));

    if (revision && strncmp(revision, "pxa27", 5)) {

        fprintf(stderr, "Machine requires a PXA27x processor.\n");

        exit(1);

    }

    if (!revision)

        revision = "pxa270";

    s->cpu = cpu_arm_init(revision);

    if (s->cpu == NULL) {

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

        exit(1);

    }

    s->reset = qemu_allocate_irq(pxa2xx_reset, s, 0);

    /* SDRAM & Internal Memory Storage */

    memory_region_init_ram(&s->sdram, NULL, "pxa270.sdram", sdram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->sdram);

    memory_region_add_subregion(address_space, PXA2XX_SDRAM_BASE, &s->sdram);

    memory_region_init_ram(&s->internal, NULL, "pxa270.internal", 0x40000,

                           &error_abort);

    vmstate_register_ram_global(&s->internal);

    memory_region_add_subregion(address_space, PXA2XX_INTERNAL_BASE,

                                &s->internal);

    s->pic = pxa2xx_pic_init(0x40d00000, s->cpu);

    s->dma = pxa27x_dma_init(0x40000000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_DMA));

    sysbus_create_varargs("pxa27x-timer", 0x40a00000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 0),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 1),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 2),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 3),

                    qdev_get_gpio_in(s->pic, PXA27X_PIC_OST_4_11),

                    NULL);

    s->gpio = pxa2xx_gpio_init(0x40e00000, s->cpu, s->pic, 121);

    dinfo = drive_get(IF_SD, 0, 0);

    if (!dinfo) {

        fprintf(stderr, "qemu: missing SecureDigital device\n");

        exit(1);

    }

    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000,

                    blk_by_legacy_dinfo(dinfo),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC),

                    qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI),

                    qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI));

    for (i = 0; pxa270_serial[i].io_base; i++) {

        if (serial_hds[i]) {

            serial_mm_init(address_space, pxa270_serial[i].io_base, 2,

                           qdev_get_gpio_in(s->pic, pxa270_serial[i].irqn),

                           14857000 / 16, serial_hds[i],

                           DEVICE_NATIVE_ENDIAN);

        } else {

            break;

        }

    }

    if (serial_hds[i])

        s->fir = pxa2xx_fir_init(address_space, 0x40800000,

                        qdev_get_gpio_in(s->pic, PXA2XX_PIC_ICP),

                        qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_ICP),

                        qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_ICP),

                        serial_hds[i]);

    s->lcd = pxa2xx_lcdc_init(address_space, 0x44000000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_LCD));

    s->cm_base = 0x41300000;

    s->cm_regs[CCCR >> 2] = 0x02000210;	/* 416.0 MHz */

    s->clkcfg = 0x00000009;		/* Turbo mode active */

    memory_region_init_io(&s->cm_iomem, NULL, &pxa2xx_cm_ops, s, "pxa2xx-cm", 0x1000);

    memory_region_add_subregion(address_space, s->cm_base, &s->cm_iomem);

    vmstate_register(NULL, 0, &vmstate_pxa2xx_cm, s);

    pxa2xx_setup_cp14(s);

    s->mm_base = 0x48000000;

    s->mm_regs[MDMRS >> 2] = 0x00020002;

    s->mm_regs[MDREFR >> 2] = 0x03ca4000;

    s->mm_regs[MECR >> 2] = 0x00000001;	/* Two PC Card sockets */

    memory_region_init_io(&s->mm_iomem, NULL, &pxa2xx_mm_ops, s, "pxa2xx-mm", 0x1000);

    memory_region_add_subregion(address_space, s->mm_base, &s->mm_iomem);

    vmstate_register(NULL, 0, &vmstate_pxa2xx_mm, s);

    s->pm_base = 0x40f00000;

    memory_region_init_io(&s->pm_iomem, NULL, &pxa2xx_pm_ops, s, "pxa2xx-pm", 0x100);

    memory_region_add_subregion(address_space, s->pm_base, &s->pm_iomem);

    vmstate_register(NULL, 0, &vmstate_pxa2xx_pm, s);

    for (i = 0; pxa27x_ssp[i].io_base; i ++);

    s->ssp = (SSIBus **)g_malloc0(sizeof(SSIBus *) * i);

    for (i = 0; pxa27x_ssp[i].io_base; i ++) {

        DeviceState *dev;

        dev = sysbus_create_simple(TYPE_PXA2XX_SSP, pxa27x_ssp[i].io_base,

                        qdev_get_gpio_in(s->pic, pxa27x_ssp[i].irqn));

        s->ssp[i] = (SSIBus *)qdev_get_child_bus(dev, "ssi");

    }

    if (usb_enabled()) {

        sysbus_create_simple("sysbus-ohci", 0x4c000000,

                        qdev_get_gpio_in(s->pic, PXA2XX_PIC_USBH1));

    }

    s->pcmcia[0] = pxa2xx_pcmcia_init(address_space, 0x20000000);

    s->pcmcia[1] = pxa2xx_pcmcia_init(address_space, 0x30000000);

    sysbus_create_simple(TYPE_PXA2XX_RTC, 0x40900000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_RTCALARM));

    s->i2c[0] = pxa2xx_i2c_init(0x40301600,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_I2C), 0xffff);

    s->i2c[1] = pxa2xx_i2c_init(0x40f00100,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_PWRI2C), 0xff);

    s->i2s = pxa2xx_i2s_init(address_space, 0x40400000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_I2S),

                    qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_I2S),

                    qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_I2S));

    s->kp = pxa27x_keypad_init(address_space, 0x41500000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_KEYPAD));

    /* GPIO1 resets the processor */

    /* The handler can be overridden by board-specific code */

    qdev_connect_gpio_out(s->gpio, 1, s->reset);

    return s;

}


static int cpu_mips_register (CPUMIPSState *env, const mips_def_t *def)

{

    env->CP0_PRid = def->CP0_PRid;

    env->CP0_Config0 = def->CP0_Config0;

#ifdef TARGET_WORDS_BIGENDIAN

    env->CP0_Config0 |= (1 << CP0C0_BE);

#endif

    env->CP0_Config1 = def->CP0_Config1;

    env->CP0_Config2 = def->CP0_Config2;

    env->CP0_Config3 = def->CP0_Config3;

    env->CP0_Config6 = def->CP0_Config6;

    env->CP0_Config7 = def->CP0_Config7;

    env->SYNCI_Step = def->SYNCI_Step;

    env->CCRes = def->CCRes;

    env->CP0_Status_rw_bitmask = def->CP0_Status_rw_bitmask;

    env->CP0_TCStatus_rw_bitmask = def->CP0_TCStatus_rw_bitmask;

    env->CP0_SRSCtl = def->CP0_SRSCtl;

    env->current_tc = 0;

    env->SEGBITS = def->SEGBITS;

    env->SEGMask = (target_ulong)((1ULL << def->SEGBITS) - 1);

#if defined(TARGET_MIPS64)

    if (def->insn_flags & ISA_MIPS3) {

        env->hflags |= MIPS_HFLAG_64;

        env->SEGMask |= 3ULL << 62;

    }

#endif

    env->PABITS = def->PABITS;

    env->PAMask = (target_ulong)((1ULL << def->PABITS) - 1);

    env->CP0_SRSConf0_rw_bitmask = def->CP0_SRSConf0_rw_bitmask;

    env->CP0_SRSConf0 = def->CP0_SRSConf0;

    env->CP0_SRSConf1_rw_bitmask = def->CP0_SRSConf1_rw_bitmask;

    env->CP0_SRSConf1 = def->CP0_SRSConf1;

    env->CP0_SRSConf2_rw_bitmask = def->CP0_SRSConf2_rw_bitmask;

    env->CP0_SRSConf2 = def->CP0_SRSConf2;

    env->CP0_SRSConf3_rw_bitmask = def->CP0_SRSConf3_rw_bitmask;

    env->CP0_SRSConf3 = def->CP0_SRSConf3;

    env->CP0_SRSConf4_rw_bitmask = def->CP0_SRSConf4_rw_bitmask;

    env->CP0_SRSConf4 = def->CP0_SRSConf4;

    env->insn_flags = def->insn_flags;

#ifndef CONFIG_USER_ONLY

    mmu_init(env, def);

#endif

    fpu_init(env, def);

    mvp_init(env, def);

    return 0;

}


static void gd_update(DisplayChangeListener *dcl,

                      DisplayState *ds, int x, int y, int w, int h)

{

    GtkDisplayState *s = ds->opaque;

    int x1, x2, y1, y2;

    int mx, my;

    int fbw, fbh;

    int ww, wh;

    DPRINTF("update(x=%d, y=%d, w=%d, h=%d)\n", x, y, w, h);

    x1 = floor(x * s->scale_x);

    y1 = floor(y * s->scale_y);

    x2 = ceil(x * s->scale_x + w * s->scale_x);

    y2 = ceil(y * s->scale_y + h * s->scale_y);

    fbw = ds_get_width(s->ds) * s->scale_x;

    fbh = ds_get_height(s->ds) * s->scale_y;

    gdk_drawable_get_size(gtk_widget_get_window(s->drawing_area), &ww, &wh);

    mx = my = 0;

    if (ww > fbw) {

        mx = (ww - fbw) / 2;

    }

    if (wh > fbh) {

        my = (wh - fbh) / 2;

    }

    gtk_widget_queue_draw_area(s->drawing_area, mx + x1, my + y1, (x2 - x1), (y2 - y1));

}


static void load_module(const char *filename)

{

    void *dll;

    void (*init_func)(void);

    dll = dlopen(filename, RTLD_NOW);

    if (!dll) {

        fprintf(stderr, "Could not load module '%s' - %s\n",

                filename, dlerror());

    }

    init_func = dlsym(dll, "ffserver_module_init");

    if (!init_func) {

        fprintf(stderr,

                "%s: init function 'ffserver_module_init()' not found\n",

                filename);

        dlclose(dll);

    }

    init_func();

}


DVDemuxContext* avpriv_dv_init_demux(AVFormatContext *s)

{

    DVDemuxContext *c;

    c = av_mallocz(sizeof(DVDemuxContext));

    if (!c)

        return NULL;

    c->vst = avformat_new_stream(s, NULL);

    if (!c->vst) {

        av_free(c);

        return NULL;

    }

    c->sys  = NULL;

    c->fctx = s;

    memset(c->ast, 0, sizeof(c->ast));

    c->ach    = 0;

    c->frames = 0;

    c->abytes = 0;

    c->vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    c->vst->codec->codec_id   = CODEC_ID_DVVIDEO;

    c->vst->codec->bit_rate   = 25000000;

    c->vst->start_time        = 0;

    return c;

}


int ff_read_riff_info(AVFormatContext *s, int64_t size)

{

    int64_t start, end, cur;

    AVIOContext *pb = s->pb;

    start = avio_tell(pb);

    end = start + size;

    while ((cur = avio_tell(pb)) >= 0 && cur <= end - 8 /* = tag + size */) {

        uint32_t chunk_code;

        int64_t chunk_size;

        char key[5] = {0};

        char *value;

        chunk_code = avio_rl32(pb);

        chunk_size = avio_rl32(pb);

        if (chunk_size > end || end - chunk_size < cur || chunk_size == UINT_MAX) {

            av_log(s, AV_LOG_ERROR, "too big INFO subchunk\n");

            return AVERROR_INVALIDDATA;

        }

        chunk_size += (chunk_size & 1);

        value = av_malloc(chunk_size + 1);

        if (!value) {

            av_log(s, AV_LOG_ERROR, "out of memory, unable to read INFO tag\n");

            return AVERROR(ENOMEM);

        }

        AV_WL32(key, chunk_code);

        if (avio_read(pb, value, chunk_size) != chunk_size) {

            av_freep(key);

            av_freep(value);

            av_log(s, AV_LOG_ERROR, "premature end of file while reading INFO tag\n");

            return AVERROR_INVALIDDATA;

        }

        value[chunk_size] = 0;

        av_dict_set(&s->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);

    }

    return 0;

}


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

                             int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    H261Context *h     = avctx->priv_data;

    MpegEncContext *s  = &h->s;

    int ret;

    AVFrame *pict = data;

    av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);

    av_dlog(avctx, "bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);

    s->flags  = avctx->flags;

    s->flags2 = avctx->flags2;

    h->gob_start_code_skipped = 0;

retry:

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

    if (!s->context_initialized)

        // we need the IDCT permutaton for reading a custom matrix

        if (ff_MPV_common_init(s) < 0)

            return -1;

    ret = h261_decode_picture_header(h);

    /* skip if the header was thrashed */

    if (ret < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");

        return -1;

    }

    if (s->width != avctx->coded_width || s->height != avctx->coded_height) {

        ParseContext pc = s->parse_context; // FIXME move this demuxing hack to libavformat

        s->parse_context.buffer = 0;

        ff_MPV_common_end(s);

        s->parse_context = pc;

    }

    if (!s->context_initialized) {

        ret = ff_set_dimensions(avctx, s->width, s->height);

        if (ret < 0)

            return ret;

        goto retry;

    }

    // for skipping the frame

    s->current_picture.f.pict_type = s->pict_type;

    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;

    if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||

        (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) ||

         avctx->skip_frame >= AVDISCARD_ALL)

        return get_consumed_bytes(s, buf_size);

    if (ff_MPV_frame_start(s, avctx) < 0)

        return -1;

    ff_mpeg_er_frame_start(s);

    /* decode each macroblock */

    s->mb_x = 0;

    s->mb_y = 0;

    while (h->gob_number < (s->mb_height == 18 ? 12 : 5)) {

        if (h261_resync(h) < 0)

            break;

        h261_decode_gob(h);

    }

    ff_MPV_frame_end(s);

    assert(s->current_picture.f.pict_type == s->current_picture_ptr->f.pict_type);

    assert(s->current_picture.f.pict_type == s->pict_type);

    if ((ret = av_frame_ref(pict, &s->current_picture_ptr->f)) < 0)

        return ret;

    ff_print_debug_info(s, s->current_picture_ptr);

    *got_frame = 1;

    return get_consumed_bytes(s, buf_size);

}


int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,

    int n_start, int n_end, int *num, QCowL2Meta *m)

{

    BDRVQcowState *s = bs->opaque;

    int l2_index, ret, sectors;

    uint64_t *l2_table;

    unsigned int nb_clusters, keep_clusters;

    uint64_t cluster_offset;

    trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset,

                                      n_start, n_end);

    /* Find L2 entry for the first involved cluster */

again:

    ret = get_cluster_table(bs, offset, &l2_table, &l2_index);

    if (ret < 0) {

        return ret;

    }

    /*

     * Calculate the number of clusters to look for. We stop at L2 table

     * boundaries to keep things simple.

     */

    nb_clusters = MIN(size_to_clusters(s, n_end << BDRV_SECTOR_BITS),

                      s->l2_size - l2_index);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    /*

     * Check how many clusters are already allocated and don't need COW, and how

     * many need a new allocation.

     */

    if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL

        && (cluster_offset & QCOW_OFLAG_COPIED))

    {

        /* We keep all QCOW_OFLAG_COPIED clusters */

        keep_clusters =

            count_contiguous_clusters(nb_clusters, s->cluster_size,

                                      &l2_table[l2_index], 0,

                                      QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);

        assert(keep_clusters <= nb_clusters);

        nb_clusters -= keep_clusters;

    } else {

        /* For the moment, overwrite compressed clusters one by one */

        if (cluster_offset & QCOW_OFLAG_COMPRESSED) {

            nb_clusters = 1;

        } else {

            nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);

        }

        keep_clusters = 0;

        cluster_offset = 0;

    }

    cluster_offset &= L2E_OFFSET_MASK;

    /*

     * The L2 table isn't used any more after this. As long as the cache works

     * synchronously, it's important to release it before calling

     * do_alloc_cluster_offset, which may yield if we need to wait for another

     * request to complete. If we still had the reference, we could use up the

     * whole cache with sleeping requests.

     */

    ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);

    if (ret < 0) {

        return ret;

    }

    /* If there is something left to allocate, do that now */

    *m = (QCowL2Meta) {

        .cluster_offset     = cluster_offset,

        .nb_clusters        = 0,

    };

    qemu_co_queue_init(&m->dependent_requests);

    if (nb_clusters > 0) {

        uint64_t alloc_offset;

        uint64_t alloc_cluster_offset;

        uint64_t keep_bytes = keep_clusters * s->cluster_size;

        /* Calculate start and size of allocation */

        alloc_offset = offset + keep_bytes;

        if (keep_clusters == 0) {

            alloc_cluster_offset = 0;

        } else {

            alloc_cluster_offset = cluster_offset + keep_bytes;

        }

        /* Allocate, if necessary at a given offset in the image file */

        ret = do_alloc_cluster_offset(bs, alloc_offset, &alloc_cluster_offset,

                                      &nb_clusters);

        if (ret == -EAGAIN) {

            goto again;

        } else if (ret < 0) {

            goto fail;

        }

        /* save info needed for meta data update */

        if (nb_clusters > 0) {

            int requested_sectors = n_end - keep_clusters * s->cluster_sectors;

            int avail_sectors = (keep_clusters + nb_clusters)

                                << (s->cluster_bits - BDRV_SECTOR_BITS);

            *m = (QCowL2Meta) {

                .cluster_offset = keep_clusters == 0 ?

                                  alloc_cluster_offset : cluster_offset,

                .alloc_offset   = alloc_cluster_offset,

                .offset         = alloc_offset,

                .n_start        = keep_clusters == 0 ? n_start : 0,

                .nb_clusters    = nb_clusters,

                .nb_available   = MIN(requested_sectors, avail_sectors),

            };

            qemu_co_queue_init(&m->dependent_requests);

            QLIST_INSERT_HEAD(&s->cluster_allocs, m, next_in_flight);

        }

    }

    /* Some cleanup work */

    sectors = (keep_clusters + nb_clusters) << (s->cluster_bits - 9);

    if (sectors > n_end) {

        sectors = n_end;

    }

    assert(sectors > n_start);

    *num = sectors - n_start;

    return 0;

fail:

    if (m->nb_clusters > 0) {

        QLIST_REMOVE(m, next_in_flight);

    }

    return ret;

}


static void tb_gen_code(CPUState *env,

                        target_ulong pc, target_ulong cs_base, int flags,

                        int cflags)

{

    TranslationBlock *tb;

    uint8_t *tc_ptr;

    target_ulong phys_pc, phys_page2, virt_page2;

    int code_gen_size;

    phys_pc = get_phys_addr_code(env, pc);

    tb = tb_alloc(pc);

    if (!tb) {

        /* flush must be done */

        tb_flush(env);

        /* cannot fail at this point */

        tb = tb_alloc(pc);

    }

    tc_ptr = code_gen_ptr;

    tb->tc_ptr = tc_ptr;

    tb->cs_base = cs_base;

    tb->flags = flags;

    tb->cflags = cflags;

    cpu_gen_code(env, tb, CODE_GEN_MAX_SIZE, &code_gen_size);

    code_gen_ptr = (void *)(((unsigned long)code_gen_ptr + code_gen_size + CODE_GEN_ALIGN - 1) & ~(CODE_GEN_ALIGN - 1));

    /* check next page if needed */

    virt_page2 = (pc + tb->size - 1) & TARGET_PAGE_MASK;

    phys_page2 = -1;

    if ((pc & TARGET_PAGE_MASK) != virt_page2) {

        phys_page2 = get_phys_addr_code(env, virt_page2);

    }

    tb_link_phys(tb, phys_pc, phys_page2);

}


void cpu_inject_x86_mce(CPUState *cenv, int bank, uint64_t status,

                        uint64_t mcg_status, uint64_t addr, uint64_t misc)

{

    uint64_t mcg_cap = cenv->mcg_cap;

    unsigned bank_num = mcg_cap & 0xff;

    uint64_t *banks = cenv->mce_banks;

    if (bank >= bank_num || !(status & MCI_STATUS_VAL))

        return;

    if (kvm_enabled()) {

        kvm_inject_x86_mce(cenv, bank, status, mcg_status, addr, misc);

        return;

    }

    /*

     * if MSR_MCG_CTL is not all 1s, the uncorrected error

     * reporting is disabled

     */

    if ((status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&

        cenv->mcg_ctl != ~(uint64_t)0)

        return;

    banks += 4 * bank;

    /*

     * if MSR_MCi_CTL is not all 1s, the uncorrected error

     * reporting is disabled for the bank

     */

    if ((status & MCI_STATUS_UC) && banks[0] != ~(uint64_t)0)

        return;

    if (status & MCI_STATUS_UC) {

        if ((cenv->mcg_status & MCG_STATUS_MCIP) ||

            !(cenv->cr[4] & CR4_MCE_MASK)) {

            fprintf(stderr, "injects mce exception while previous "

                    "one is in progress!\n");

            qemu_log_mask(CPU_LOG_RESET, "Triple fault\n");

            qemu_system_reset_request();

            return;

        }

        if (banks[1] & MCI_STATUS_VAL)

            status |= MCI_STATUS_OVER;

        banks[2] = addr;

        banks[3] = misc;

        cenv->mcg_status = mcg_status;

        banks[1] = status;

        cpu_interrupt(cenv, CPU_INTERRUPT_MCE);

    } else if (!(banks[1] & MCI_STATUS_VAL)

               || !(banks[1] & MCI_STATUS_UC)) {

        if (banks[1] & MCI_STATUS_VAL)

            status |= MCI_STATUS_OVER;

        banks[2] = addr;

        banks[3] = misc;

        banks[1] = status;

    } else

        banks[1] |= MCI_STATUS_OVER;

}


void virtqueue_map_sg(struct iovec *sg, hwaddr *addr,

    size_t num_sg, int is_write)

{

    unsigned int i;

    hwaddr len;

    if (num_sg > VIRTQUEUE_MAX_SIZE) {

        error_report("virtio: map attempt out of bounds: %zd > %d",

                     num_sg, VIRTQUEUE_MAX_SIZE);

        exit(1);

    }

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

        len = sg[i].iov_len;

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

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

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

            exit(1);

        }

    }

}


static int aasc_decode_frame(AVCodecContext *avctx,
                              void *data, int *got_frame,
                              AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size       = avpkt->size;
    AascContext *s     = avctx->priv_data;
    int compr, i, stride, ret;
    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
        return ret;
    }
    compr     = AV_RL32(buf);
    buf      += 4;
    buf_size -= 4;
    switch (compr) {
    case 0:
        stride = (avctx->width * 3 + 3) & ~3;
        if (buf_size < stride * avctx->height)
        for (i = avctx->height - 1; i >= 0; i--) {
            memcpy(s->frame->data[0] + i * s->frame->linesize[0], buf, avctx->width * 3);
            buf += stride;
        }
        break;
    case 1:
        bytestream2_init(&s->gb, buf, buf_size);
        ff_msrle_decode(avctx, (AVPicture*)s->frame, 8, &s->gb);
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "Unknown compression type %d\n", compr);
    }
    *got_frame = 1;
    if ((ret = av_frame_ref(data, s->frame)) < 0)
        return ret;
    /* report that the buffer was completely consumed */
    return buf_size;
}


static av_always_inline void filter_common(uint8_t *p, ptrdiff_t stride,

                                           int is4tap)

{

    LOAD_PIXELS

    int a, f1, f2;

    const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;

    a = 3 * (q0 - p0);

    if (is4tap)

        a += clip_int8(p1 - q1);

    a = clip_int8(a);

    // We deviate from the spec here with c(a+3) >> 3

    // since that's what libvpx does.

    f1 = FFMIN(a + 4, 127) >> 3;

    f2 = FFMIN(a + 3, 127) >> 3;

    // Despite what the spec says, we do need to clamp here to

    // be bitexact with libvpx.

    p[-1 * stride] = cm[p0 + f2];

    p[ 0 * stride] = cm[q0 - f1];

    // only used for _inner on blocks without high edge variance

    if (!is4tap) {

        a = (f1 + 1) >> 1;

        p[-2 * stride] = cm[p1 + a];

        p[ 1 * stride] = cm[q1 - a];

    }

}


static int virtio_blk_init_pci(PCIDevice *pci_dev)

{

    VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);

    VirtIODevice *vdev;

    if (proxy->class_code != PCI_CLASS_STORAGE_SCSI &&

        proxy->class_code != PCI_CLASS_STORAGE_OTHER)

        proxy->class_code = PCI_CLASS_STORAGE_SCSI;

    if (!proxy->block.bs) {

        error_report("virtio-blk-pci: drive property not set");

    vdev = virtio_blk_init(&pci_dev->qdev, &proxy->block);

    vdev->nvectors = proxy->nvectors;

    virtio_init_pci(proxy, vdev,

                    PCI_VENDOR_ID_REDHAT_QUMRANET,

                    PCI_DEVICE_ID_VIRTIO_BLOCK,

                    proxy->class_code, 0x00);

    /* make the actual value visible */

    proxy->nvectors = vdev->nvectors;

    return 0;


static target_ulong helper_sdiv_common(CPUSPARCState *env, target_ulong a,

                                       target_ulong b, int cc)

{

    SPARCCPU *cpu = sparc_env_get_cpu(env);

    int overflow = 0;

    int64_t x0;

    int32_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 ((int32_t) x0 != x0) {

        x0 = x0 < 0 ? 0x80000000 : 0x7fffffff;

        overflow = 1;

    }

    if (cc) {

        env->cc_dst = x0;

        env->cc_src2 = overflow;

        env->cc_op = CC_OP_DIV;

    }

    return x0;

}