int net_init_l2tpv3(const NetClientOptions *opts,

                    const char *name,

                    NetClientState *peer, Error **errp)

{

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

    const NetdevL2TPv3Options *l2tpv3;

    NetL2TPV3State *s;

    NetClientState *nc;

    int fd = -1, gairet;

    struct addrinfo hints;

    struct addrinfo *result = NULL;

    char *srcport, *dstport;

    nc = qemu_new_net_client(&net_l2tpv3_info, peer, "l2tpv3", name);

    s = DO_UPCAST(NetL2TPV3State, nc, nc);

    s->queue_head = 0;

    s->queue_tail = 0;

    s->header_mismatch = false;

    assert(opts->type == NET_CLIENT_OPTIONS_KIND_L2TPV3);

    l2tpv3 = opts->u.l2tpv3;

    if (l2tpv3->has_ipv6 && l2tpv3->ipv6) {

        s->ipv6 = l2tpv3->ipv6;

    } else {

        s->ipv6 = false;

    }

    if ((l2tpv3->has_offset) && (l2tpv3->offset > 256)) {

        error_report("l2tpv3_open : offset must be less than 256 bytes");

        goto outerr;

    }

    if (l2tpv3->has_rxcookie || l2tpv3->has_txcookie) {

        if (l2tpv3->has_rxcookie && l2tpv3->has_txcookie) {

            s->cookie = true;

        } else {

            goto outerr;

        }

    } else {

        s->cookie = false;

    }

    if (l2tpv3->has_cookie64 || l2tpv3->cookie64) {

        s->cookie_is_64  = true;

    } else {

        s->cookie_is_64  = false;

    }

    if (l2tpv3->has_udp && l2tpv3->udp) {

        s->udp = true;

        if (!(l2tpv3->has_srcport && l2tpv3->has_dstport)) {

            error_report("l2tpv3_open : need both src and dst port for udp");

            goto outerr;

        } else {

            srcport = l2tpv3->srcport;

            dstport = l2tpv3->dstport;

        }

    } else {

        s->udp = false;

        srcport = NULL;

        dstport = NULL;

    }

    s->offset = 4;

    s->session_offset = 0;

    s->cookie_offset = 4;

    s->counter_offset = 4;

    s->tx_session = l2tpv3->txsession;

    if (l2tpv3->has_rxsession) {

        s->rx_session = l2tpv3->rxsession;

    } else {

        s->rx_session = s->tx_session;

    }

    if (s->cookie) {

        s->rx_cookie = l2tpv3->rxcookie;

        s->tx_cookie = l2tpv3->txcookie;

        if (s->cookie_is_64 == true) {

            /* 64 bit cookie */

            s->offset += 8;

            s->counter_offset += 8;

        } else {

            /* 32 bit cookie */

            s->offset += 4;

            s->counter_offset += 4;

        }

    }

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

    if (s->ipv6) {

        hints.ai_family = AF_INET6;

    } else {

        hints.ai_family = AF_INET;

    }

    if (s->udp) {

        hints.ai_socktype = SOCK_DGRAM;

        hints.ai_protocol = 0;

        s->offset += 4;

        s->counter_offset += 4;

        s->session_offset += 4;

        s->cookie_offset += 4;

    } else {

        hints.ai_socktype = SOCK_RAW;

        hints.ai_protocol = IPPROTO_L2TP;

    }

    gairet = getaddrinfo(l2tpv3->src, srcport, &hints, &result);

    if ((gairet != 0) || (result == NULL)) {

        error_report(

            "l2tpv3_open : could not resolve src, errno = %s",

            gai_strerror(gairet)

        );

        goto outerr;

    }

    fd = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

    if (fd == -1) {

        fd = -errno;

        error_report("l2tpv3_open : socket creation failed, errno = %d", -fd);

        goto outerr;

    }

    if (bind(fd, (struct sockaddr *) result->ai_addr, result->ai_addrlen)) {

        error_report("l2tpv3_open :  could not bind socket err=%i", errno);

        goto outerr;

    }

    if (result) {

        freeaddrinfo(result);

    }

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

    if (s->ipv6) {

        hints.ai_family = AF_INET6;

    } else {

        hints.ai_family = AF_INET;

    }

    if (s->udp) {

        hints.ai_socktype = SOCK_DGRAM;

        hints.ai_protocol = 0;

    } else {

        hints.ai_socktype = SOCK_RAW;

        hints.ai_protocol = IPPROTO_L2TP;

    }

    result = NULL;

    gairet = getaddrinfo(l2tpv3->dst, dstport, &hints, &result);

    if ((gairet != 0) || (result == NULL)) {

        error_report(

            "l2tpv3_open : could not resolve dst, error = %s",

            gai_strerror(gairet)

        );

        goto outerr;

    }

    s->dgram_dst = g_new0(struct sockaddr_storage, 1);

    memcpy(s->dgram_dst, result->ai_addr, result->ai_addrlen);

    s->dst_size = result->ai_addrlen;

    if (result) {

        freeaddrinfo(result);

    }

    if (l2tpv3->has_counter && l2tpv3->counter) {

        s->has_counter = true;

        s->offset += 4;

    } else {

        s->has_counter = false;

    }

    if (l2tpv3->has_pincounter && l2tpv3->pincounter) {

        s->has_counter = true;  /* pin counter implies that there is counter */

        s->pin_counter = true;

    } else {

        s->pin_counter = false;

    }

    if (l2tpv3->has_offset) {

        /* extra offset */

        s->offset += l2tpv3->offset;

    }

    if ((s->ipv6) || (s->udp)) {

        s->header_size = s->offset;

    } else {

        s->header_size = s->offset + sizeof(struct iphdr);

    }

    s->msgvec = build_l2tpv3_vector(s, MAX_L2TPV3_MSGCNT);

    s->vec = g_new(struct iovec, MAX_L2TPV3_IOVCNT);

    s->header_buf = g_malloc(s->header_size);

    qemu_set_nonblock(fd);

    s->fd = fd;

    s->counter = 0;

    l2tpv3_read_poll(s, true);

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

             "l2tpv3: connected");

    return 0;

outerr:

    qemu_del_net_client(nc);

    if (fd >= 0) {

        close(fd);

    }

    if (result) {

        freeaddrinfo(result);

    }

    return -1;

}


CPUDebugExcpHandler *cpu_set_debug_excp_handler(CPUDebugExcpHandler *handler)

{

    CPUDebugExcpHandler *old_handler = debug_excp_handler;

    debug_excp_handler = handler;

    return old_handler;

}


av_cold int ff_vp56_init_context(AVCodecContext *avctx, VP56Context *s,

                                  int flip, int has_alpha)

{

    int i;

    s->avctx = avctx;

    avctx->pix_fmt = has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P;

    if (avctx->skip_alpha) avctx->pix_fmt = AV_PIX_FMT_YUV420P;

    ff_h264chroma_init(&s->h264chroma, 8);

    ff_hpeldsp_init(&s->hdsp, avctx->flags);

    ff_videodsp_init(&s->vdsp, 8);

    ff_vp3dsp_init(&s->vp3dsp, avctx->flags);

    ff_vp56dsp_init(&s->vp56dsp, avctx->codec->id);

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

#define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)

        s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);

#undef TRANSPOSE

    }

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

        s->frames[i] = av_frame_alloc();

        if (!s->frames[i]) {

            ff_vp56_free(avctx);

            return AVERROR(ENOMEM);

        }

    }

    s->edge_emu_buffer_alloc = NULL;

    s->above_blocks = NULL;

    s->macroblocks = NULL;

    s->quantizer = -1;

    s->deblock_filtering = 1;

    s->golden_frame = 0;

    s->filter = NULL;

    s->has_alpha = has_alpha;

    s->modelp = &s->model;

    if (flip) {

        s->flip = -1;

        s->frbi = 2;

        s->srbi = 0;

    } else {

        s->flip = 1;

        s->frbi = 0;

        s->srbi = 2;

    }

    return 0;

}


static av_always_inline void dist_scale(HEVCContext *s, Mv *mv,

                                        int min_pu_width, int x, int y,

                                        int elist, int ref_idx_curr, int ref_idx)

{

    RefPicList *refPicList = s->ref->refPicList;

    MvField *tab_mvf       = s->ref->tab_mvf;

    int ref_pic_elist      = refPicList[elist].list[TAB_MVF(x, y).ref_idx[elist]];

    int ref_pic_curr       = refPicList[ref_idx_curr].list[ref_idx];

    if (ref_pic_elist != ref_pic_curr)

        mv_scale(mv, mv, s->poc - ref_pic_elist, s->poc - ref_pic_curr);

}


static int rm_write_video(AVFormatContext *s, const uint8_t *buf, int size)

{

    RMContext *rm = s->priv_data;

    ByteIOContext *pb = &s->pb;

    StreamInfo *stream = rm->video_stream;

    int key_frame = stream->enc->coded_frame->key_frame;

    /* XXX: this is incorrect: should be a parameter */

    /* Well, I spent some time finding the meaning of these bits. I am

       not sure I understood everything, but it works !! */

#if 1

    write_packet_header(s, stream, size + 7, key_frame);

    /* bit 7: '1' if final packet of a frame converted in several packets */

    put_byte(pb, 0x81);

    /* bit 7: '1' if I frame. bits 6..0 : sequence number in current

       frame starting from 1 */

    if (key_frame) {

        put_byte(pb, 0x81);

    } else {

        put_byte(pb, 0x01);

    }

    put_be16(pb, 0x4000 | (size)); /* total frame size */

    put_be16(pb, 0x4000 | (size));              /* offset from the start or the end */

#else

    /* full frame */

    write_packet_header(s, size + 6);

    put_byte(pb, 0xc0);

    put_be16(pb, 0x4000 | size); /* total frame size */

    put_be16(pb, 0x4000 + packet_number * 126); /* position in stream */

#endif

    put_byte(pb, stream->nb_frames & 0xff);

    put_buffer(pb, buf, size);

    put_flush_packet(pb);

    stream->nb_frames++;

    return 0;

}


void av_get_channel_layout_string(char *buf, int buf_size,

                                  int nb_channels, int64_t channel_layout)

{

    int i;

    if (nb_channels <= 0)

        nb_channels = av_get_channel_layout_nb_channels(channel_layout);

    for (i = 0; channel_layout_map[i].name; i++)

        if (nb_channels    == channel_layout_map[i].nb_channels &&

            channel_layout == channel_layout_map[i].layout) {

            av_strlcpy(buf, channel_layout_map[i].name, buf_size);

            return;

        }

    snprintf(buf, buf_size, "%d channels", nb_channels);

    if (channel_layout) {

        int i, ch;

        av_strlcat(buf, " (", buf_size);

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

            if ((channel_layout & (1L << i))) {

                const char *name = get_channel_name(i);

                if (name) {

                    if (ch > 0)

                        av_strlcat(buf, "|", buf_size);

                    av_strlcat(buf, name, buf_size);

                }

                ch++;

            }

        }

        av_strlcat(buf, ")", buf_size);

    }

}


void qemu_co_queue_run_restart(Coroutine *co)

{

    Coroutine *next;

    trace_qemu_co_queue_run_restart(co);

    while ((next = QSIMPLEQ_FIRST(&co->co_queue_wakeup))) {

        QSIMPLEQ_REMOVE_HEAD(&co->co_queue_wakeup, co_queue_next);

        qemu_coroutine_enter(next, NULL);

    }

}


static inline void RENAME(uyvyToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width)

{

#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)

	asm volatile(

		"movq "MANGLE(bm01010101)", %%mm4\n\t"

		"mov %0, %%"REG_a"		\n\t"

		"1:				\n\t"

		"movq (%1, %%"REG_a",4), %%mm0	\n\t"

		"movq 8(%1, %%"REG_a",4), %%mm1	\n\t"

		"movq (%2, %%"REG_a",4), %%mm2	\n\t"

		"movq 8(%2, %%"REG_a",4), %%mm3	\n\t"

		PAVGB(%%mm2, %%mm0)

		PAVGB(%%mm3, %%mm1)

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

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

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

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

		"psrlw $8, %%mm0		\n\t"

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

		"packuswb %%mm0, %%mm0		\n\t"

		"packuswb %%mm1, %%mm1		\n\t"

		"movd %%mm0, (%4, %%"REG_a")	\n\t"

		"movd %%mm1, (%3, %%"REG_a")	\n\t"

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

		" js 1b				\n\t"

		: : "g" ((long)-width), "r" (src1+width*4), "r" (src2+width*4), "r" (dstU+width), "r" (dstV+width)

		: "%"REG_a

	);

#else

	int i;

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

	{

		dstU[i]= (src1[4*i + 0] + src2[4*i + 0])>>1;

		dstV[i]= (src1[4*i + 2] + src2[4*i + 2])>>1;

	}

#endif

}


static void default_show_tags(WriterContext *wctx, AVDictionary *dict)

{

    AVDictionaryEntry *tag = NULL;

    while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {

        printf("TAG:");

        writer_print_string(wctx, tag->key, tag->value);

    }

}


static int decode_block(ALSDecContext *ctx, ALSBlockData *bd)

{

    unsigned int smp;

    // read block type flag and read the samples accordingly

    if (*bd->const_block)

        decode_const_block_data(ctx, bd);

    else if (decode_var_block_data(ctx, bd))

        return -1;

    // TODO: read RLSLMS extension data

    if (*bd->shift_lsbs)

        for (smp = 0; smp < bd->block_length; smp++)

            bd->raw_samples[smp] <<= *bd->shift_lsbs;

    return 0;

}


static void hdcd_reset(hdcd_state *state, unsigned rate, unsigned cdt_ms)

{

    int i;

    state->window = 0;

    state->readahead = 32;

    state->arg = 0;

    state->control = 0;

    state->running_gain = 0;

    state->sustain = 0;

    state->sustain_reset = cdt_ms*rate/1000;

    state->code_counterA = 0;

    state->code_counterA_almost = 0;

    state->code_counterB = 0;

    state->code_counterB_checkfails = 0;

    state->code_counterC = 0;

    state->code_counterC_unmatched = 0;

    state->count_peak_extend = 0;

    state->count_transient_filter = 0;

    for(i = 0; i < 16; i++) state->gain_counts[i] = 0;

    state->max_gain = 0;

    state->count_sustain_expired = -1;

    state->_ana_snb = 0;

}


static int ehci_register_companion(USBBus *bus, USBPort *ports[],

                                   uint32_t portcount, uint32_t firstport)

{

    EHCIState *s = container_of(bus, EHCIState, bus);

    uint32_t i;

    if (firstport + portcount > NB_PORTS) {

        qerror_report(QERR_INVALID_PARAMETER_VALUE, "firstport",

                      "firstport on masterbus");

        error_printf_unless_qmp(

            "firstport value of %u makes companion take ports %u - %u, which "

            "is outside of the valid range of 0 - %u\n", firstport, firstport,

            firstport + portcount - 1, NB_PORTS - 1);

        return -1;

    }

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

        if (s->companion_ports[firstport + i]) {

            qerror_report(QERR_INVALID_PARAMETER_VALUE, "masterbus",

                          "an USB masterbus");

            error_printf_unless_qmp(

                "port %u on masterbus %s already has a companion assigned\n",

                firstport + i, bus->qbus.name);

            return -1;

        }

    }

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

        s->companion_ports[firstport + i] = ports[i];

        s->ports[firstport + i].speedmask |=

            USB_SPEED_MASK_LOW | USB_SPEED_MASK_FULL;

        /* Ensure devs attached before the initial reset go to the companion */

        s->portsc[firstport + i] = PORTSC_POWNER;

    }

    s->companion_count++;

    s->mmio[0x05] = (s->companion_count << 4) | portcount;

    return 0;

}


static int ehci_execute(EHCIPacket *p, const char *action)

{

    USBEndpoint *ep;

    int ret;

    int endp;

    if (!(p->qtd.token & QTD_TOKEN_ACTIVE)) {

        fprintf(stderr, "Attempting to execute inactive qtd\n");

        return USB_RET_PROCERR;

    }

    p->tbytes = (p->qtd.token & QTD_TOKEN_TBYTES_MASK) >> QTD_TOKEN_TBYTES_SH;

    if (p->tbytes > BUFF_SIZE) {

        ehci_trace_guest_bug(p->queue->ehci,

                             "guest requested more bytes than allowed");

        return USB_RET_PROCERR;

    }

    p->pid = (p->qtd.token & QTD_TOKEN_PID_MASK) >> QTD_TOKEN_PID_SH;

    switch (p->pid) {

    case 0:

        p->pid = USB_TOKEN_OUT;

        break;

    case 1:

        p->pid = USB_TOKEN_IN;

        break;

    case 2:

        p->pid = USB_TOKEN_SETUP;

        break;

    default:

        fprintf(stderr, "bad token\n");

        break;

    }

    if (ehci_init_transfer(p) != 0) {

        return USB_RET_PROCERR;

    }

    endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);

    ep = usb_ep_get(p->queue->dev, p->pid, endp);

    usb_packet_setup(&p->packet, p->pid, ep, p->qtdaddr);

    usb_packet_map(&p->packet, &p->sgl);

    trace_usb_ehci_packet_action(p->queue, p, action);

    ret = usb_handle_packet(p->queue->dev, &p->packet);

    DPRINTF("submit: qh %x next %x qtd %x pid %x len %zd "

            "(total %d) endp %x ret %d\n",

            q->qhaddr, q->qh.next, q->qtdaddr, q->pid,

            q->packet.iov.size, q->tbytes, endp, ret);

    if (ret > BUFF_SIZE) {

        fprintf(stderr, "ret from usb_handle_packet > BUFF_SIZE\n");

        return USB_RET_PROCERR;

    }

    return ret;

}


int ff_ivi_decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                        AVPacket *avpkt)

{

    IVI45DecContext *ctx = avctx->priv_data;

    const uint8_t   *buf = avpkt->data;

    int             buf_size = avpkt->size;

    int             result, p, b;

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

    ctx->frame_data = buf;

    ctx->frame_size = buf_size;

    result = ctx->decode_pic_hdr(ctx, avctx);

    if (result) {

        av_log(avctx, AV_LOG_ERROR,

               "Error while decoding picture header: %d\n", result);

        return -1;

    }

    if (ctx->gop_invalid)

        return AVERROR_INVALIDDATA;

    if (ctx->gop_flags & IVI5_IS_PROTECTED) {

        av_log(avctx, AV_LOG_ERROR, "Password-protected clip!\n");

        return -1;

    }

    ctx->switch_buffers(ctx);

    //{ START_TIMER;

    if (ctx->is_nonnull_frame(ctx)) {

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

            for (b = 0; b < ctx->planes[p].num_bands; b++) {

                result = decode_band(ctx, p, &ctx->planes[p].bands[b], avctx);

                if (result) {

                    av_log(avctx, AV_LOG_ERROR,

                           "Error while decoding band: %d, plane: %d\n", b, p);

                    return -1;

                }

            }

        }

    }

    //STOP_TIMER("decode_planes"); }

    /* If the bidirectional mode is enabled, next I and the following P frame will */

    /* be sent together. Unfortunately the approach below seems to be the only way */

    /* to handle the B-frames mode. That's exactly the same Intel decoders do.     */

    if (avctx->codec_id == AV_CODEC_ID_INDEO4 && ctx->frame_type == 0/*FRAMETYPE_INTRA*/) {

        while (get_bits(&ctx->gb, 8)); // skip version string

        skip_bits_long(&ctx->gb, 64);  // skip padding, TODO: implement correct 8-bytes alignment

        if (get_bits_left(&ctx->gb) > 18 && show_bits(&ctx->gb, 18) == 0x3FFF8)

            av_log(avctx, AV_LOG_ERROR, "Buffer contains IP frames!\n");

    }

    if (ctx->frame.data[0])

        avctx->release_buffer(avctx, &ctx->frame);

    ctx->frame.reference = 0;

    if ((result = avctx->get_buffer(avctx, &ctx->frame)) < 0) {

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

        return result;

    }

    if (ctx->is_scalable) {

        if (avctx->codec_id == AV_CODEC_ID_INDEO4)

            ff_ivi_recompose_haar(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);

        else

            ff_ivi_recompose53   (&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);

    } else {

        ff_ivi_output_plane(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);

    }

    ff_ivi_output_plane(&ctx->planes[2], ctx->frame.data[1], ctx->frame.linesize[1]);

    ff_ivi_output_plane(&ctx->planes[1], ctx->frame.data[2], ctx->frame.linesize[2]);

    *data_size = sizeof(AVFrame);

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

    return buf_size;

}


static int avcodec_find_best_pix_fmt1(int64_t pix_fmt_mask,

                                      int src_pix_fmt,

                                      int has_alpha,

                                      int loss_mask)

{

    int dist, i, loss, min_dist, dst_pix_fmt;

    /* find exact color match with smallest size */

    dst_pix_fmt = -1;

    min_dist = 0x7fffffff;

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

        if (pix_fmt_mask & (1 << i)) {

            loss = avcodec_get_pix_fmt_loss(i, src_pix_fmt, has_alpha) & loss_mask;

            if (loss == 0) {

                dist = avg_bits_per_pixel(i);

                if (dist < min_dist) {

                    min_dist = dist;

                    dst_pix_fmt = i;

                }

            }

        }

    }

    return dst_pix_fmt;

}


static int vorbis_parse_audio_packet(vorbis_context *vc)

{

    GetBitContext *gb = &vc->gb;

    FFTContext *mdct;

    unsigned previous_window = vc->previous_window;

    unsigned mode_number, blockflag, blocksize;

    int i, j;

    uint8_t no_residue[255];

    uint8_t do_not_decode[255];

    vorbis_mapping *mapping;

    float *ch_res_ptr   = vc->channel_residues;

    float *ch_floor_ptr = vc->channel_floors;

    uint8_t res_chan[255];

    unsigned res_num = 0;

    int retlen  = 0;

    int ch_left = vc->audio_channels;

    if (get_bits1(gb)) {

        av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");

        return AVERROR_INVALIDDATA; // packet type not audio

    }

    if (vc->mode_count == 1) {

        mode_number = 0;

    } else {

        GET_VALIDATED_INDEX(mode_number, ilog(vc->mode_count-1), vc->mode_count)

    }

    vc->mode_number = mode_number;

    mapping = &vc->mappings[vc->modes[mode_number].mapping];

    av_dlog(NULL, " Mode number: %u , mapping: %d , blocktype %d\n", mode_number,

            vc->modes[mode_number].mapping, vc->modes[mode_number].blockflag);

    blockflag = vc->modes[mode_number].blockflag;

    blocksize = vc->blocksize[blockflag];

    if (blockflag)

        skip_bits(gb, 2); // previous_window, next_window

    memset(ch_res_ptr,   0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?

    memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?

// Decode floor

    for (i = 0; i < vc->audio_channels; ++i) {

        vorbis_floor *floor;

        int ret;

        if (mapping->submaps > 1) {

            floor = &vc->floors[mapping->submap_floor[mapping->mux[i]]];

        } else {

            floor = &vc->floors[mapping->submap_floor[0]];

        }

        ret = floor->decode(vc, &floor->data, ch_floor_ptr);

        if (ret < 0) {

            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");

            return AVERROR_INVALIDDATA;

        }

        no_residue[i] = ret;

        ch_floor_ptr += blocksize / 2;

    }

// Nonzero vector propagate

    for (i = mapping->coupling_steps - 1; i >= 0; --i) {

        if (!(no_residue[mapping->magnitude[i]] & no_residue[mapping->angle[i]])) {

            no_residue[mapping->magnitude[i]] = 0;

            no_residue[mapping->angle[i]]     = 0;

        }

    }

// Decode residue

    for (i = 0; i < mapping->submaps; ++i) {

        vorbis_residue *residue;

        unsigned ch = 0;

        for (j = 0; j < vc->audio_channels; ++j) {

            if ((mapping->submaps == 1) || (i == mapping->mux[j])) {

                res_chan[j] = res_num;

                if (no_residue[j]) {

                    do_not_decode[ch] = 1;

                } else {

                    do_not_decode[ch] = 0;

                }

                ++ch;

                ++res_num;

            }

        }

        residue = &vc->residues[mapping->submap_residue[i]];

        if (ch_left < ch) {

            av_log(vc->avccontext, AV_LOG_ERROR, "Too many channels in vorbis_floor_decode.\n");

            return -1;

        }

        vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, blocksize/2);

        ch_res_ptr += ch * blocksize / 2;

        ch_left -= ch;

    }

// Inverse coupling

    for (i = mapping->coupling_steps - 1; i >= 0; --i) { //warning: i has to be signed

        float *mag, *ang;

        mag = vc->channel_residues+res_chan[mapping->magnitude[i]] * blocksize / 2;

        ang = vc->channel_residues+res_chan[mapping->angle[i]]     * blocksize / 2;

        vc->dsp.vorbis_inverse_coupling(mag, ang, blocksize / 2);

    }

// Dotproduct, MDCT

    mdct = &vc->mdct[blockflag];

    for (j = vc->audio_channels-1;j >= 0; j--) {

        ch_floor_ptr = vc->channel_floors   + j           * blocksize / 2;

        ch_res_ptr   = vc->channel_residues + res_chan[j] * blocksize / 2;

        vc->dsp.vector_fmul(ch_floor_ptr, ch_floor_ptr, ch_res_ptr, blocksize / 2);

        mdct->imdct_half(mdct, ch_res_ptr, ch_floor_ptr);

    }

// Overlap/add, save data for next overlapping  FPMATH

    retlen = (blocksize + vc->blocksize[previous_window]) / 4;

    for (j = 0; j < vc->audio_channels; j++) {

        unsigned bs0 = vc->blocksize[0];

        unsigned bs1 = vc->blocksize[1];

        float *residue    = vc->channel_residues + res_chan[j] * blocksize / 2;

        float *saved      = vc->saved + j * bs1 / 4;

        float *ret        = vc->channel_floors + j * retlen;

        float *buf        = residue;

        const float *win  = vc->win[blockflag & previous_window];

        if (blockflag == previous_window) {

            vc->dsp.vector_fmul_window(ret, saved, buf, win, blocksize / 4);

        } else if (blockflag > previous_window) {

            vc->dsp.vector_fmul_window(ret, saved, buf, win, bs0 / 4);

            memcpy(ret+bs0/2, buf+bs0/4, ((bs1-bs0)/4) * sizeof(float));

        } else {

            memcpy(ret, saved, ((bs1 - bs0) / 4) * sizeof(float));

            vc->dsp.vector_fmul_window(ret + (bs1 - bs0) / 4, saved + (bs1 - bs0) / 4, buf, win, bs0 / 4);

        }

        memcpy(saved, buf + blocksize / 4, blocksize / 4 * sizeof(float));

    }

    vc->previous_window = blockflag;

    return retlen;

}


static int mpc8_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

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

    MPCContext *c = s->priv_data;

    int index = av_index_search_timestamp(st, timestamp, flags);

    if(index < 0) return -1;

    avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);

    c->frame = st->index_entries[index].timestamp;

    return 0;

}


static void pred8x8_left_dc_rv40_c(uint8_t *src, int stride){

    int i;

    int dc0;

    dc0=0;

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

        dc0+= src[-1+i*stride];

    dc0= 0x01010101*((dc0 + 4)>>3);

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

        ((uint32_t*)(src+i*stride))[0]=

        ((uint32_t*)(src+i*stride))[1]= dc0;

    }

}


static void usb_msd_command_complete(SCSIBus *bus, int reason, uint32_t tag,

                                     uint32_t arg)

{

    MSDState *s = DO_UPCAST(MSDState, dev.qdev, bus->qbus.parent);

    USBPacket *p = s->packet;

    if (tag != s->tag) {

        fprintf(stderr, "usb-msd: Unexpected SCSI Tag 0x%x\n", tag);

    }

    if (reason == SCSI_REASON_DONE) {

        DPRINTF("Command complete %d\n", arg);

        s->residue = s->data_len;

        s->result = arg != 0;

        if (s->packet) {

            if (s->data_len == 0 && s->mode == USB_MSDM_DATAOUT) {

                /* A deferred packet with no write data remaining must be

                   the status read packet.  */

                usb_msd_send_status(s, p);

                s->mode = USB_MSDM_CBW;

            } else {

                if (s->data_len) {

                    s->data_len -= s->usb_len;

                    if (s->mode == USB_MSDM_DATAIN)

                        memset(s->usb_buf, 0, s->usb_len);

                    s->usb_len = 0;

                }

                if (s->data_len == 0)

                    s->mode = USB_MSDM_CSW;

            }

            s->packet = NULL;

            usb_packet_complete(&s->dev, p);

        } else if (s->data_len == 0) {

            s->mode = USB_MSDM_CSW;

        }

        return;

    }

    s->scsi_len = arg;

    s->scsi_buf = s->scsi_dev->info->get_buf(s->scsi_dev, tag);

    if (p) {

        usb_msd_copy_data(s);

        if (s->usb_len == 0) {

            /* Set s->packet to NULL before calling usb_packet_complete

               because another request may be issued before

               usb_packet_complete returns.  */

            DPRINTF("Packet complete %p\n", p);

            s->packet = NULL;

            usb_packet_complete(&s->dev, p);

        }

    }

}


static int latm_decode_frame(AVCodecContext *avctx, void *out, int *out_size,

                             AVPacket *avpkt)

{

    struct LATMContext *latmctx = avctx->priv_data;

    int                 muxlength, err;

    GetBitContext       gb;

    if (avpkt->size == 0)

        return 0;

    init_get_bits(&gb, avpkt->data, avpkt->size * 8);

    // check for LOAS sync word

    if (get_bits(&gb, 11) != LOAS_SYNC_WORD)

        return AVERROR_INVALIDDATA;

    muxlength = get_bits(&gb, 13) + 3;

    // not enough data, the parser should have sorted this

    if (muxlength > avpkt->size)

        return AVERROR_INVALIDDATA;

    if ((err = read_audio_mux_element(latmctx, &gb)) < 0)

        return err;

    if (!latmctx->initialized) {

        if (!avctx->extradata) {

            *out_size = 0;

            return avpkt->size;

        } else {

            if ((err = aac_decode_init(avctx)) < 0)

                return err;

            latmctx->initialized = 1;

        }

    }

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

        av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,

               "ADTS header detected, probably as result of configuration "

               "misparsing\n");

        return AVERROR_INVALIDDATA;

    }

    if ((err = aac_decode_frame_int(avctx, out, out_size, &gb)) < 0)

        return err;

    return muxlength;

}


static void quantize_and_encode_band_mips(struct AACEncContext *s, PutBitContext *pb,

                                          const float *in, float *out, int size, int scale_idx,

                                          int cb, const float lambda, int rtz)

{

    quantize_and_encode_band_cost(s, pb, in, out, NULL, size, scale_idx, cb, lambda,

                                  INFINITY, NULL, (rtz) ? ROUND_TO_ZERO : ROUND_STANDARD);

}


void visit_type_number(Visitor *v, double *obj, const char *name, Error **errp)

{

    if (!error_is_set(errp)) {

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

    }

}


static void decode_opc (CPUMIPSState *env, DisasContext *ctx, int *is_branch)

{

    int32_t offset;

    int rs, rt, rd, sa;

    uint32_t op, op1, op2;

    int16_t imm;

    /* make sure instructions are on a word boundary */

    if (ctx->pc & 0x3) {

        env->CP0_BadVAddr = ctx->pc;

        generate_exception(ctx, EXCP_AdEL);

        return;

    }

    /* Handle blikely not taken case */

    if ((ctx->hflags & MIPS_HFLAG_BMASK_BASE) == MIPS_HFLAG_BL) {

        int l1 = gen_new_label();

        MIPS_DEBUG("blikely condition (" TARGET_FMT_lx ")", ctx->pc + 4);

        tcg_gen_brcondi_tl(TCG_COND_NE, bcond, 0, l1);

        tcg_gen_movi_i32(hflags, ctx->hflags & ~MIPS_HFLAG_BMASK);

        gen_goto_tb(ctx, 1, ctx->pc + 4);

        gen_set_label(l1);

    }

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT))) {

        tcg_gen_debug_insn_start(ctx->pc);

    }

    op = MASK_OP_MAJOR(ctx->opcode);

    rs = (ctx->opcode >> 21) & 0x1f;

    rt = (ctx->opcode >> 16) & 0x1f;

    rd = (ctx->opcode >> 11) & 0x1f;

    sa = (ctx->opcode >> 6) & 0x1f;

    imm = (int16_t)ctx->opcode;

    switch (op) {

    case OPC_SPECIAL:

        op1 = MASK_SPECIAL(ctx->opcode);

        switch (op1) {

        case OPC_SLL:          /* Shift with immediate */

        case OPC_SRA:

            gen_shift_imm(ctx, op1, rd, rt, sa);

            break;

        case OPC_SRL:

            switch ((ctx->opcode >> 21) & 0x1f) {

            case 1:

                /* rotr is decoded as srl on non-R2 CPUs */

                if (ctx->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_ROTR;

                }

                /* Fallthrough */

            case 0:

                gen_shift_imm(ctx, op1, rd, rt, sa);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_MOVN:         /* Conditional move */

        case OPC_MOVZ:

            check_insn(ctx, ISA_MIPS4 | ISA_MIPS32 |

                                 INSN_LOONGSON2E | INSN_LOONGSON2F);

            gen_cond_move(ctx, op1, rd, rs, rt);

            break;

        case OPC_ADD ... OPC_SUBU:

            gen_arith(ctx, op1, rd, rs, rt);

            break;

        case OPC_SLLV:         /* Shifts */

        case OPC_SRAV:

            gen_shift(ctx, op1, rd, rs, rt);

            break;

        case OPC_SRLV:

            switch ((ctx->opcode >> 6) & 0x1f) {

            case 1:

                /* rotrv is decoded as srlv on non-R2 CPUs */

                if (ctx->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_ROTRV;

                }

                /* Fallthrough */

            case 0:

                gen_shift(ctx, op1, rd, rs, rt);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_SLT:          /* Set on less than */

        case OPC_SLTU:

            gen_slt(ctx, op1, rd, rs, rt);

            break;

        case OPC_AND:          /* Logic*/

        case OPC_OR:

        case OPC_NOR:

        case OPC_XOR:

            gen_logic(ctx, op1, rd, rs, rt);

            break;

        case OPC_MULT:

        case OPC_MULTU:

            if (sa) {

                check_insn(ctx, INSN_VR54XX);

                op1 = MASK_MUL_VR54XX(ctx->opcode);

                gen_mul_vr54xx(ctx, op1, rd, rs, rt);

            } else {

                gen_muldiv(ctx, op1, rd & 3, rs, rt);

            }

            break;

        case OPC_DIV:

        case OPC_DIVU:

            gen_muldiv(ctx, op1, 0, rs, rt);

            break;

        case OPC_JR ... OPC_JALR:

            gen_compute_branch(ctx, op1, 4, rs, rd, sa);

            *is_branch = 1;

            break;

        case OPC_TGE ... OPC_TEQ: /* Traps */

        case OPC_TNE:

            gen_trap(ctx, op1, rs, rt, -1);

            break;

        case OPC_MFHI:          /* Move from HI/LO */

        case OPC_MFLO:

            gen_HILO(ctx, op1, rs & 3, rd);

            break;

        case OPC_MTHI:

        case OPC_MTLO:          /* Move to HI/LO */

            gen_HILO(ctx, op1, rd & 3, rs);

            break;

        case OPC_PMON:          /* Pmon entry point, also R4010 selsl */

#ifdef MIPS_STRICT_STANDARD

            MIPS_INVAL("PMON / selsl");

            generate_exception(ctx, EXCP_RI);

#else

            gen_helper_0e0i(pmon, sa);

#endif

            break;

        case OPC_SYSCALL:

            generate_exception(ctx, EXCP_SYSCALL);

            ctx->bstate = BS_STOP;

            break;

        case OPC_BREAK:

            generate_exception(ctx, EXCP_BREAK);

            break;

        case OPC_SPIM:

#ifdef MIPS_STRICT_STANDARD

            MIPS_INVAL("SPIM");

            generate_exception(ctx, EXCP_RI);

#else

           /* Implemented as RI exception for now. */

            MIPS_INVAL("spim (unofficial)");

            generate_exception(ctx, EXCP_RI);

#endif

            break;

        case OPC_SYNC:

            /* Treat as NOP. */

            break;

        case OPC_MOVCI:

            check_insn(ctx, ISA_MIPS4 | ISA_MIPS32);

            if (env->CP0_Config1 & (1 << CP0C1_FP)) {

                check_cp1_enabled(ctx);

                gen_movci(ctx, rd, rs, (ctx->opcode >> 18) & 0x7,

                          (ctx->opcode >> 16) & 1);

            } else {

                generate_exception_err(ctx, EXCP_CpU, 1);

            }

            break;

#if defined(TARGET_MIPS64)

       /* MIPS64 specific opcodes */

        case OPC_DSLL:

        case OPC_DSRA:

        case OPC_DSLL32:

        case OPC_DSRA32:

            check_insn(ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_shift_imm(ctx, op1, rd, rt, sa);

            break;

        case OPC_DSRL:

            switch ((ctx->opcode >> 21) & 0x1f) {

            case 1:

                /* drotr is decoded as dsrl on non-R2 CPUs */

                if (ctx->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_DROTR;

                }

                /* Fallthrough */

            case 0:

                check_insn(ctx, ISA_MIPS3);

                check_mips_64(ctx);

                gen_shift_imm(ctx, op1, rd, rt, sa);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DSRL32:

            switch ((ctx->opcode >> 21) & 0x1f) {

            case 1:

                /* drotr32 is decoded as dsrl32 on non-R2 CPUs */

                if (ctx->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_DROTR32;

                }

                /* Fallthrough */

            case 0:

                check_insn(ctx, ISA_MIPS3);

                check_mips_64(ctx);

                gen_shift_imm(ctx, op1, rd, rt, sa);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DADD ... OPC_DSUBU:

            check_insn(ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_arith(ctx, op1, rd, rs, rt);

            break;

        case OPC_DSLLV:

        case OPC_DSRAV:

            check_insn(ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_shift(ctx, op1, rd, rs, rt);

            break;

        case OPC_DSRLV:

            switch ((ctx->opcode >> 6) & 0x1f) {

            case 1:

                /* drotrv is decoded as dsrlv on non-R2 CPUs */

                if (ctx->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_DROTRV;

                }

                /* Fallthrough */

            case 0:

                check_insn(ctx, ISA_MIPS3);

                check_mips_64(ctx);

                gen_shift(ctx, op1, rd, rs, rt);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DMULT ... OPC_DDIVU:

            check_insn(ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_muldiv(ctx, op1, 0, rs, rt);

            break;

#endif

        default:            /* Invalid */

            MIPS_INVAL("special");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_SPECIAL2:

        op1 = MASK_SPECIAL2(ctx->opcode);

        switch (op1) {

        case OPC_MADD ... OPC_MADDU: /* Multiply and add/sub */

        case OPC_MSUB ... OPC_MSUBU:

            check_insn(ctx, ISA_MIPS32);

            gen_muldiv(ctx, op1, rd & 3, rs, rt);

            break;

        case OPC_MUL:

            gen_arith(ctx, op1, rd, rs, rt);

            break;

        case OPC_CLO:

        case OPC_CLZ:

            check_insn(ctx, ISA_MIPS32);

            gen_cl(ctx, op1, rd, rs);

            break;

        case OPC_SDBBP:

            /* XXX: not clear which exception should be raised

             *      when in debug mode...

             */

            check_insn(ctx, ISA_MIPS32);

            if (!(ctx->hflags & MIPS_HFLAG_DM)) {

                generate_exception(ctx, EXCP_DBp);

            } else {

                generate_exception(ctx, EXCP_DBp);

            }

            /* Treat as NOP. */

            break;

        case OPC_DIV_G_2F:

        case OPC_DIVU_G_2F:

        case OPC_MULT_G_2F:

        case OPC_MULTU_G_2F:

        case OPC_MOD_G_2F:

        case OPC_MODU_G_2F:

            check_insn(ctx, INSN_LOONGSON2F);

            gen_loongson_integer(ctx, op1, rd, rs, rt);

            break;

#if defined(TARGET_MIPS64)

        case OPC_DCLO:

        case OPC_DCLZ:

            check_insn(ctx, ISA_MIPS64);

            check_mips_64(ctx);

            gen_cl(ctx, op1, rd, rs);

            break;

        case OPC_DMULT_G_2F:

        case OPC_DMULTU_G_2F:

        case OPC_DDIV_G_2F:

        case OPC_DDIVU_G_2F:

        case OPC_DMOD_G_2F:

        case OPC_DMODU_G_2F:

            check_insn(ctx, INSN_LOONGSON2F);

            gen_loongson_integer(ctx, op1, rd, rs, rt);

            break;

#endif

        default:            /* Invalid */

            MIPS_INVAL("special2");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_SPECIAL3:

        op1 = MASK_SPECIAL3(ctx->opcode);

        switch (op1) {

        case OPC_EXT:

        case OPC_INS:

            check_insn(ctx, ISA_MIPS32R2);

            gen_bitops(ctx, op1, rt, rs, sa, rd);

            break;

        case OPC_BSHFL:

            check_insn(ctx, ISA_MIPS32R2);

            op2 = MASK_BSHFL(ctx->opcode);

            gen_bshfl(ctx, op2, rt, rd);

            break;

        case OPC_RDHWR:

            gen_rdhwr(ctx, rt, rd);

            break;

        case OPC_FORK:

            check_insn(ctx, ASE_MT);

            {

                TCGv t0 = tcg_temp_new();

                TCGv t1 = tcg_temp_new();

                gen_load_gpr(t0, rt);

                gen_load_gpr(t1, rs);

                gen_helper_fork(t0, t1);

                tcg_temp_free(t0);

                tcg_temp_free(t1);

            }

            break;

        case OPC_YIELD:

            check_insn(ctx, ASE_MT);

            {

                TCGv t0 = tcg_temp_new();

                save_cpu_state(ctx, 1);

                gen_load_gpr(t0, rs);

                gen_helper_yield(t0, cpu_env, t0);

                gen_store_gpr(t0, rd);

                tcg_temp_free(t0);

            }

            break;

        case OPC_DIV_G_2E ... OPC_DIVU_G_2E:

        case OPC_MOD_G_2E ... OPC_MODU_G_2E:

        case OPC_MULT_G_2E ... OPC_MULTU_G_2E:

        /* OPC_MULT_G_2E, OPC_ADDUH_QB_DSP, OPC_MUL_PH_DSP have

         * the same mask and op1. */

            if ((ctx->insn_flags & ASE_DSPR2) && (op1 == OPC_MULT_G_2E)) {

                op2 = MASK_ADDUH_QB(ctx->opcode);

                switch (op2) {

                case OPC_ADDUH_QB:

                case OPC_ADDUH_R_QB:

                case OPC_ADDQH_PH:

                case OPC_ADDQH_R_PH:

                case OPC_ADDQH_W:

                case OPC_ADDQH_R_W:

                case OPC_SUBUH_QB:

                case OPC_SUBUH_R_QB:

                case OPC_SUBQH_PH:

                case OPC_SUBQH_R_PH:

                case OPC_SUBQH_W:

                case OPC_SUBQH_R_W:

                    gen_mipsdsp_arith(ctx, op1, op2, rd, rs, rt);

                    break;

                case OPC_MUL_PH:

                case OPC_MUL_S_PH:

                case OPC_MULQ_S_W:

                case OPC_MULQ_RS_W:

                    gen_mipsdsp_multiply(ctx, op1, op2, rd, rs, rt, 1);

                    break;

                default:

                    MIPS_INVAL("MASK ADDUH.QB");

                    generate_exception(ctx, EXCP_RI);

                    break;

                }

            } else if (ctx->insn_flags & INSN_LOONGSON2E) {

                gen_loongson_integer(ctx, op1, rd, rs, rt);

            } else {

                generate_exception(ctx, EXCP_RI);

            }

            break;

        case OPC_LX_DSP:

            op2 = MASK_LX(ctx->opcode);

            switch (op2) {

#if defined(TARGET_MIPS64)

            case OPC_LDX:

#endif

            case OPC_LBUX:

            case OPC_LHX:

            case OPC_LWX:

                gen_mipsdsp_ld(ctx, op2, rd, rs, rt);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK LX");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_ABSQ_S_PH_DSP:

            op2 = MASK_ABSQ_S_PH(ctx->opcode);

            switch (op2) {

            case OPC_ABSQ_S_QB:

            case OPC_ABSQ_S_PH:

            case OPC_ABSQ_S_W:

            case OPC_PRECEQ_W_PHL:

            case OPC_PRECEQ_W_PHR:

            case OPC_PRECEQU_PH_QBL:

            case OPC_PRECEQU_PH_QBR:

            case OPC_PRECEQU_PH_QBLA:

            case OPC_PRECEQU_PH_QBRA:

            case OPC_PRECEU_PH_QBL:

            case OPC_PRECEU_PH_QBR:

            case OPC_PRECEU_PH_QBLA:

            case OPC_PRECEU_PH_QBRA:

                gen_mipsdsp_arith(ctx, op1, op2, rd, rs, rt);

                break;

            case OPC_BITREV:

            case OPC_REPL_QB:

            case OPC_REPLV_QB:

            case OPC_REPL_PH:

            case OPC_REPLV_PH:

                gen_mipsdsp_bitinsn(ctx, op1, op2, rd, rt);

                break;

            default:

                MIPS_INVAL("MASK ABSQ_S.PH");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_ADDU_QB_DSP:

            op2 = MASK_ADDU_QB(ctx->opcode);

            switch (op2) {

            case OPC_ADDQ_PH:

            case OPC_ADDQ_S_PH:

            case OPC_ADDQ_S_W:

            case OPC_ADDU_QB:

            case OPC_ADDU_S_QB:

            case OPC_ADDU_PH:

            case OPC_ADDU_S_PH:

            case OPC_SUBQ_PH:

            case OPC_SUBQ_S_PH:

            case OPC_SUBQ_S_W:

            case OPC_SUBU_QB:

            case OPC_SUBU_S_QB:

            case OPC_SUBU_PH:

            case OPC_SUBU_S_PH:

            case OPC_ADDSC:

            case OPC_ADDWC:

            case OPC_MODSUB:

            case OPC_RADDU_W_QB:

                gen_mipsdsp_arith(ctx, op1, op2, rd, rs, rt);

                break;

            case OPC_MULEU_S_PH_QBL:

            case OPC_MULEU_S_PH_QBR:

            case OPC_MULQ_RS_PH:

            case OPC_MULEQ_S_W_PHL:

            case OPC_MULEQ_S_W_PHR:

            case OPC_MULQ_S_PH:

                gen_mipsdsp_multiply(ctx, op1, op2, rd, rs, rt, 1);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK ADDU.QB");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_CMPU_EQ_QB_DSP:

            op2 = MASK_CMPU_EQ_QB(ctx->opcode);

            switch (op2) {

            case OPC_PRECR_SRA_PH_W:

            case OPC_PRECR_SRA_R_PH_W:

                gen_mipsdsp_arith(ctx, op1, op2, rt, rs, rd);

                break;

            case OPC_PRECR_QB_PH:

            case OPC_PRECRQ_QB_PH:

            case OPC_PRECRQ_PH_W:

            case OPC_PRECRQ_RS_PH_W:

            case OPC_PRECRQU_S_QB_PH:

                gen_mipsdsp_arith(ctx, op1, op2, rd, rs, rt);

                break;

            case OPC_CMPU_EQ_QB:

            case OPC_CMPU_LT_QB:

            case OPC_CMPU_LE_QB:

            case OPC_CMP_EQ_PH:

            case OPC_CMP_LT_PH:

            case OPC_CMP_LE_PH:

                gen_mipsdsp_add_cmp_pick(ctx, op1, op2, rd, rs, rt, 0);

                break;

            case OPC_CMPGU_EQ_QB:

            case OPC_CMPGU_LT_QB:

            case OPC_CMPGU_LE_QB:

            case OPC_CMPGDU_EQ_QB:

            case OPC_CMPGDU_LT_QB:

            case OPC_CMPGDU_LE_QB:

            case OPC_PICK_QB:

            case OPC_PICK_PH:

            case OPC_PACKRL_PH:

                gen_mipsdsp_add_cmp_pick(ctx, op1, op2, rd, rs, rt, 1);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK CMPU.EQ.QB");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_SHLL_QB_DSP:

            gen_mipsdsp_shift(ctx, op1, rd, rs, rt);

            break;

        case OPC_DPA_W_PH_DSP:

            op2 = MASK_DPA_W_PH(ctx->opcode);

            switch (op2) {

            case OPC_DPAU_H_QBL:

            case OPC_DPAU_H_QBR:

            case OPC_DPSU_H_QBL:

            case OPC_DPSU_H_QBR:

            case OPC_DPA_W_PH:

            case OPC_DPAX_W_PH:

            case OPC_DPAQ_S_W_PH:

            case OPC_DPAQX_S_W_PH:

            case OPC_DPAQX_SA_W_PH:

            case OPC_DPS_W_PH:

            case OPC_DPSX_W_PH:

            case OPC_DPSQ_S_W_PH:

            case OPC_DPSQX_S_W_PH:

            case OPC_DPSQX_SA_W_PH:

            case OPC_MULSAQ_S_W_PH:

            case OPC_DPAQ_SA_L_W:

            case OPC_DPSQ_SA_L_W:

            case OPC_MAQ_S_W_PHL:

            case OPC_MAQ_S_W_PHR:

            case OPC_MAQ_SA_W_PHL:

            case OPC_MAQ_SA_W_PHR:

            case OPC_MULSA_W_PH:

                gen_mipsdsp_multiply(ctx, op1, op2, rd, rs, rt, 0);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK DPAW.PH");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_INSV_DSP:

            op2 = MASK_INSV(ctx->opcode);

            switch (op2) {

            case OPC_INSV:

                check_dsp(ctx);

                {

                    TCGv t0, t1;

                    if (rt == 0) {

                        MIPS_DEBUG("NOP");

                        break;

                    }

                    t0 = tcg_temp_new();

                    t1 = tcg_temp_new();

                    gen_load_gpr(t0, rt);

                    gen_load_gpr(t1, rs);

                    gen_helper_insv(cpu_gpr[rt], cpu_env, t1, t0);

                    tcg_temp_free(t0);

                    tcg_temp_free(t1);

                    break;

                }

            default:            /* Invalid */

                MIPS_INVAL("MASK INSV");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_APPEND_DSP:

            gen_mipsdsp_append(env, ctx, op1, rt, rs, rd);

            break;

        case OPC_EXTR_W_DSP:

            op2 = MASK_EXTR_W(ctx->opcode);

            switch (op2) {

            case OPC_EXTR_W:

            case OPC_EXTR_R_W:

            case OPC_EXTR_RS_W:

            case OPC_EXTR_S_H:

            case OPC_EXTRV_S_H:

            case OPC_EXTRV_W:

            case OPC_EXTRV_R_W:

            case OPC_EXTRV_RS_W:

            case OPC_EXTP:

            case OPC_EXTPV:

            case OPC_EXTPDP:

            case OPC_EXTPDPV:

                gen_mipsdsp_accinsn(ctx, op1, op2, rt, rs, rd, 1);

                break;

            case OPC_RDDSP:

                gen_mipsdsp_accinsn(ctx, op1, op2, rd, rs, rt, 1);

                break;

            case OPC_SHILO:

            case OPC_SHILOV:

            case OPC_MTHLIP:

            case OPC_WRDSP:

                gen_mipsdsp_accinsn(ctx, op1, op2, rd, rs, rt, 0);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK EXTR.W");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

#if defined(TARGET_MIPS64)

        case OPC_DEXTM ... OPC_DEXT:

        case OPC_DINSM ... OPC_DINS:

            check_insn(ctx, ISA_MIPS64R2);

            check_mips_64(ctx);

            gen_bitops(ctx, op1, rt, rs, sa, rd);

            break;

        case OPC_DBSHFL:

            check_insn(ctx, ISA_MIPS64R2);

            check_mips_64(ctx);

            op2 = MASK_DBSHFL(ctx->opcode);

            gen_bshfl(ctx, op2, rt, rd);

            break;

        case OPC_DDIV_G_2E ... OPC_DDIVU_G_2E:

        case OPC_DMULT_G_2E ... OPC_DMULTU_G_2E:

        case OPC_DMOD_G_2E ... OPC_DMODU_G_2E:

            check_insn(ctx, INSN_LOONGSON2E);

            gen_loongson_integer(ctx, op1, rd, rs, rt);

            break;

        case OPC_ABSQ_S_QH_DSP:

            op2 = MASK_ABSQ_S_QH(ctx->opcode);

            switch (op2) {

            case OPC_PRECEQ_L_PWL:

            case OPC_PRECEQ_L_PWR:

            case OPC_PRECEQ_PW_QHL:

            case OPC_PRECEQ_PW_QHR:

            case OPC_PRECEQ_PW_QHLA:

            case OPC_PRECEQ_PW_QHRA:

            case OPC_PRECEQU_QH_OBL:

            case OPC_PRECEQU_QH_OBR:

            case OPC_PRECEQU_QH_OBLA:

            case OPC_PRECEQU_QH_OBRA:

            case OPC_PRECEU_QH_OBL:

            case OPC_PRECEU_QH_OBR:

            case OPC_PRECEU_QH_OBLA:

            case OPC_PRECEU_QH_OBRA:

            case OPC_ABSQ_S_OB:

            case OPC_ABSQ_S_PW:

            case OPC_ABSQ_S_QH:

                gen_mipsdsp_arith(ctx, op1, op2, rd, rs, rt);

                break;

            case OPC_REPL_OB:

            case OPC_REPL_PW:

            case OPC_REPL_QH:

            case OPC_REPLV_OB:

            case OPC_REPLV_PW:

            case OPC_REPLV_QH:

                gen_mipsdsp_bitinsn(ctx, op1, op2, rd, rt);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK ABSQ_S.QH");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_ADDU_OB_DSP:

            op2 = MASK_ADDU_OB(ctx->opcode);

            switch (op2) {

            case OPC_RADDU_L_OB:

            case OPC_SUBQ_PW:

            case OPC_SUBQ_S_PW:

            case OPC_SUBQ_QH:

            case OPC_SUBQ_S_QH:

            case OPC_SUBU_OB:

            case OPC_SUBU_S_OB:

            case OPC_SUBU_QH:

            case OPC_SUBU_S_QH:

            case OPC_SUBUH_OB:

            case OPC_SUBUH_R_OB:

            case OPC_ADDQ_PW:

            case OPC_ADDQ_S_PW:

            case OPC_ADDQ_QH:

            case OPC_ADDQ_S_QH:

            case OPC_ADDU_OB:

            case OPC_ADDU_S_OB:

            case OPC_ADDU_QH:

            case OPC_ADDU_S_QH:

            case OPC_ADDUH_OB:

            case OPC_ADDUH_R_OB:

                gen_mipsdsp_arith(ctx, op1, op2, rd, rs, rt);

                break;

            case OPC_MULEQ_S_PW_QHL:

            case OPC_MULEQ_S_PW_QHR:

            case OPC_MULEU_S_QH_OBL:

            case OPC_MULEU_S_QH_OBR:

            case OPC_MULQ_RS_QH:

                gen_mipsdsp_multiply(ctx, op1, op2, rd, rs, rt, 1);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK ADDU.OB");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_CMPU_EQ_OB_DSP:

            op2 = MASK_CMPU_EQ_OB(ctx->opcode);

            switch (op2) {

            case OPC_PRECR_SRA_QH_PW:

            case OPC_PRECR_SRA_R_QH_PW:

                /* Return value is rt. */

                gen_mipsdsp_arith(ctx, op1, op2, rt, rs, rd);

                break;

            case OPC_PRECR_OB_QH:

            case OPC_PRECRQ_OB_QH:

            case OPC_PRECRQ_PW_L:

            case OPC_PRECRQ_QH_PW:

            case OPC_PRECRQ_RS_QH_PW:

            case OPC_PRECRQU_S_OB_QH:

                gen_mipsdsp_arith(ctx, op1, op2, rd, rs, rt);

                break;

            case OPC_CMPU_EQ_OB:

            case OPC_CMPU_LT_OB:

            case OPC_CMPU_LE_OB:

            case OPC_CMP_EQ_QH:

            case OPC_CMP_LT_QH:

            case OPC_CMP_LE_QH:

            case OPC_CMP_EQ_PW:

            case OPC_CMP_LT_PW:

            case OPC_CMP_LE_PW:

                gen_mipsdsp_add_cmp_pick(ctx, op1, op2, rd, rs, rt, 0);

                break;

            case OPC_CMPGDU_EQ_OB:

            case OPC_CMPGDU_LT_OB:

            case OPC_CMPGDU_LE_OB:

            case OPC_CMPGU_EQ_OB:

            case OPC_CMPGU_LT_OB:

            case OPC_CMPGU_LE_OB:

            case OPC_PACKRL_PW:

            case OPC_PICK_OB:

            case OPC_PICK_PW:

            case OPC_PICK_QH:

                gen_mipsdsp_add_cmp_pick(ctx, op1, op2, rd, rs, rt, 1);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK CMPU_EQ.OB");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DAPPEND_DSP:

            gen_mipsdsp_append(env, ctx, op1, rt, rs, rd);

            break;

        case OPC_DEXTR_W_DSP:

            op2 = MASK_DEXTR_W(ctx->opcode);

            switch (op2) {

            case OPC_DEXTP:

            case OPC_DEXTPDP:

            case OPC_DEXTPDPV:

            case OPC_DEXTPV:

            case OPC_DEXTR_L:

            case OPC_DEXTR_R_L:

            case OPC_DEXTR_RS_L:

            case OPC_DEXTR_W:

            case OPC_DEXTR_R_W:

            case OPC_DEXTR_RS_W:

            case OPC_DEXTR_S_H:

            case OPC_DEXTRV_L:

            case OPC_DEXTRV_R_L:

            case OPC_DEXTRV_RS_L:

            case OPC_DEXTRV_S_H:

            case OPC_DEXTRV_W:

            case OPC_DEXTRV_R_W:

            case OPC_DEXTRV_RS_W:

                gen_mipsdsp_accinsn(ctx, op1, op2, rt, rs, rd, 1);

                break;

            case OPC_DMTHLIP:

            case OPC_DSHILO:

            case OPC_DSHILOV:

                gen_mipsdsp_accinsn(ctx, op1, op2, rd, rs, rt, 0);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK EXTR.W");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DPAQ_W_QH_DSP:

            op2 = MASK_DPAQ_W_QH(ctx->opcode);

            switch (op2) {

            case OPC_DPAU_H_OBL:

            case OPC_DPAU_H_OBR:

            case OPC_DPSU_H_OBL:

            case OPC_DPSU_H_OBR:

            case OPC_DPA_W_QH:

            case OPC_DPAQ_S_W_QH:

            case OPC_DPS_W_QH:

            case OPC_DPSQ_S_W_QH:

            case OPC_MULSAQ_S_W_QH:

            case OPC_DPAQ_SA_L_PW:

            case OPC_DPSQ_SA_L_PW:

            case OPC_MULSAQ_S_L_PW:

                gen_mipsdsp_multiply(ctx, op1, op2, rd, rs, rt, 0);

                break;

            case OPC_MAQ_S_W_QHLL:

            case OPC_MAQ_S_W_QHLR:

            case OPC_MAQ_S_W_QHRL:

            case OPC_MAQ_S_W_QHRR:

            case OPC_MAQ_SA_W_QHLL:

            case OPC_MAQ_SA_W_QHLR:

            case OPC_MAQ_SA_W_QHRL:

            case OPC_MAQ_SA_W_QHRR:

            case OPC_MAQ_S_L_PWL:

            case OPC_MAQ_S_L_PWR:

            case OPC_DMADD:

            case OPC_DMADDU:

            case OPC_DMSUB:

            case OPC_DMSUBU:

                gen_mipsdsp_multiply(ctx, op1, op2, rd, rs, rt, 0);

                break;

            default:            /* Invalid */

                MIPS_INVAL("MASK DPAQ.W.QH");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DINSV_DSP:

            op2 = MASK_INSV(ctx->opcode);

            switch (op2) {

            case OPC_DINSV:

                {

                    TCGv t0, t1;

                    if (rt == 0) {

                        MIPS_DEBUG("NOP");

                        break;

                    }

                    check_dsp(ctx);

                    t0 = tcg_temp_new();

                    t1 = tcg_temp_new();

                    gen_load_gpr(t0, rt);

                    gen_load_gpr(t1, rs);

                    gen_helper_dinsv(cpu_gpr[rt], cpu_env, t1, t0);

                    break;

                }

            default:            /* Invalid */

                MIPS_INVAL("MASK DINSV");

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_SHLL_OB_DSP:

            gen_mipsdsp_shift(ctx, op1, rd, rs, rt);

            break;

#endif

        default:            /* Invalid */

            MIPS_INVAL("special3");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_REGIMM:

        op1 = MASK_REGIMM(ctx->opcode);

        switch (op1) {

        case OPC_BLTZ ... OPC_BGEZL: /* REGIMM branches */

        case OPC_BLTZAL ... OPC_BGEZALL:

            gen_compute_branch(ctx, op1, 4, rs, -1, imm << 2);

            *is_branch = 1;

            break;

        case OPC_TGEI ... OPC_TEQI: /* REGIMM traps */

        case OPC_TNEI:

            gen_trap(ctx, op1, rs, -1, imm);

            break;

        case OPC_SYNCI:

            check_insn(ctx, ISA_MIPS32R2);

            /* Treat as NOP. */

            break;

        case OPC_BPOSGE32:    /* MIPS DSP branch */

#if defined(TARGET_MIPS64)

        case OPC_BPOSGE64:

#endif

            check_dsp(ctx);

            gen_compute_branch(ctx, op1, 4, -1, -2, (int32_t)imm << 2);

            *is_branch = 1;

            break;

        default:            /* Invalid */

            MIPS_INVAL("regimm");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_CP0:

        check_cp0_enabled(ctx);

        op1 = MASK_CP0(ctx->opcode);

        switch (op1) {

        case OPC_MFC0:

        case OPC_MTC0:

        case OPC_MFTR:

        case OPC_MTTR:

#if defined(TARGET_MIPS64)

        case OPC_DMFC0:

        case OPC_DMTC0:

#endif

#ifndef CONFIG_USER_ONLY

            gen_cp0(env, ctx, op1, rt, rd);

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_C0_FIRST ... OPC_C0_LAST:

#ifndef CONFIG_USER_ONLY

            gen_cp0(env, ctx, MASK_C0(ctx->opcode), rt, rd);

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_MFMC0:

#ifndef CONFIG_USER_ONLY

            {

                TCGv t0 = tcg_temp_new();

                op2 = MASK_MFMC0(ctx->opcode);

                switch (op2) {

                case OPC_DMT:

                    check_insn(ctx, ASE_MT);

                    gen_helper_dmt(t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_EMT:

                    check_insn(ctx, ASE_MT);

                    gen_helper_emt(t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_DVPE:

                    check_insn(ctx, ASE_MT);

                    gen_helper_dvpe(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_EVPE:

                    check_insn(ctx, ASE_MT);

                    gen_helper_evpe(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_DI:

                    check_insn(ctx, ISA_MIPS32R2);

                    save_cpu_state(ctx, 1);

                    gen_helper_di(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    /* Stop translation as we may have switched the execution mode */

                    ctx->bstate = BS_STOP;

                    break;

                case OPC_EI:

                    check_insn(ctx, ISA_MIPS32R2);

                    save_cpu_state(ctx, 1);

                    gen_helper_ei(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    /* Stop translation as we may have switched the execution mode */

                    ctx->bstate = BS_STOP;

                    break;

                default:            /* Invalid */

                    MIPS_INVAL("mfmc0");

                    generate_exception(ctx, EXCP_RI);

                    break;

                }

                tcg_temp_free(t0);

            }

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_RDPGPR:

            check_insn(ctx, ISA_MIPS32R2);

            gen_load_srsgpr(rt, rd);

            break;

        case OPC_WRPGPR:

            check_insn(ctx, ISA_MIPS32R2);

            gen_store_srsgpr(rt, rd);

            break;

        default:

            MIPS_INVAL("cp0");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_ADDI: /* Arithmetic with immediate opcode */

    case OPC_ADDIU:

         gen_arith_imm(ctx, op, rt, rs, imm);

         break;

    case OPC_SLTI: /* Set on less than with immediate opcode */

    case OPC_SLTIU:

         gen_slt_imm(ctx, op, rt, rs, imm);

         break;

    case OPC_ANDI: /* Arithmetic with immediate opcode */

    case OPC_LUI:

    case OPC_ORI:

    case OPC_XORI:

         gen_logic_imm(ctx, op, rt, rs, imm);

         break;

    case OPC_J ... OPC_JAL: /* Jump */

         offset = (int32_t)(ctx->opcode & 0x3FFFFFF) << 2;

         gen_compute_branch(ctx, op, 4, rs, rt, offset);

         *is_branch = 1;

         break;

    case OPC_BEQ ... OPC_BGTZ: /* Branch */

    case OPC_BEQL ... OPC_BGTZL:

         gen_compute_branch(ctx, op, 4, rs, rt, imm << 2);

         *is_branch = 1;

         break;

    case OPC_LB ... OPC_LWR: /* Load and stores */

    case OPC_LL:

         gen_ld(ctx, op, rt, rs, imm);

         break;

    case OPC_SB ... OPC_SW:

    case OPC_SWR:

         gen_st(ctx, op, rt, rs, imm);

         break;

    case OPC_SC:

         gen_st_cond(ctx, op, rt, rs, imm);

         break;

    case OPC_CACHE:

        check_cp0_enabled(ctx);

        check_insn(ctx, ISA_MIPS3 | ISA_MIPS32);

        /* Treat as NOP. */

        break;

    case OPC_PREF:

        check_insn(ctx, ISA_MIPS4 | ISA_MIPS32);

        /* Treat as NOP. */

        break;

    /* Floating point (COP1). */

    case OPC_LWC1:

    case OPC_LDC1:

    case OPC_SWC1:

    case OPC_SDC1:

        gen_cop1_ldst(env, ctx, op, rt, rs, imm);

        break;

    case OPC_CP1:

        if (env->CP0_Config1 & (1 << CP0C1_FP)) {

            check_cp1_enabled(ctx);

            op1 = MASK_CP1(ctx->opcode);

            switch (op1) {

            case OPC_MFHC1:

            case OPC_MTHC1:

                check_insn(ctx, ISA_MIPS32R2);

            case OPC_MFC1:

            case OPC_CFC1:

            case OPC_MTC1:

            case OPC_CTC1:

                gen_cp1(ctx, op1, rt, rd);

                break;

#if defined(TARGET_MIPS64)

            case OPC_DMFC1:

            case OPC_DMTC1:

                check_insn(ctx, ISA_MIPS3);

                gen_cp1(ctx, op1, rt, rd);

                break;

#endif

            case OPC_BC1ANY2:

            case OPC_BC1ANY4:

                check_cop1x(ctx);

                check_insn(ctx, ASE_MIPS3D);

                /* fall through */

            case OPC_BC1:

                gen_compute_branch1(ctx, MASK_BC1(ctx->opcode),

                                    (rt >> 2) & 0x7, imm << 2);

                *is_branch = 1;

                break;

            case OPC_S_FMT:

            case OPC_D_FMT:

            case OPC_W_FMT:

            case OPC_L_FMT:

            case OPC_PS_FMT:

                gen_farith(ctx, ctx->opcode & FOP(0x3f, 0x1f), rt, rd, sa,

                           (imm >> 8) & 0x7);

                break;

            default:

                MIPS_INVAL("cp1");

                generate_exception (ctx, EXCP_RI);

                break;

            }

        } else {

            generate_exception_err(ctx, EXCP_CpU, 1);

        }

        break;

    /* COP2.  */

    case OPC_LWC2:

    case OPC_LDC2:

    case OPC_SWC2:

    case OPC_SDC2:

        /* COP2: Not implemented. */

        generate_exception_err(ctx, EXCP_CpU, 2);

        break;

    case OPC_CP2:

        check_insn(ctx, INSN_LOONGSON2F);

        /* Note that these instructions use different fields.  */

        gen_loongson_multimedia(ctx, sa, rd, rt);

        break;

    case OPC_CP3:

        if (env->CP0_Config1 & (1 << CP0C1_FP)) {

            check_cp1_enabled(ctx);

            op1 = MASK_CP3(ctx->opcode);

            switch (op1) {

            case OPC_LWXC1:

            case OPC_LDXC1:

            case OPC_LUXC1:

            case OPC_SWXC1:

            case OPC_SDXC1:

            case OPC_SUXC1:

                gen_flt3_ldst(ctx, op1, sa, rd, rs, rt);

                break;

            case OPC_PREFX:

                /* Treat as NOP. */

                break;

            case OPC_ALNV_PS:

            case OPC_MADD_S:

            case OPC_MADD_D:

            case OPC_MADD_PS:

            case OPC_MSUB_S:

            case OPC_MSUB_D:

            case OPC_MSUB_PS:

            case OPC_NMADD_S:

            case OPC_NMADD_D:

            case OPC_NMADD_PS:

            case OPC_NMSUB_S:

            case OPC_NMSUB_D:

            case OPC_NMSUB_PS:

                gen_flt3_arith(ctx, op1, sa, rs, rd, rt);

                break;

            default:

                MIPS_INVAL("cp3");

                generate_exception (ctx, EXCP_RI);

                break;

            }

        } else {

            generate_exception_err(ctx, EXCP_CpU, 1);

        }

        break;

#if defined(TARGET_MIPS64)

    /* MIPS64 opcodes */

    case OPC_LWU:

    case OPC_LDL ... OPC_LDR:

    case OPC_LLD:

    case OPC_LD:

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_ld(ctx, op, rt, rs, imm);

        break;

    case OPC_SDL ... OPC_SDR:

    case OPC_SD:

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_st(ctx, op, rt, rs, imm);

        break;

    case OPC_SCD:

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_st_cond(ctx, op, rt, rs, imm);

        break;

    case OPC_DADDI:

    case OPC_DADDIU:

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_arith_imm(ctx, op, rt, rs, imm);

        break;

#endif

    case OPC_JALX:

        check_insn(ctx, ASE_MIPS16 | ASE_MICROMIPS);

        offset = (int32_t)(ctx->opcode & 0x3FFFFFF) << 2;

        gen_compute_branch(ctx, op, 4, rs, rt, offset);

        *is_branch = 1;

        break;

    case OPC_MDMX:

        check_insn(ctx, ASE_MDMX);

        /* MDMX: Not implemented. */

    default:            /* Invalid */

        MIPS_INVAL("major opcode");

        generate_exception(ctx, EXCP_RI);

        break;

    }

}


static int lzw_get_code(struct LZWState * s)

{

    int c;

    if(s->mode == FF_LZW_GIF) {

        while (s->bbits < s->cursize) {

            if (!s->bs) {

                s->bs = *s->pbuf++;

                if(!s->bs) {

                    s->eob_reached = 1;

                    break;

                }

            }

            s->bbuf |= (*s->pbuf++) << s->bbits;

            s->bbits += 8;

            s->bs--;

        }

        c = s->bbuf & s->curmask;

        s->bbuf >>= s->cursize;

    } else { // TIFF

        while (s->bbits < s->cursize) {

            if (s->pbuf >= s->ebuf) {

                s->eob_reached = 1;

            }

            s->bbuf = (s->bbuf << 8) | (*s->pbuf++);

            s->bbits += 8;

        }

        c = (s->bbuf >> (s->bbits - s->cursize)) & s->curmask;

    }

    s->bbits -= s->cursize;

    return c;

}


static av_cold int yop_decode_init(AVCodecContext *avctx)
{
    YopDecContext *s = avctx->priv_data;
    s->avctx = avctx;
    if (avctx->width & 1 || avctx->height & 1 ||
        av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
        av_log(avctx, AV_LOG_ERROR, "YOP has invalid dimensions\n");
        return -1;
    avctx->pix_fmt = PIX_FMT_PAL8;
    avcodec_get_frame_defaults(&s->frame);
    s->num_pal_colors = avctx->extradata[0];
    s->first_color[0] = avctx->extradata[1];
    s->first_color[1] = avctx->extradata[2];
    if (s->num_pal_colors + s->first_color[0] > 256 ||
        s->num_pal_colors + s->first_color[1] > 256) {
        av_log(avctx, AV_LOG_ERROR,
               "YOP: palette parameters invalid, header probably corrupt\n");
    return 0;


static int local_open(FsContext *ctx, V9fsPath *fs_path,

                      int flags, V9fsFidOpenState *fs)

{

    char *buffer;

    char *path = fs_path->data;

    int fd;

    buffer = rpath(ctx, path);

    fd = open(buffer, flags | O_NOFOLLOW);

    g_free(buffer);

    if (fd == -1) {

        return -1;

    }

    fs->fd = fd;

    return fs->fd;

}


static int local_lstat(FsContext *fs_ctx, V9fsPath *fs_path, struct stat *stbuf)

{

    int err;

    char *buffer;

    char *path = fs_path->data;

    buffer = rpath(fs_ctx, path);

    err =  lstat(buffer, stbuf);

    if (err) {

        goto err_out;

    }

    if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

        /* Actual credentials are part of extended attrs */

        uid_t tmp_uid;

        gid_t tmp_gid;

        mode_t tmp_mode;

        dev_t tmp_dev;

        if (getxattr(buffer, "user.virtfs.uid", &tmp_uid, sizeof(uid_t)) > 0) {

            stbuf->st_uid = le32_to_cpu(tmp_uid);

        }

        if (getxattr(buffer, "user.virtfs.gid", &tmp_gid, sizeof(gid_t)) > 0) {

            stbuf->st_gid = le32_to_cpu(tmp_gid);

        }

        if (getxattr(buffer, "user.virtfs.mode",

                    &tmp_mode, sizeof(mode_t)) > 0) {

            stbuf->st_mode = le32_to_cpu(tmp_mode);

        }

        if (getxattr(buffer, "user.virtfs.rdev", &tmp_dev, sizeof(dev_t)) > 0) {

            stbuf->st_rdev = le64_to_cpu(tmp_dev);

        }

    } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        local_mapped_file_attr(fs_ctx, path, stbuf);

    }

err_out:

    g_free(buffer);

    return err;

}


int vnc_tls_set_x509_creds_dir(VncDisplay *vd,

                               const char *certdir)

{

    if (vnc_set_x509_credential(vd, certdir, X509_CA_CERT_FILE, &vd->tls.x509cacert, 0) < 0)

        goto cleanup;

    if (vnc_set_x509_credential(vd, certdir, X509_CA_CRL_FILE, &vd->tls.x509cacrl, 1) < 0)

        goto cleanup;

    if (vnc_set_x509_credential(vd, certdir, X509_SERVER_CERT_FILE, &vd->tls.x509cert, 0) < 0)

        goto cleanup;

    if (vnc_set_x509_credential(vd, certdir, X509_SERVER_KEY_FILE, &vd->tls.x509key, 0) < 0)

        goto cleanup;

    return 0;

 cleanup:

    g_free(vd->tls.x509cacert);

    g_free(vd->tls.x509cacrl);

    g_free(vd->tls.x509cert);

    g_free(vd->tls.x509key);

    vd->tls.x509cacert = vd->tls.x509cacrl = vd->tls.x509cert = vd->tls.x509key = NULL;

    return -1;

}


int mm_support(void)

{

    int rval;

    int eax, ebx, ecx, edx;

    __asm__ __volatile__ (

                          /* See if CPUID instruction is supported ... */

                          /* ... Get copies of EFLAGS into eax and ecx */

                          "pushf\n\t"

                          "pop %0\n\t"

                          "movl %0, %1\n\t"

                          /* ... Toggle the ID bit in one copy and store */

                          /*     to the EFLAGS reg */

                          "xorl $0x200000, %0\n\t"

                          "push %0\n\t"

                          "popf\n\t"

                          /* ... Get the (hopefully modified) EFLAGS */

                          "pushf\n\t"

                          "pop %0\n\t"

                          : "=a" (eax), "=c" (ecx)

                          :

                          : "cc"

                          );

    if (eax == ecx)

        return 0; /* CPUID not supported */

    cpuid(0, eax, ebx, ecx, edx);

    if (ebx == 0x756e6547 &&

        edx == 0x49656e69 &&

        ecx == 0x6c65746e) {

        /* intel */

    inteltest:

        cpuid(1, eax, ebx, ecx, edx);

        if ((edx & 0x00800000) == 0)

            return 0;

        rval = MM_MMX;

        if (edx & 0x02000000)

            rval |= MM_MMXEXT | MM_SSE;

        if (edx & 0x04000000)

            rval |= MM_SSE2;

        return rval;

    } else if (ebx == 0x68747541 &&

               edx == 0x69746e65 &&

               ecx == 0x444d4163) {

        /* AMD */

        cpuid(0x80000000, eax, ebx, ecx, edx);

        if ((unsigned)eax < 0x80000001)

            goto inteltest;

        cpuid(0x80000001, eax, ebx, ecx, edx);

        if ((edx & 0x00800000) == 0)

            return 0;

        rval = MM_MMX;

        if (edx & 0x80000000)

            rval |= MM_3DNOW;

        if (edx & 0x00400000)

            rval |= MM_MMXEXT;

        return rval;

    } else if (ebx == 0x746e6543 &&

               edx == 0x48727561 &&

               ecx == 0x736c7561) {  /*  "CentaurHauls" */

        /* VIA C3 */

        cpuid(0x80000000, eax, ebx, ecx, edx);

        if ((unsigned)eax < 0x80000001)

            goto inteltest;

	cpuid(0x80000001, eax, ebx, ecx, edx);

	rval = 0;

	if( edx & ( 1 << 31) )

	  rval |= MM_3DNOW;

	if( edx & ( 1 << 23) )

	  rval |= MM_MMX;

	if( edx & ( 1 << 24) )

	  rval |= MM_MMXEXT;

        if(rval==0)

            goto inteltest;

	return rval;

    } else if (ebx == 0x69727943 &&

               edx == 0x736e4978 &&

               ecx == 0x64616574) {

        /* Cyrix Section */

        /* See if extended CPUID level 80000001 is supported */

        /* The value of CPUID/80000001 for the 6x86MX is undefined

           according to the Cyrix CPU Detection Guide (Preliminary

           Rev. 1.01 table 1), so we'll check the value of eax for

           CPUID/0 to see if standard CPUID level 2 is supported.

           According to the table, the only CPU which supports level

           2 is also the only one which supports extended CPUID levels.

        */

        if (eax != 2)

            goto inteltest;

        cpuid(0x80000001, eax, ebx, ecx, edx);

        if ((eax & 0x00800000) == 0)

            return 0;

        rval = MM_MMX;

        if (eax & 0x01000000)

            rval |= MM_MMXEXT;

        return rval;

    } else if (ebx == 0x756e6547 &&

               edx == 0x54656e69 &&

               ecx == 0x3638784d) {

        /* Tranmeta Crusoe */

        cpuid(0x80000000, eax, ebx, ecx, edx);

        if ((unsigned)eax < 0x80000001)

            return 0;

        cpuid(0x80000001, eax, ebx, ecx, edx);

        if ((edx & 0x00800000) == 0)

            return 0;

        return MM_MMX;

    } else {

        return 0;

    }

}


static uint64_t xscom_read(void *opaque, hwaddr addr, unsigned width)

{

    PnvChip *chip = opaque;

    uint32_t pcba = pnv_xscom_pcba(chip, addr);

    uint64_t val = 0;

    MemTxResult result;

    /* Handle some SCOMs here before dispatch */

    val = xscom_read_default(chip, pcba);

    if (val != -1) {

        goto complete;

    }

    val = address_space_ldq(&chip->xscom_as, pcba << 3, MEMTXATTRS_UNSPECIFIED,

                            &result);

    if (result != MEMTX_OK) {

        qemu_log_mask(LOG_GUEST_ERROR, "XSCOM read failed at @0x%"

                      HWADDR_PRIx " pcba=0x%08x\n", addr, pcba);

        xscom_complete(current_cpu, HMER_XSCOM_FAIL | HMER_XSCOM_DONE);

        return 0;

    }

complete:

    xscom_complete(current_cpu, HMER_XSCOM_DONE);

    return val;

}


static int remove_mapping(BDRVVVFATState* s, int mapping_index)

{

    mapping_t* mapping = array_get(&(s->mapping), mapping_index);

    mapping_t* first_mapping = array_get(&(s->mapping), 0);

    /* free mapping */

    if (mapping->first_mapping_index < 0)

	free(mapping->path);

    /* remove from s->mapping */

    array_remove(&(s->mapping), mapping_index);

    /* adjust all references to mappings */

    adjust_mapping_indices(s, mapping_index, -1);

    if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)

	s->current_mapping = array_get(&(s->mapping),

		s->current_mapping - first_mapping);

    return 0;

}


static void test_redirector_tx(void)

{

#ifndef _WIN32

/* socketpair(PF_UNIX) which does not exist on windows */

    int backend_sock[2], recv_sock;

    char *cmdline;

    uint32_t ret = 0, len = 0;

    char send_buf[] = "Hello!!";

    char sock_path0[] = "filter-redirector0.XXXXXX";

    char sock_path1[] = "filter-redirector1.XXXXXX";

    char *recv_buf;

    uint32_t size = sizeof(send_buf);

    size = htonl(size);

    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, backend_sock);

    g_assert_cmpint(ret, !=, -1);

    ret = mkstemp(sock_path0);

    g_assert_cmpint(ret, !=, -1);

    ret = mkstemp(sock_path1);

    g_assert_cmpint(ret, !=, -1);

    cmdline = g_strdup_printf("-netdev socket,id=qtest-bn0,fd=%d "

                "-device rtl8139,netdev=qtest-bn0,id=qtest-e0 "

                "-chardev socket,id=redirector0,path=%s,server,nowait "

                "-chardev socket,id=redirector1,path=%s,server,nowait "

                "-chardev socket,id=redirector2,path=%s,nowait "

                "-object filter-redirector,id=qtest-f0,netdev=qtest-bn0,"

                "queue=tx,outdev=redirector0 "

                "-object filter-redirector,id=qtest-f1,netdev=qtest-bn0,"

                "queue=tx,indev=redirector2 "

                "-object filter-redirector,id=qtest-f2,netdev=qtest-bn0,"

                "queue=tx,outdev=redirector1 "

                , backend_sock[1], sock_path0, sock_path1, sock_path0);

    qtest_start(cmdline);

    g_free(cmdline);

    recv_sock = unix_connect(sock_path1, NULL);

    g_assert_cmpint(recv_sock, !=, -1);

    /* send a qmp command to guarantee that 'connected' is setting to true. */

    qmp("{ 'execute' : 'query-status'}");

    struct iovec iov[] = {

        {

            .iov_base = &size,

            .iov_len = sizeof(size),

        }, {

            .iov_base = send_buf,

            .iov_len = sizeof(send_buf),

        },

    };

    ret = iov_send(backend_sock[0], iov, 2, 0, sizeof(size) + sizeof(send_buf));

    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(size));

    close(backend_sock[0]);

    ret = qemu_recv(recv_sock, &len, sizeof(len), 0);

    g_assert_cmpint(ret, ==, sizeof(len));

    len = ntohl(len);

    g_assert_cmpint(len, ==, sizeof(send_buf));

    recv_buf = g_malloc(len);

    ret = qemu_recv(recv_sock, recv_buf, len, 0);

    g_assert_cmpstr(recv_buf, ==, send_buf);

    g_free(recv_buf);

    close(recv_sock);

    unlink(sock_path0);

    unlink(sock_path1);

    qtest_end();

#endif

}


void do_divduo (void)

{

    if (likely((uint64_t)T1 != 0)) {

        xer_ov = 0;

        T0 = (uint64_t)T0 / (uint64_t)T1;

    } else {

        xer_so = 1;

        xer_ov = 1;

        T0 = 0;

    }

}


static int megasas_dcmd_cfg_read(MegasasState *s, MegasasCmd *cmd)

{

    uint8_t data[4096];

    struct mfi_config_data *info;

    int num_pd_disks = 0, array_offset, ld_offset;

    BusChild *kid;

    if (cmd->iov_size > 4096) {

        return MFI_STAT_INVALID_PARAMETER;

    }

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

        num_pd_disks++;

    }

    info = (struct mfi_config_data *)&data;

    /*

     * Array mapping:

     * - One array per SCSI device

     * - One logical drive per SCSI device

     *   spanning the entire device

     */

    info->array_count = num_pd_disks;

    info->array_size = sizeof(struct mfi_array) * num_pd_disks;

    info->log_drv_count = num_pd_disks;

    info->log_drv_size = sizeof(struct mfi_ld_config) * num_pd_disks;

    info->spares_count = 0;

    info->spares_size = sizeof(struct mfi_spare);

    info->size = sizeof(struct mfi_config_data) + info->array_size +

        info->log_drv_size;

    if (info->size > 4096) {

        return MFI_STAT_INVALID_PARAMETER;

    }

    array_offset = sizeof(struct mfi_config_data);

    ld_offset = array_offset + sizeof(struct mfi_array) * num_pd_disks;

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

        SCSIDevice *sdev = SCSI_DEVICE(kid->child);

        uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF);

        struct mfi_array *array;

        struct mfi_ld_config *ld;

        uint64_t pd_size;

        int i;

        array = (struct mfi_array *)(data + array_offset);

        blk_get_geometry(sdev->conf.blk, &pd_size);

        array->size = cpu_to_le64(pd_size);

        array->num_drives = 1;

        array->array_ref = cpu_to_le16(sdev_id);

        array->pd[0].ref.v.device_id = cpu_to_le16(sdev_id);

        array->pd[0].ref.v.seq_num = 0;

        array->pd[0].fw_state = MFI_PD_STATE_ONLINE;

        array->pd[0].encl.pd = 0xFF;

        array->pd[0].encl.slot = (sdev->id & 0xFF);

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

            array->pd[i].ref.v.device_id = 0xFFFF;

            array->pd[i].ref.v.seq_num = 0;

            array->pd[i].fw_state = MFI_PD_STATE_UNCONFIGURED_GOOD;

            array->pd[i].encl.pd = 0xFF;

            array->pd[i].encl.slot = 0xFF;

        }

        array_offset += sizeof(struct mfi_array);

        ld = (struct mfi_ld_config *)(data + ld_offset);

        memset(ld, 0, sizeof(struct mfi_ld_config));

        ld->properties.ld.v.target_id = sdev->id;

        ld->properties.default_cache_policy = MR_LD_CACHE_READ_AHEAD |

            MR_LD_CACHE_READ_ADAPTIVE;

        ld->properties.current_cache_policy = MR_LD_CACHE_READ_AHEAD |

            MR_LD_CACHE_READ_ADAPTIVE;

        ld->params.state = MFI_LD_STATE_OPTIMAL;

        ld->params.stripe_size = 3;

        ld->params.num_drives = 1;

        ld->params.span_depth = 1;

        ld->params.is_consistent = 1;

        ld->span[0].start_block = 0;

        ld->span[0].num_blocks = cpu_to_le64(pd_size);

        ld->span[0].array_ref = cpu_to_le16(sdev_id);

        ld_offset += sizeof(struct mfi_ld_config);

    }

    cmd->iov_size -= dma_buf_read((uint8_t *)data, info->size, &cmd->qsg);

    return MFI_STAT_OK;

}


static void lsi_do_msgout(LSIState *s)

{

    uint8_t msg;

    int len;

    uint32_t current_tag;

    SCSIDevice *current_dev;

    lsi_request *p, *p_next;

    int id;

    if (s->current) {

        current_tag = s->current->tag;

    } else {

        current_tag = s->select_tag;

    }

    id = (current_tag >> 8) & 0xf;

    current_dev = s->bus.devs[id];

    DPRINTF("MSG out len=%d\n", s->dbc);

    while (s->dbc) {

        msg = lsi_get_msgbyte(s);

        s->sfbr = msg;

        switch (msg) {

        case 0x04:

            DPRINTF("MSG: Disconnect\n");

            lsi_disconnect(s);

            break;

        case 0x08:

            DPRINTF("MSG: No Operation\n");

            lsi_set_phase(s, PHASE_CMD);

            break;

        case 0x01:

            len = lsi_get_msgbyte(s);

            msg = lsi_get_msgbyte(s);

            (void)len; /* avoid a warning about unused variable*/

            DPRINTF("Extended message 0x%x (len %d)\n", msg, len);

            switch (msg) {

            case 1:

                DPRINTF("SDTR (ignored)\n");

                lsi_skip_msgbytes(s, 2);

                break;

            case 3:

                DPRINTF("WDTR (ignored)\n");

                lsi_skip_msgbytes(s, 1);

                break;

            default:

                goto bad;

            }

            break;

        case 0x20: /* SIMPLE queue */

            s->select_tag |= lsi_get_msgbyte(s) | LSI_TAG_VALID;

            DPRINTF("SIMPLE queue tag=0x%x\n", s->select_tag & 0xff);

            break;

        case 0x21: /* HEAD of queue */

            BADF("HEAD queue not implemented\n");

            s->select_tag |= lsi_get_msgbyte(s) | LSI_TAG_VALID;

            break;

        case 0x22: /* ORDERED queue */

            BADF("ORDERED queue not implemented\n");

            s->select_tag |= lsi_get_msgbyte(s) | LSI_TAG_VALID;

            break;

        case 0x0d:

            /* The ABORT TAG message clears the current I/O process only. */

            DPRINTF("MSG: ABORT TAG tag=0x%x\n", current_tag);

            current_dev->info->cancel_io(current_dev, current_tag);

            lsi_disconnect(s);

            break;

        case 0x06:

        case 0x0e:

        case 0x0c:

            /* The ABORT message clears all I/O processes for the selecting

               initiator on the specified logical unit of the target. */

            if (msg == 0x06) {

                DPRINTF("MSG: ABORT tag=0x%x\n", current_tag);

            }

            /* The CLEAR QUEUE message clears all I/O processes for all

               initiators on the specified logical unit of the target. */

            if (msg == 0x0e) {

                DPRINTF("MSG: CLEAR QUEUE tag=0x%x\n", current_tag);

            }

            /* The BUS DEVICE RESET message clears all I/O processes for all

               initiators on all logical units of the target. */

            if (msg == 0x0c) {

                DPRINTF("MSG: BUS DEVICE RESET tag=0x%x\n", current_tag);

            }

            /* clear the current I/O process */

            current_dev->info->cancel_io(current_dev, current_tag);

            /* As the current implemented devices scsi_disk and scsi_generic

               only support one LUN, we don't need to keep track of LUNs.

               Clearing I/O processes for other initiators could be possible

               for scsi_generic by sending a SG_SCSI_RESET to the /dev/sgX

               device, but this is currently not implemented (and seems not

               to be really necessary). So let's simply clear all queued

               commands for the current device: */

            id = current_tag & 0x0000ff00;

            QTAILQ_FOREACH_SAFE(p, &s->queue, next, p_next) {

                if ((p->tag & 0x0000ff00) == id) {

                    current_dev->info->cancel_io(current_dev, p->tag);

                    QTAILQ_REMOVE(&s->queue, p, next);

                }

            }

            lsi_disconnect(s);

            break;

        default:

            if ((msg & 0x80) == 0) {

                goto bad;

            }

            s->current_lun = msg & 7;

            DPRINTF("Select LUN %d\n", s->current_lun);

            lsi_set_phase(s, PHASE_CMD);

            break;

        }

    }

    return;

bad:

    BADF("Unimplemented message 0x%02x\n", msg);

    lsi_set_phase(s, PHASE_MI);

    lsi_add_msg_byte(s, 7); /* MESSAGE REJECT */

    s->msg_action = 0;

}


static void local_mapped_file_attr(FsContext *ctx, const char *path,

                                   struct stat *stbuf)

{

    FILE *fp;

    char buf[ATTR_MAX];

    char attr_path[PATH_MAX];

    local_mapped_attr_path(ctx, path, attr_path);

    fp = local_fopen(attr_path, "r");

    if (!fp) {

        return;

    }

    memset(buf, 0, ATTR_MAX);

    while (fgets(buf, ATTR_MAX, fp)) {

        if (!strncmp(buf, "virtfs.uid", 10)) {

            stbuf->st_uid = atoi(buf+11);

        } else if (!strncmp(buf, "virtfs.gid", 10)) {

            stbuf->st_gid = atoi(buf+11);

        } else if (!strncmp(buf, "virtfs.mode", 11)) {

            stbuf->st_mode = atoi(buf+12);

        } else if (!strncmp(buf, "virtfs.rdev", 11)) {

            stbuf->st_rdev = atoi(buf+12);

        }

        memset(buf, 0, ATTR_MAX);

    }

    fclose(fp);

}


static int qemu_rbd_parsename(const char *filename,

                              char *pool, int pool_len,

                              char *snap, int snap_len,

                              char *name, int name_len,

                              char *conf, int conf_len,

                              Error **errp)

{

    const char *start;

    char *p, *buf;

    int ret = 0;

    char *found_str;

    Error *local_err = NULL;

    if (!strstart(filename, "rbd:", &start)) {

        error_setg(errp, "File name must start with 'rbd:'");

        return -EINVAL;

    }

    buf = g_strdup(start);

    p = buf;

    *snap = '\0';

    *conf = '\0';

    found_str = qemu_rbd_next_tok(pool_len, p,

                                  '/', "pool name", &p, &local_err);

    if (local_err) {

        goto done;

    }

    if (!p) {

        ret = -EINVAL;

        error_setg(errp, "Pool name is required");

        goto done;

    }

    qemu_rbd_unescape(found_str);

    g_strlcpy(pool, found_str, pool_len);

    if (strchr(p, '@')) {

        found_str = qemu_rbd_next_tok(name_len, p,

                                      '@', "object name", &p, &local_err);

        if (local_err) {

            goto done;

        }

        qemu_rbd_unescape(found_str);

        g_strlcpy(name, found_str, name_len);

        found_str = qemu_rbd_next_tok(snap_len, p,

                                      ':', "snap name", &p, &local_err);

        if (local_err) {

            goto done;

        }

        qemu_rbd_unescape(found_str);

        g_strlcpy(snap, found_str, snap_len);

    } else {

        found_str = qemu_rbd_next_tok(name_len, p,

                                      ':', "object name", &p, &local_err);

        if (local_err) {

            goto done;

        }

        qemu_rbd_unescape(found_str);

        g_strlcpy(name, found_str, name_len);

    }

    if (!p) {

        goto done;

    }

    found_str = qemu_rbd_next_tok(conf_len, p,

                                  '\0', "configuration", &p, &local_err);

    if (local_err) {

        goto done;

    }

    g_strlcpy(conf, found_str, conf_len);

done:

    if (local_err) {

        ret = -EINVAL;

        error_propagate(errp, local_err);

    }

    g_free(buf);

    return ret;

}


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

{

    MachineState *ms = MACHINE(qdev_get_machine());

    MachineClass *mc = MACHINE_GET_CLASS(ms);

    PCMachineState *pcms =

        PC_MACHINE(object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE));

    PCIBus *bus;

    IntelIOMMUState *s = INTEL_IOMMU_DEVICE(dev);

    X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(dev);

    if (!pcms) {

        error_setg(errp, "Machine-type '%s' not supported by intel-iommu",

                   mc->name);

        return;

    }

    bus = pcms->bus;

    x86_iommu->type = TYPE_INTEL;

    if (!vtd_decide_config(s, errp)) {

        return;

    }

    QLIST_INIT(&s->notifiers_list);

    memset(s->vtd_as_by_bus_num, 0, sizeof(s->vtd_as_by_bus_num));

    memory_region_init_io(&s->csrmem, OBJECT(s), &vtd_mem_ops, s,

                          "intel_iommu", DMAR_REG_SIZE);

    sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->csrmem);

    /* No corresponding destroy */

    s->iotlb = g_hash_table_new_full(vtd_uint64_hash, vtd_uint64_equal,

                                     g_free, g_free);

    s->vtd_as_by_busptr = g_hash_table_new_full(vtd_uint64_hash, vtd_uint64_equal,

                                              g_free, g_free);

    vtd_init(s);

    sysbus_mmio_map(SYS_BUS_DEVICE(s), 0, Q35_HOST_BRIDGE_IOMMU_ADDR);

    pci_setup_iommu(bus, vtd_host_dma_iommu, dev);

    /* Pseudo address space under root PCI bus. */

    pcms->ioapic_as = vtd_host_dma_iommu(bus, s, Q35_PSEUDO_DEVFN_IOAPIC);

}


void s390x_cpu_timer(void *opaque)

{

    S390CPU *cpu = opaque;

    CPUS390XState *env = &cpu->env;

    env->pending_int |= INTERRUPT_CPUTIMER;

    cpu_interrupt(CPU(cpu), CPU_INTERRUPT_HARD);

}


static int ahci_dma_prepare_buf(IDEDMA *dma, int is_write)

{

    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);

    IDEState *s = &ad->port.ifs[0];

    ahci_populate_sglist(ad, &s->sg, 0);

    s->io_buffer_size = s->sg.size;

    DPRINTF(ad->port_no, "len=%#x\n", s->io_buffer_size);

    return s->io_buffer_size != 0;

}


void tcp_start_incoming_migration(const char *host_port, Error **errp)

{

    Error *err = NULL;

    SocketAddressLegacy *saddr = tcp_build_address(host_port, &err);

    if (!err) {

        socket_start_incoming_migration(saddr, &err);

    }

    error_propagate(errp, err);

}


static void init_quantization(Jpeg2000EncoderContext *s)

{

    int compno, reslevelno, bandno;

    Jpeg2000QuantStyle  *qntsty = &s->qntsty;

    Jpeg2000CodingStyle *codsty = &s->codsty;

    for (compno = 0; compno < s->ncomponents; compno++){

        int gbandno = 0;

        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){

            int nbands, lev = codsty->nreslevels - reslevelno - 1;

            nbands = reslevelno ? 3 : 1;

            for (bandno = 0; bandno < nbands; bandno++, gbandno++){

                int expn, mant;

                if (codsty->transform == FF_DWT97){

                    int bandpos = bandno + (reslevelno>0),

                        ss = 81920000 / dwt_norms[0][bandpos][lev],

                        log = av_log2(ss);

                    mant = (11 - log < 0 ? ss >> log - 11 : ss << 11 - log) & 0x7ff;

                    expn = s->cbps[compno] - log + 13;

                } else

                    expn = ((bandno&2)>>1) + (reslevelno>0) + s->cbps[compno];

                qntsty->expn[gbandno] = expn;

                qntsty->mant[gbandno] = mant;

            }

        }

    }

}