void helper_store_fpcr (uint64_t val)

{

#ifdef CONFIG_SOFTFLOAT

    set_float_exception_flags((val >> 52) & 0x3F, &FP_STATUS);

#endif

    switch ((val >> 58) & 3) {

    case 0:

        set_float_rounding_mode(float_round_to_zero, &FP_STATUS);

        break;

    case 1:

        set_float_rounding_mode(float_round_down, &FP_STATUS);

        break;

    case 2:

        set_float_rounding_mode(float_round_nearest_even, &FP_STATUS);

        break;

    case 3:

        set_float_rounding_mode(float_round_up, &FP_STATUS);

        break;

    }

}


void spapr_tce_set_bypass(sPAPRTCETable *tcet, bool bypass)

{

    tcet->bypass = bypass;

}


void qemu_system_wakeup_request(WakeupReason reason)

{

    if (!is_suspended) {

        return;

    }

    if (!(wakeup_reason_mask & (1 << reason))) {

        return;

    }

    runstate_set(RUN_STATE_RUNNING);

    monitor_protocol_event(QEVENT_WAKEUP, NULL);

    notifier_list_notify(&wakeup_notifiers, &reason);

    reset_requested = 1;

    qemu_notify_event();

    is_suspended = false;

}


static int rtsp_listen(AVFormatContext *s)

{

    RTSPState *rt = s->priv_data;

    char proto[128], host[128], path[512], auth[128];

    char uri[500];

    int port;

    int default_port = RTSP_DEFAULT_PORT;

    char tcpname[500];

    const char *lower_proto = "tcp";

    unsigned char rbuf[4096];

    unsigned char method[10];

    int rbuflen = 0;

    int ret;

    enum RTSPMethod methodcode;

    if (!rt->protocols) {

        rt->protocols = ffurl_get_protocols(NULL, NULL);

        if (!rt->protocols)

            return AVERROR(ENOMEM);

    }

    /* extract hostname and port */

    av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),

                 &port, path, sizeof(path), s->filename);

    /* ff_url_join. No authorization by now (NULL) */

    ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,

                port, "%s", path);

    if (!strcmp(proto, "rtsps")) {

        lower_proto  = "tls";

        default_port = RTSPS_DEFAULT_PORT;

    }

    if (port < 0)

        port = default_port;

    /* Create TCP connection */

    ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,

                "?listen&listen_timeout=%d", rt->initial_timeout * 1000);

    if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,

                         &s->interrupt_callback, NULL, rt->protocols)) {

        av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");

        return ret;

    }

    rt->state       = RTSP_STATE_IDLE;

    rt->rtsp_hd_out = rt->rtsp_hd;

    for (;;) { /* Wait for incoming RTSP messages */

        ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);

        if (ret < 0)

            return ret;

        ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,

                                 sizeof(method), &methodcode);

        if (ret) {

            av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");

            return ret;

        }

        if (methodcode == ANNOUNCE) {

            ret       = rtsp_read_announce(s);

            rt->state = RTSP_STATE_PAUSED;

        } else if (methodcode == OPTIONS) {

            ret = rtsp_read_options(s);

        } else if (methodcode == RECORD) {

            ret = rtsp_read_record(s);

            if (!ret)

                return 0; // We are ready for streaming

        } else if (methodcode == SETUP)

            ret = rtsp_read_setup(s, host, uri);

        if (ret) {

            ffurl_close(rt->rtsp_hd);

            return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


int ff_wma_run_level_decode(AVCodecContext *avctx, GetBitContext *gb,

                            VLC *vlc, const float *level_table,

                            const uint16_t *run_table, int version,

                            WMACoef *ptr, int offset, int num_coefs,

                            int block_len, int frame_len_bits,

                            int coef_nb_bits)

{

    int code, level, sign;

    const uint32_t *ilvl = (const uint32_t *) level_table;

    uint32_t *iptr = (uint32_t *) ptr;

    const unsigned int coef_mask = block_len - 1;

    for (; offset < num_coefs; offset++) {

        code = get_vlc2(gb, vlc->table, VLCBITS, VLCMAX);

        if (code > 1) {

            /** normal code */

            offset                  += run_table[code];

            sign                     = get_bits1(gb) - 1;

            iptr[offset & coef_mask] = ilvl[code] ^ sign << 31;

        } else if (code == 1) {

            /** EOB */

            break;

        } else {

            /** escape */

            if (!version) {

                level = get_bits(gb, coef_nb_bits);

                /** NOTE: this is rather suboptimal. reading

                 *  block_len_bits would be better */

                offset += get_bits(gb, frame_len_bits);

            } else {

                level = ff_wma_get_large_val(gb);

                /** escape decode */

                if (get_bits1(gb)) {

                    if (get_bits1(gb)) {

                        if (get_bits1(gb)) {

                            av_log(avctx, AV_LOG_ERROR,

                                   "broken escape sequence\n");

                            return -1;

                        } else

                            offset += get_bits(gb, frame_len_bits) + 4;

                    } else

                        offset += get_bits(gb, 2) + 1;

                }

            }

            sign                    = get_bits1(gb) - 1;

            ptr[offset & coef_mask] = (level ^ sign) - sign;

        }

    }

    /** NOTE: EOB can be omitted */

    if (offset > num_coefs) {

        av_log(avctx, AV_LOG_ERROR, "overflow in spectral RLE, ignoring\n");

        return -1;

    }

    return 0;

}


int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,

                         AVFilterInOut *open_inputs,

                         AVFilterInOut *open_outputs, AVClass *log_ctx)

{

    int index = 0, ret;

    char chr = 0;

    AVFilterInOut *curr_inputs = NULL;

    do {

        AVFilterContext *filter;

        filters += strspn(filters, WHITESPACES);

        if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx)) < 0)

            goto fail;

        if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)

            goto fail;

        if (filter->input_count == 1 && !curr_inputs && !index) {

            /* First input can be omitted if it is "[in]" */

            const char *tmp = "[in]";

            if ((ret = parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx)) < 0)

                goto fail;

        }

        if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx)) < 0)

            goto fail;

        if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,

                                 log_ctx)) < 0)

            goto fail;

        filters += strspn(filters, WHITESPACES);

        chr = *filters++;

        if (chr == ';' && curr_inputs) {

            av_log(log_ctx, AV_LOG_ERROR,

                   "Could not find a output to link when parsing \"%s\"\n",

                   filters - 1);

            ret = AVERROR(EINVAL);

            goto fail;

        }

        index++;

    } while (chr == ',' || chr == ';');

    if (chr) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Unable to parse graph description substring: \"%s\"\n",

               filters - 1);

        ret = AVERROR(EINVAL);

        goto fail;

    }

    if (open_inputs && !strcmp(open_inputs->name, "out") && curr_inputs) {

        /* Last output can be omitted if it is "[out]" */

        const char *tmp = "[out]";

        if ((ret = parse_outputs(&tmp, &curr_inputs, &open_inputs, &open_outputs,

                                 log_ctx)) < 0)

            goto fail;

    }

    return 0;

 fail:

    avfilter_graph_free(graph);

    free_inout(open_inputs);

    free_inout(open_outputs);

    free_inout(curr_inputs);

    return ret;

}


static int virtio_net_device_exit(DeviceState *qdev)

{

    VirtIONet *n = VIRTIO_NET(qdev);

    VirtIODevice *vdev = VIRTIO_DEVICE(qdev);

    int i;

    /* This will stop vhost backend if appropriate. */

    virtio_net_set_status(vdev, 0);

    unregister_savevm(qdev, "virtio-net", n);

    if (n->netclient_name) {

        g_free(n->netclient_name);

        n->netclient_name = NULL;

    }

    if (n->netclient_type) {

        g_free(n->netclient_type);

        n->netclient_type = NULL;

    }

    g_free(n->mac_table.macs);

    g_free(n->vlans);

    for (i = 0; i < n->max_queues; i++) {

        VirtIONetQueue *q = &n->vqs[i];

        NetClientState *nc = qemu_get_subqueue(n->nic, i);

        qemu_purge_queued_packets(nc);

        if (q->tx_timer) {

            timer_del(q->tx_timer);

            timer_free(q->tx_timer);

        } else {

            qemu_bh_delete(q->tx_bh);

        }

    }

    g_free(n->vqs);

    qemu_del_nic(n->nic);

    virtio_cleanup(vdev);

    return 0;

}


static inline void gen_neon_widen(TCGv dest, TCGv src, int size, int u)

{

    if (u) {

        switch (size) {

        case 0: gen_helper_neon_widen_u8(dest, src); break;

        case 1: gen_helper_neon_widen_u16(dest, src); break;

        case 2: tcg_gen_extu_i32_i64(dest, src); break;

        default: abort();

        }

    } else {

        switch (size) {

        case 0: gen_helper_neon_widen_s8(dest, src); break;

        case 1: gen_helper_neon_widen_s16(dest, src); break;

        case 2: tcg_gen_ext_i32_i64(dest, src); break;

        default: abort();

        }

    }

    dead_tmp(src);

}


static int sd_create_branch(BDRVSheepdogState *s)

{

    int ret, fd;

    uint32_t vid;

    char *buf;

    dprintf("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);

    buf = g_malloc(SD_INODE_SIZE);

    ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &vid, 1,

                       s->addr, s->port);

    if (ret) {

        goto out;

    }

    dprintf("%" PRIx32 " is created.\n", vid);

    fd = connect_to_sdog(s->addr, s->port);

    if (fd < 0) {

        error_report("failed to connect");

        ret = fd;

        goto out;

    }

    ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,

                      SD_INODE_SIZE, 0, s->cache_enabled);

    closesocket(fd);

    if (ret < 0) {

        goto out;

    }

    memcpy(&s->inode, buf, sizeof(s->inode));

    s->is_snapshot = false;

    ret = 0;

    dprintf("%" PRIx32 " was newly created.\n", s->inode.vdi_id);

out:

    g_free(buf);

    return ret;

}


static int parse_uint8(DeviceState *dev, Property *prop, const char *str)

{

    uint8_t *ptr = qdev_get_prop_ptr(dev, prop);

    const char *fmt;

    /* accept both hex and decimal */

    fmt = strncasecmp(str, "0x",2) == 0 ? "%" PRIx8 : "%" PRIu8;

    if (sscanf(str, fmt, ptr) != 1)

        return -EINVAL;

    return 0;

}


av_cold int swri_rematrix_init(SwrContext *s){

    int i, j;

    int nb_in  = av_get_channel_layout_nb_channels(s->in_ch_layout);

    int nb_out = av_get_channel_layout_nb_channels(s->out_ch_layout);

    s->mix_any_f = NULL;

    if (!s->rematrix_custom) {

        int r = auto_matrix(s);

        if (r)

            return r;

    }

    if (s->midbuf.fmt == AV_SAMPLE_FMT_S16P){

        s->native_matrix = av_calloc(nb_in * nb_out, sizeof(int));

        s->native_one    = av_mallocz(sizeof(int));

        if (!s->native_matrix || !s->native_one)

            return AVERROR(ENOMEM);

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

            double rem = 0;

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

                double target = s->matrix[i][j] * 32768 + rem;

                ((int*)s->native_matrix)[i * nb_in + j] = lrintf(target);

                rem += target - ((int*)s->native_matrix)[i * nb_in + j];

            }

        }

        *((int*)s->native_one) = 32768;

        s->mix_1_1_f = (mix_1_1_func_type*)copy_s16;

        s->mix_2_1_f = (mix_2_1_func_type*)sum2_s16;

        s->mix_any_f = (mix_any_func_type*)get_mix_any_func_s16(s);

    }else if(s->midbuf.fmt == AV_SAMPLE_FMT_FLTP){

        s->native_matrix = av_calloc(nb_in * nb_out, sizeof(float));

        s->native_one    = av_mallocz(sizeof(float));

        if (!s->native_matrix || !s->native_one)

            return AVERROR(ENOMEM);

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

            for (j = 0; j < nb_in; j++)

                ((float*)s->native_matrix)[i * nb_in + j] = s->matrix[i][j];

        *((float*)s->native_one) = 1.0;

        s->mix_1_1_f = (mix_1_1_func_type*)copy_float;

        s->mix_2_1_f = (mix_2_1_func_type*)sum2_float;

        s->mix_any_f = (mix_any_func_type*)get_mix_any_func_float(s);

    }else if(s->midbuf.fmt == AV_SAMPLE_FMT_DBLP){

        s->native_matrix = av_calloc(nb_in * nb_out, sizeof(double));

        s->native_one    = av_mallocz(sizeof(double));

        if (!s->native_matrix || !s->native_one)

            return AVERROR(ENOMEM);

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

            for (j = 0; j < nb_in; j++)

                ((double*)s->native_matrix)[i * nb_in + j] = s->matrix[i][j];

        *((double*)s->native_one) = 1.0;

        s->mix_1_1_f = (mix_1_1_func_type*)copy_double;

        s->mix_2_1_f = (mix_2_1_func_type*)sum2_double;

        s->mix_any_f = (mix_any_func_type*)get_mix_any_func_double(s);

    }else if(s->midbuf.fmt == AV_SAMPLE_FMT_S32P){

        // Only for dithering currently

//         s->native_matrix = av_calloc(nb_in * nb_out, sizeof(double));

        s->native_one    = av_mallocz(sizeof(int));

        if (!s->native_one)

            return AVERROR(ENOMEM);

//         for (i = 0; i < nb_out; i++)

//             for (j = 0; j < nb_in; j++)

//                 ((double*)s->native_matrix)[i * nb_in + j] = s->matrix[i][j];

        *((int*)s->native_one) = 32768;

        s->mix_1_1_f = (mix_1_1_func_type*)copy_s32;

        s->mix_2_1_f = (mix_2_1_func_type*)sum2_s32;

        s->mix_any_f = (mix_any_func_type*)get_mix_any_func_s32(s);

    }else

        av_assert0(0);

    //FIXME quantize for integeres

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

        int ch_in=0;

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

            s->matrix32[i][j]= lrintf(s->matrix[i][j] * 32768);

            if(s->matrix[i][j])

                s->matrix_ch[i][++ch_in]= j;

        }

        s->matrix_ch[i][0]= ch_in;

    }

    if(HAVE_YASM && HAVE_MMX)

        return swri_rematrix_init_x86(s);

    return 0;

}


void s390_machine_reset(void)

{

    S390CPU *ipl_cpu = S390_CPU(qemu_get_cpu(0));

    qemu_devices_reset();

    s390_cmma_reset();

    s390_crypto_reset();

    /* all cpus are stopped - configure and start the ipl cpu only */

    s390_ipl_prepare_cpu(ipl_cpu);

    s390_cpu_set_state(CPU_STATE_OPERATING, ipl_cpu);

}


static int fic_decode_block(FICContext *ctx, GetBitContext *gb,

                            uint8_t *dst, int stride, int16_t *block)

{

    int i, num_coeff;

    /* Is it a skip block? */

    if (get_bits1(gb)) {

        /* This is a P-frame. */

        ctx->frame->key_frame = 0;

        ctx->frame->pict_type = AV_PICTURE_TYPE_P;

        return 0;

    }

    memset(block, 0, sizeof(*block) * 64);

    num_coeff = get_bits(gb, 7);

    if (num_coeff > 64)

        return AVERROR_INVALIDDATA;

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

        block[ff_zigzag_direct[i]] = get_se_golomb(gb) *

                                     ctx->qmat[ff_zigzag_direct[i]];

    fic_idct_put(dst, stride, block);

    return 0;

}


void ff_rtsp_undo_setup(AVFormatContext *s, int send_packets)

{

    RTSPState *rt = s->priv_data;

    int i;

    for (i = 0; i < rt->nb_rtsp_streams; i++) {

        RTSPStream *rtsp_st = rt->rtsp_streams[i];

        if (!rtsp_st)

            continue;

        if (rtsp_st->transport_priv) {

            if (s->oformat) {

                AVFormatContext *rtpctx = rtsp_st->transport_priv;

                av_write_trailer(rtpctx);

                if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {

                    uint8_t *ptr;

                    if (CONFIG_RTSP_MUXER && rtpctx->pb && send_packets)

                        ff_rtsp_tcp_write_packet(s, rtsp_st);

                    avio_close_dyn_buf(rtpctx->pb, &ptr);

                    av_free(ptr);

                } else {

                    avio_close(rtpctx->pb);

                }

                avformat_free_context(rtpctx);

            } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)

                ff_rdt_parse_close(rtsp_st->transport_priv);

            else if (rt->transport == RTSP_TRANSPORT_RTP && CONFIG_RTPDEC)

                ff_rtp_parse_close(rtsp_st->transport_priv);

        }

        rtsp_st->transport_priv = NULL;

        if (rtsp_st->rtp_handle)

            ffurl_close(rtsp_st->rtp_handle);

        rtsp_st->rtp_handle = NULL;

    }

}


static void do_token_in(USBDevice *s, USBPacket *p)

{

    int request, value, index;

    assert(p->ep->nr == 0);

    request = (s->setup_buf[0] << 8) | s->setup_buf[1];

    value   = (s->setup_buf[3] << 8) | s->setup_buf[2];

    index   = (s->setup_buf[5] << 8) | s->setup_buf[4];

    switch(s->setup_state) {

    case SETUP_STATE_ACK:

        if (!(s->setup_buf[0] & USB_DIR_IN)) {

            usb_device_handle_control(s, p, request, value, index,

                                      s->setup_len, s->data_buf);

            if (p->status == USB_RET_ASYNC) {

                return;

            }

            s->setup_state = SETUP_STATE_IDLE;

            p->actual_length = 0;

        }

        break;

    case SETUP_STATE_DATA:

        if (s->setup_buf[0] & USB_DIR_IN) {

            int len = s->setup_len - s->setup_index;

            if (len > p->iov.size) {

                len = p->iov.size;

            }

            usb_packet_copy(p, s->data_buf + s->setup_index, len);

            s->setup_index += len;

            if (s->setup_index >= s->setup_len) {

                s->setup_state = SETUP_STATE_ACK;

            }

            return;

        }

        s->setup_state = SETUP_STATE_IDLE;

        p->status = USB_RET_STALL;

        break;

    default:

        p->status = USB_RET_STALL;

    }

}


static int get_video_buffer(AVFrame *frame, int align)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);

    int ret, i;

    if (!desc)

        return AVERROR(EINVAL);

    if ((ret = av_image_check_size(frame->width, frame->height, 0, NULL)) < 0)

        return ret;

    if (!frame->linesize[0]) {

        ret = av_image_fill_linesizes(frame->linesize, frame->format,

                                      frame->width);

        if (ret < 0)

            return ret;

        for (i = 0; i < 4 && frame->linesize[i]; i++)

            frame->linesize[i] = FFALIGN(frame->linesize[i], align);

    }

    for (i = 0; i < 4 && frame->linesize[i]; i++) {

        int h = FFALIGN(frame->height, 32);

        if (i == 1 || i == 2)

            h = -((-h) >> desc->log2_chroma_h);

        frame->buf[i] = av_buffer_alloc(frame->linesize[i] * h);

        if (!frame->buf[i])

            goto fail;

        frame->data[i] = frame->buf[i]->data;

    }

    if (desc->flags & PIX_FMT_PAL || desc->flags & PIX_FMT_PSEUDOPAL) {

        av_buffer_unref(&frame->buf[1]);

        frame->buf[1] = av_buffer_alloc(1024);

        if (!frame->buf[1])

            goto fail;

        frame->data[1] = frame->buf[1]->data;

    }

    frame->extended_data = frame->data;

    return 0;

fail:

    av_frame_unref(frame);

    return AVERROR(ENOMEM);

}


static int kvm_get_msrs(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;

    int ret, i;

    uint64_t mtrr_top_bits;

    kvm_msr_buf_reset(cpu);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);

    kvm_msr_entry_add(cpu, MSR_PAT, 0);

    if (has_msr_star) {

        kvm_msr_entry_add(cpu, MSR_STAR, 0);

    }

    if (has_msr_hsave_pa) {

        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);

    }

    if (has_msr_tsc_aux) {

        kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);

    }

    if (has_msr_tsc_adjust) {

        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);

    }

    if (has_msr_tsc_deadline) {

        kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);

    }

    if (has_msr_misc_enable) {

        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);

    }

    if (has_msr_smbase) {

        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);

    }

    if (has_msr_feature_control) {

        kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);

    }

    if (has_msr_bndcfgs) {

        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);

    }

    if (has_msr_xss) {

        kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);

    }

    if (!env->tsc_valid) {

        kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);

        env->tsc_valid = !runstate_is_running();

    }

#ifdef TARGET_X86_64

    if (lm_capable_kernel) {

        kvm_msr_entry_add(cpu, MSR_CSTAR, 0);

        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);

        kvm_msr_entry_add(cpu, MSR_FMASK, 0);

        kvm_msr_entry_add(cpu, MSR_LSTAR, 0);

    }

#endif

    kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);

    kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);

    if (has_msr_async_pf_en) {

        kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);

    }

    if (has_msr_pv_eoi_en) {

        kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);

    }

    if (has_msr_kvm_steal_time) {

        kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);

    }

    if (has_msr_architectural_pmu) {

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);

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

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);

        }

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

            kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);

            kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);

        }

    }

    if (env->mcg_cap) {

        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);

        kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);

        if (has_msr_mcg_ext_ctl) {

            kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);

        }

        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {

            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);

        }

    }

    if (has_msr_hv_hypercall) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);

        kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);

    }

    if (has_msr_hv_vapic) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);

    }

    if (has_msr_hv_tsc) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);

    }

    if (has_msr_hv_crash) {

        int j;

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

            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);

        }

    }

    if (has_msr_hv_runtime) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);

    }

    if (cpu->hyperv_synic) {

        uint32_t msr;

        kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);

        kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, 0);

        kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);

        kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);

        for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {

            kvm_msr_entry_add(cpu, msr, 0);

        }

    }

    if (has_msr_hv_stimer) {

        uint32_t msr;

        for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;

             msr++) {

            kvm_msr_entry_add(cpu, msr, 0);

        }

    }

    if (has_msr_mtrr) {

        kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);

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

            kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);

            kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);

        }

    }

    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);

    if (ret < 0) {

        return ret;

    }

    assert(ret == cpu->kvm_msr_buf->nmsrs);

    /*

     * MTRR masks: Each mask consists of 5 parts

     * a  10..0: must be zero

     * b  11   : valid bit

     * c n-1.12: actual mask bits

     * d  51..n: reserved must be zero

     * e  63.52: reserved must be zero

     *

     * 'n' is the number of physical bits supported by the CPU and is

     * apparently always <= 52.   We know our 'n' but don't know what

     * the destinations 'n' is; it might be smaller, in which case

     * it masks (c) on loading. It might be larger, in which case

     * we fill 'd' so that d..c is consistent irrespetive of the 'n'

     * we're migrating to.

     */

    if (cpu->fill_mtrr_mask) {

        QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);

        assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);

        mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);

    } else {

        mtrr_top_bits = 0;

    }

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

        uint32_t index = msrs[i].index;

        switch (index) {

        case MSR_IA32_SYSENTER_CS:

            env->sysenter_cs = msrs[i].data;

            break;

        case MSR_IA32_SYSENTER_ESP:

            env->sysenter_esp = msrs[i].data;

            break;

        case MSR_IA32_SYSENTER_EIP:

            env->sysenter_eip = msrs[i].data;

            break;

        case MSR_PAT:

            env->pat = msrs[i].data;

            break;

        case MSR_STAR:

            env->star = msrs[i].data;

            break;

#ifdef TARGET_X86_64

        case MSR_CSTAR:

            env->cstar = msrs[i].data;

            break;

        case MSR_KERNELGSBASE:

            env->kernelgsbase = msrs[i].data;

            break;

        case MSR_FMASK:

            env->fmask = msrs[i].data;

            break;

        case MSR_LSTAR:

            env->lstar = msrs[i].data;

            break;

#endif

        case MSR_IA32_TSC:

            env->tsc = msrs[i].data;

            break;

        case MSR_TSC_AUX:

            env->tsc_aux = msrs[i].data;

            break;

        case MSR_TSC_ADJUST:

            env->tsc_adjust = msrs[i].data;

            break;

        case MSR_IA32_TSCDEADLINE:

            env->tsc_deadline = msrs[i].data;

            break;

        case MSR_VM_HSAVE_PA:

            env->vm_hsave = msrs[i].data;

            break;

        case MSR_KVM_SYSTEM_TIME:

            env->system_time_msr = msrs[i].data;

            break;

        case MSR_KVM_WALL_CLOCK:

            env->wall_clock_msr = msrs[i].data;

            break;

        case MSR_MCG_STATUS:

            env->mcg_status = msrs[i].data;

            break;

        case MSR_MCG_CTL:

            env->mcg_ctl = msrs[i].data;

            break;

        case MSR_MCG_EXT_CTL:

            env->mcg_ext_ctl = msrs[i].data;

            break;

        case MSR_IA32_MISC_ENABLE:

            env->msr_ia32_misc_enable = msrs[i].data;

            break;

        case MSR_IA32_SMBASE:

            env->smbase = msrs[i].data;

            break;

        case MSR_IA32_FEATURE_CONTROL:

            env->msr_ia32_feature_control = msrs[i].data;

            break;

        case MSR_IA32_BNDCFGS:

            env->msr_bndcfgs = msrs[i].data;

            break;

        case MSR_IA32_XSS:

            env->xss = msrs[i].data;

            break;

        default:

            if (msrs[i].index >= MSR_MC0_CTL &&

                msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {

                env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;

            }

            break;

        case MSR_KVM_ASYNC_PF_EN:

            env->async_pf_en_msr = msrs[i].data;

            break;

        case MSR_KVM_PV_EOI_EN:

            env->pv_eoi_en_msr = msrs[i].data;

            break;

        case MSR_KVM_STEAL_TIME:

            env->steal_time_msr = msrs[i].data;

            break;

        case MSR_CORE_PERF_FIXED_CTR_CTRL:

            env->msr_fixed_ctr_ctrl = msrs[i].data;

            break;

        case MSR_CORE_PERF_GLOBAL_CTRL:

            env->msr_global_ctrl = msrs[i].data;

            break;

        case MSR_CORE_PERF_GLOBAL_STATUS:

            env->msr_global_status = msrs[i].data;

            break;

        case MSR_CORE_PERF_GLOBAL_OVF_CTRL:

            env->msr_global_ovf_ctrl = msrs[i].data;

            break;

        case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:

            env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;

            break;

        case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:

            env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;

            break;

        case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:

            env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;

            break;

        case HV_X64_MSR_HYPERCALL:

            env->msr_hv_hypercall = msrs[i].data;

            break;

        case HV_X64_MSR_GUEST_OS_ID:

            env->msr_hv_guest_os_id = msrs[i].data;

            break;

        case HV_X64_MSR_APIC_ASSIST_PAGE:

            env->msr_hv_vapic = msrs[i].data;

            break;

        case HV_X64_MSR_REFERENCE_TSC:

            env->msr_hv_tsc = msrs[i].data;

            break;

        case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:

            env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;

            break;

        case HV_X64_MSR_VP_RUNTIME:

            env->msr_hv_runtime = msrs[i].data;

            break;

        case HV_X64_MSR_SCONTROL:

            env->msr_hv_synic_control = msrs[i].data;

            break;

        case HV_X64_MSR_SVERSION:

            env->msr_hv_synic_version = msrs[i].data;

            break;

        case HV_X64_MSR_SIEFP:

            env->msr_hv_synic_evt_page = msrs[i].data;

            break;

        case HV_X64_MSR_SIMP:

            env->msr_hv_synic_msg_page = msrs[i].data;

            break;

        case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:

            env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;

            break;

        case HV_X64_MSR_STIMER0_CONFIG:

        case HV_X64_MSR_STIMER1_CONFIG:

        case HV_X64_MSR_STIMER2_CONFIG:

        case HV_X64_MSR_STIMER3_CONFIG:

            env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =

                                msrs[i].data;

            break;

        case HV_X64_MSR_STIMER0_COUNT:

        case HV_X64_MSR_STIMER1_COUNT:

        case HV_X64_MSR_STIMER2_COUNT:

        case HV_X64_MSR_STIMER3_COUNT:

            env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =

                                msrs[i].data;

            break;

        case MSR_MTRRdefType:

            env->mtrr_deftype = msrs[i].data;

            break;

        case MSR_MTRRfix64K_00000:

            env->mtrr_fixed[0] = msrs[i].data;

            break;

        case MSR_MTRRfix16K_80000:

            env->mtrr_fixed[1] = msrs[i].data;

            break;

        case MSR_MTRRfix16K_A0000:

            env->mtrr_fixed[2] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_C0000:

            env->mtrr_fixed[3] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_C8000:

            env->mtrr_fixed[4] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_D0000:

            env->mtrr_fixed[5] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_D8000:

            env->mtrr_fixed[6] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_E0000:

            env->mtrr_fixed[7] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_E8000:

            env->mtrr_fixed[8] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_F0000:

            env->mtrr_fixed[9] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_F8000:

            env->mtrr_fixed[10] = msrs[i].data;

            break;

        case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):

            if (index & 1) {

                env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |

                                                               mtrr_top_bits;

            } else {

                env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;

            }

            break;

        }

    }

    return 0;

}


host_memory_backend_can_be_deleted(UserCreatable *uc, Error **errp)

{

    MemoryRegion *mr;

    mr = host_memory_backend_get_memory(MEMORY_BACKEND(uc), errp);

    if (memory_region_is_mapped(mr)) {

        return false;

    } else {

        return true;

    }

}


av_cold int ffv1_init_slice_contexts(FFV1Context *f)

{

    int i;

    f->slice_count = f->num_h_slices * f->num_v_slices;

    if (f->slice_count <= 0) {

        av_log(f->avctx, AV_LOG_ERROR, "Invalid number of slices\n");

        return AVERROR(EINVAL);

    }

    for (i = 0; i < f->slice_count; i++) {

        FFV1Context *fs = av_mallocz(sizeof(*fs));

        int sx          = i % f->num_h_slices;

        int sy          = i / f->num_h_slices;

        int sxs         = f->avctx->width  *  sx      / f->num_h_slices;

        int sxe         = f->avctx->width  * (sx + 1) / f->num_h_slices;

        int sys         = f->avctx->height *  sy      / f->num_v_slices;

        int sye         = f->avctx->height * (sy + 1) / f->num_v_slices;

        f->slice_context[i] = fs;

        memcpy(fs, f, sizeof(*fs));

        memset(fs->rc_stat2, 0, sizeof(fs->rc_stat2));

        fs->slice_width  = sxe - sxs;

        fs->slice_height = sye - sys;

        fs->slice_x      = sxs;

        fs->slice_y      = sys;

        fs->sample_buffer = av_malloc(3 * MAX_PLANES * (fs->width + 6) *

                                      sizeof(*fs->sample_buffer));

        if (!fs->sample_buffer)

            return AVERROR(ENOMEM);

    }

    return 0;

}


static void omap_pwt_write(void *opaque, target_phys_addr_t addr,

                           uint64_t value, unsigned size)

{

    struct omap_pwt_s *s = (struct omap_pwt_s *) opaque;

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (size != 1) {

        return omap_badwidth_write8(opaque, addr, value);

    }

    switch (offset) {

    case 0x00:	/* FRC */

        s->frc = value & 0x3f;

        break;

    case 0x04:	/* VRC */

        if ((value ^ s->vrc) & 1) {

            if (value & 1)

                printf("%s: %iHz buzz on\n", __FUNCTION__, (int)

                                /* 1.5 MHz from a 12-MHz or 13-MHz PWT_CLK */

                                ((omap_clk_getrate(s->clk) >> 3) /

                                 /* Pre-multiplexer divider */

                                 ((s->gcr & 2) ? 1 : 154) /

                                 /* Octave multiplexer */

                                 (2 << (value & 3)) *

                                 /* 101/107 divider */

                                 ((value & (1 << 2)) ? 101 : 107) *

                                 /*  49/55 divider */

                                 ((value & (1 << 3)) ?  49 : 55) *

                                 /*  50/63 divider */

                                 ((value & (1 << 4)) ?  50 : 63) *

                                 /*  80/127 divider */

                                 ((value & (1 << 5)) ?  80 : 127) /

                                 (107 * 55 * 63 * 127)));

            else

                printf("%s: silence!\n", __FUNCTION__);

        }

        s->vrc = value & 0x7f;

        break;

    case 0x08:	/* GCR */

        s->gcr = value & 3;

        break;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


static void predictor_decode_mono(APEContext *ctx, int count)

{

    APEPredictor *p = &ctx->predictor;

    int32_t *decoded0 = ctx->decoded[0];

    int32_t predictionA, currentA, A, sign;

    currentA = p->lastA[0];

    while (count--) {

        A = *decoded0;

        p->buf[YDELAYA] = currentA;

        p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];

        predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +

                      p->buf[YDELAYA - 1] * p->coeffsA[0][1] +

                      p->buf[YDELAYA - 2] * p->coeffsA[0][2] +

                      p->buf[YDELAYA - 3] * p->coeffsA[0][3];

        currentA = A + (predictionA >> 10);

        p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);

        p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);

        sign = APESIGN(A);

        p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;

        p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;

        p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;

        p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;

        p->buf++;

        /* Have we filled the history buffer? */

        if (p->buf == p->historybuffer + HISTORY_SIZE) {

            memmove(p->historybuffer, p->buf,

                    PREDICTOR_SIZE * sizeof(*p->historybuffer));

            p->buf = p->historybuffer;

        }

        p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);

        *(decoded0++) = p->filterA[0];

    }

    p->lastA[0] = currentA;

}


static void print_report(AVFormatContext **output_files,

                         AVOutputStream **ost_table, int nb_ostreams,

                         int is_last_report)

{

    char buf[1024];

    AVOutputStream *ost;

    AVFormatContext *oc;

    int64_t total_size;

    AVCodecContext *enc;

    int frame_number, vid, i;

    double bitrate, ti1, pts;

    static int64_t last_time = -1;

    static int qp_histogram[52];

    if (!is_last_report) {

        int64_t cur_time;

        /* display the report every 0.5 seconds */

        cur_time = av_gettime();

        if (last_time == -1) {

            last_time = cur_time;

            return;

        }

        if ((cur_time - last_time) < 500000)

            return;

        last_time = cur_time;

    }

    oc = output_files[0];

    total_size = avio_size(oc->pb);

    if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too

        total_size= avio_tell(oc->pb);

    buf[0] = '\0';

    ti1 = 1e10;

    vid = 0;

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

        float q= -1;

        ost = ost_table[i];

        enc = ost->st->codec;

        if(!ost->st->stream_copy && enc->coded_frame)

            q= enc->coded_frame->quality/(float)FF_QP2LAMBDA;

        if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {

            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);

        }

        if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {

            float t = (av_gettime()-timer_start) / 1000000.0;

            frame_number = ost->frame_number;

            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",

                     frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);

            if(is_last_report)

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");

            if(qp_hist){

                int j;

                int qp= lrintf(q);

                if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))

                    qp_histogram[qp]++;

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

                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));

            }

            if (enc->flags&CODEC_FLAG_PSNR){

                int j;

                double error, error_sum=0;

                double scale, scale_sum=0;

                char type[3]= {'Y','U','V'};

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");

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

                    if(is_last_report){

                        error= enc->error[j];

                        scale= enc->width*enc->height*255.0*255.0*frame_number;

                    }else{

                        error= enc->coded_frame->error[j];

                        scale= enc->width*enc->height*255.0*255.0;

                    }

                    if(j) scale/=4;

                    error_sum += error;

                    scale_sum += scale;

                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));

                }

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));

            }

            vid = 1;

        }

        /* compute min output value */

        pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);

        if ((pts < ti1) && (pts > 0))

            ti1 = pts;

    }

    if (ti1 < 0.01)

        ti1 = 0.01;

    if (verbose || is_last_report) {

        bitrate = (double)(total_size * 8) / ti1 / 1000.0;

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),

            "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",

            (double)total_size / 1024, ti1, bitrate);

        if (nb_frames_dup || nb_frames_drop)

          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",

                  nb_frames_dup, nb_frames_drop);

        if (verbose >= 0)

            fprintf(stderr, "%s    \r", buf);

        fflush(stderr);

    }

    if (is_last_report && verbose >= 0){

        int64_t raw= audio_size + video_size + extra_size;

        fprintf(stderr, "\n");

        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",

                video_size/1024.0,

                audio_size/1024.0,

                extra_size/1024.0,

                100.0*(total_size - raw)/raw

        );

    }

}


static av_always_inline void rv40_strong_loop_filter(uint8_t *src,

                                                     const int step,

                                                     const int stride,

                                                     const int alpha,

                                                     const int lims,

                                                     const int dmode,

                                                     const int chroma)

{

    int i;

    for(i = 0; i < 4; i++, src += stride){

        int sflag, p0, q0, p1, q1;

        int t = src[0*step] - src[-1*step];

        if (!t)

            continue;

        sflag = (alpha * FFABS(t)) >> 7;

        if (sflag > 1)

            continue;

        p0 = (25*src[-3*step] + 26*src[-2*step] + 26*src[-1*step] +

              26*src[ 0*step] + 25*src[ 1*step] +

              rv40_dither_l[dmode + i]) >> 7;

        q0 = (25*src[-2*step] + 26*src[-1*step] + 26*src[ 0*step] +

              26*src[ 1*step] + 25*src[ 2*step] +

              rv40_dither_r[dmode + i]) >> 7;

        if (sflag) {

            p0 = av_clip(p0, src[-1*step] - lims, src[-1*step] + lims);

            q0 = av_clip(q0, src[ 0*step] - lims, src[ 0*step] + lims);

        }

        p1 = (25*src[-4*step] + 26*src[-3*step] + 26*src[-2*step] + 26*p0 +

              25*src[ 0*step] + rv40_dither_l[dmode + i]) >> 7;

        q1 = (25*src[-1*step] + 26*q0 + 26*src[ 1*step] + 26*src[ 2*step] +

              25*src[ 3*step] + rv40_dither_r[dmode + i]) >> 7;

        if (sflag) {

            p1 = av_clip(p1, src[-2*step] - lims, src[-2*step] + lims);

            q1 = av_clip(q1, src[ 1*step] - lims, src[ 1*step] + lims);

        }

        src[-2*step] = p1;

        src[-1*step] = p0;

        src[ 0*step] = q0;

        src[ 1*step] = q1;

        if(!chroma){

            src[-3*step] = (25*src[-1*step] + 26*src[-2*step] +

                            51*src[-3*step] + 26*src[-4*step] + 64) >> 7;

            src[ 2*step] = (25*src[ 0*step] + 26*src[ 1*step] +

                            51*src[ 2*step] + 26*src[ 3*step] + 64) >> 7;

        }

    }

}


DeviceState *qdev_device_add(QemuOpts *opts, Error **errp)

{

    DeviceClass *dc;

    const char *driver, *path;

    DeviceState *dev;

    BusState *bus = NULL;

    Error *err = NULL;

    driver = qemu_opt_get(opts, "driver");

    if (!driver) {

        error_setg(errp, QERR_MISSING_PARAMETER, "driver");

        return NULL;

    }

    /* find driver */

    dc = qdev_get_device_class(&driver, errp);

    if (!dc) {

        return NULL;

    }

    /* find bus */

    path = qemu_opt_get(opts, "bus");

    if (path != NULL) {

        bus = qbus_find(path, errp);

        if (!bus) {

            return NULL;

        }

        if (!object_dynamic_cast(OBJECT(bus), dc->bus_type)) {

            error_setg(errp, "Device '%s' can't go on %s bus",

                       driver, object_get_typename(OBJECT(bus)));

            return NULL;

        }

    } else if (dc->bus_type != NULL) {

        bus = qbus_find_recursive(sysbus_get_default(), NULL, dc->bus_type);

        if (!bus || qbus_is_full(bus)) {

            error_setg(errp, "No '%s' bus found for device '%s'",

                       dc->bus_type, driver);

            return NULL;

        }

    }

    if (qdev_hotplug && bus && !qbus_is_hotpluggable(bus)) {

        error_setg(errp, QERR_BUS_NO_HOTPLUG, bus->name);

        return NULL;

    }

    if (!migration_is_idle()) {

        error_setg(errp, "device_add not allowed while migrating");

        return NULL;

    }

    /* create device */

    dev = DEVICE(object_new(driver));

    if (bus) {

        qdev_set_parent_bus(dev, bus);

    }

    qdev_set_id(dev, qemu_opts_id(opts));

    /* set properties */

    if (qemu_opt_foreach(opts, set_property, dev, &err)) {

    }

    dev->opts = opts;

    object_property_set_bool(OBJECT(dev), true, "realized", &err);

    if (err != NULL) {

        dev->opts = NULL;

    }

    return dev;

err_del_dev:

    error_propagate(errp, err);

    object_unparent(OBJECT(dev));

    object_unref(OBJECT(dev));

    return NULL;

}


static int rv10_decode_packet(AVCodecContext *avctx, const uint8_t *buf,

                              int buf_size, int buf_size2)

{

    RVDecContext *rv = avctx->priv_data;

    MpegEncContext *s = &rv->m;

    int mb_count, mb_pos, left, start_mb_x, active_bits_size, ret;

    active_bits_size = buf_size * 8;

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

    if (s->codec_id == AV_CODEC_ID_RV10)

        mb_count = rv10_decode_picture_header(s);

    else

        mb_count = rv20_decode_picture_header(rv);

    if (mb_count < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "HEADER ERROR\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->mb_x >= s->mb_width ||

        s->mb_y >= s->mb_height) {

        av_log(s->avctx, AV_LOG_ERROR, "POS ERROR %d %d\n", s->mb_x, s->mb_y);

        return AVERROR_INVALIDDATA;

    }

    mb_pos = s->mb_y * s->mb_width + s->mb_x;

    left   = s->mb_width * s->mb_height - mb_pos;

    if (mb_count > left) {

        av_log(s->avctx, AV_LOG_ERROR, "COUNT ERROR\n");

        return AVERROR_INVALIDDATA;

    }

    if ((s->mb_x == 0 && s->mb_y == 0) || s->current_picture_ptr == NULL) {

        // FIXME write parser so we always have complete frames?

        if (s->current_picture_ptr) {

            ff_er_frame_end(&s->er);

            ff_MPV_frame_end(s);

            s->mb_x = s->mb_y = s->resync_mb_x = s->resync_mb_y = 0;

        }

        if ((ret = ff_MPV_frame_start(s, avctx)) < 0)

            return ret;

        ff_mpeg_er_frame_start(s);

    } else {

        if (s->current_picture_ptr->f.pict_type != s->pict_type) {

            av_log(s->avctx, AV_LOG_ERROR, "Slice type mismatch\n");

            return AVERROR_INVALIDDATA;

        }

    }

    av_dlog(avctx, "qscale=%d\n", s->qscale);

    /* default quantization values */

    if (s->codec_id == AV_CODEC_ID_RV10) {

        if (s->mb_y == 0)

            s->first_slice_line = 1;

    } else {

        s->first_slice_line = 1;

        s->resync_mb_x      = s->mb_x;

    }

    start_mb_x     = s->mb_x;

    s->resync_mb_y = s->mb_y;

    if (s->h263_aic) {

        s->y_dc_scale_table =

        s->c_dc_scale_table = ff_aic_dc_scale_table;

    } else {

        s->y_dc_scale_table =

        s->c_dc_scale_table = ff_mpeg1_dc_scale_table;

    }

    if (s->modified_quant)

        s->chroma_qscale_table = ff_h263_chroma_qscale_table;

    ff_set_qscale(s, s->qscale);

    s->rv10_first_dc_coded[0] = 0;

    s->rv10_first_dc_coded[1] = 0;

    s->rv10_first_dc_coded[2] = 0;

    s->block_wrap[0] =

    s->block_wrap[1] =

    s->block_wrap[2] =

    s->block_wrap[3] = s->b8_stride;

    s->block_wrap[4] =

    s->block_wrap[5] = s->mb_stride;

    ff_init_block_index(s);

    /* decode each macroblock */

    for (s->mb_num_left = mb_count; s->mb_num_left > 0; s->mb_num_left--) {

        int ret;

        ff_update_block_index(s);

        av_dlog(avctx, "**mb x=%d y=%d\n", s->mb_x, s->mb_y);

        s->mv_dir  = MV_DIR_FORWARD;

        s->mv_type = MV_TYPE_16X16;

        ret = ff_h263_decode_mb(s, s->block);

        // Repeat the slice end check from ff_h263_decode_mb with our active

        // bitstream size

        if (ret != SLICE_ERROR) {

            int v = show_bits(&s->gb, 16);

            if (get_bits_count(&s->gb) + 16 > active_bits_size)

                v >>= get_bits_count(&s->gb) + 16 - active_bits_size;

            if (!v)

                ret = SLICE_END;

        }

        if (ret != SLICE_ERROR && active_bits_size < get_bits_count(&s->gb) &&

            8 * buf_size2 >= get_bits_count(&s->gb)) {

            active_bits_size = buf_size2 * 8;

            av_log(avctx, AV_LOG_DEBUG, "update size from %d to %d\n",

                   8 * buf_size, active_bits_size);

            ret = SLICE_OK;

        }

        if (ret == SLICE_ERROR || active_bits_size < get_bits_count(&s->gb)) {

            av_log(s->avctx, AV_LOG_ERROR, "ERROR at MB %d %d\n", s->mb_x,

                   s->mb_y);

            return AVERROR_INVALIDDATA;

        }

        if (s->pict_type != AV_PICTURE_TYPE_B)

            ff_h263_update_motion_val(s);

        ff_MPV_decode_mb(s, s->block);

        if (s->loop_filter)

            ff_h263_loop_filter(s);

        if (++s->mb_x == s->mb_width) {

            s->mb_x = 0;

            s->mb_y++;

            ff_init_block_index(s);

        }

        if (s->mb_x == s->resync_mb_x)

            s->first_slice_line = 0;

        if (ret == SLICE_END)

            break;

    }

    ff_er_add_slice(&s->er, start_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y,

                    ER_MB_END);

    return active_bits_size;

}


static inline int cpu_gdb_index(CPUState *cpu)

{

#if defined(CONFIG_USER_ONLY)

    return cpu->host_tid;

#else

    return cpu->cpu_index + 1;

#endif

}


void hmp_info_block_jobs(Monitor *mon, const QDict *qdict)
{
    BlockJobInfoList *list;
    Error *err = NULL;
    list = qmp_query_block_jobs(&err);
    assert(!err);
    if (!list) {
        monitor_printf(mon, "No active jobs\n");
        return;
    }
    while (list) {
        if (strcmp(list->value->type, "stream") == 0) {
            monitor_printf(mon, "Streaming device %s: Completed %" PRId64
                           " of %" PRId64 " bytes, speed limit %" PRId64
                           " bytes/s\n",
                           list->value->device,
                           list->value->offset,
                           list->value->len,
                           list->value->speed);
        } else {
            monitor_printf(mon, "Type %s, device %s: Completed %" PRId64
                           " of %" PRId64 " bytes, speed limit %" PRId64
                           " bytes/s\n",
                           list->value->type,
                           list->value->device,
                           list->value->offset,
                           list->value->len,
                           list->value->speed);
        }
        list = list->next;
    }
}


static int atrim_filter_frame(AVFilterLink *inlink, AVFrame *frame)

{

    AVFilterContext *ctx = inlink->dst;

    TrimContext       *s = ctx->priv;

    int64_t start_sample, end_sample = frame->nb_samples;

    int64_t pts;

    int drop;

    /* drop everything if EOF has already been returned */

    if (s->eof) {

        av_frame_free(&frame);

        return 0;

    }

    if (frame->pts != AV_NOPTS_VALUE)

        pts = av_rescale_q(frame->pts, inlink->time_base,

                           (AVRational){ 1, inlink->sample_rate });

    else

        pts = s->next_pts;

    s->next_pts = pts + frame->nb_samples;

    /* check if at least a part of the frame is after the start time */

    if (s->start_sample < 0 && s->start_pts == AV_NOPTS_VALUE) {

        start_sample = 0;

    } else {

        drop = 1;

        start_sample = frame->nb_samples;

        if (s->start_sample >= 0 &&

            s->nb_samples + frame->nb_samples > s->start_sample) {

            drop         = 0;

            start_sample = FFMIN(start_sample, s->start_sample - s->nb_samples);

        }

        if (s->start_pts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE &&

            pts + frame->nb_samples > s->start_pts) {

            drop = 0;

            start_sample = FFMIN(start_sample, s->start_pts - pts);

        }

        if (drop)

            goto drop;

    }

    if (s->first_pts == AV_NOPTS_VALUE)

        s->first_pts = pts + start_sample;

    /* check if at least a part of the frame is before the end time */

    if (s->end_sample == INT64_MAX && s->end_pts == AV_NOPTS_VALUE && !s->duration_tb) {

        end_sample = frame->nb_samples;

    } else {

        drop       = 1;

        end_sample = 0;

        if (s->end_sample != INT64_MAX &&

            s->nb_samples < s->end_sample) {

            drop       = 0;

            end_sample = FFMAX(end_sample, s->end_sample - s->nb_samples);

        }

        if (s->end_pts != AV_NOPTS_VALUE && pts != AV_NOPTS_VALUE &&

            pts < s->end_pts) {

            drop       = 0;

            end_sample = FFMAX(end_sample, s->end_pts - pts);

        }

        if (s->duration_tb && pts - s->first_pts < s->duration_tb) {

            drop       = 0;

            end_sample = FFMAX(end_sample, s->first_pts + s->duration_tb - pts);

        }

        if (drop) {

            s->eof = 1;

            goto drop;

        }

    }

    s->nb_samples += frame->nb_samples;

    start_sample   = FFMAX(0, start_sample);

    end_sample     = FFMIN(frame->nb_samples, end_sample);

    av_assert0(start_sample < end_sample);

    if (start_sample) {

        AVFrame *out = ff_get_audio_buffer(ctx->outputs[0], end_sample - start_sample);

        if (!out) {

            av_frame_free(&frame);

            return AVERROR(ENOMEM);

        }

        av_frame_copy_props(out, frame);

        av_samples_copy(out->extended_data, frame->extended_data, 0, start_sample,

                        out->nb_samples, av_get_channel_layout_nb_channels(frame->channel_layout),

                        frame->format);

        if (out->pts != AV_NOPTS_VALUE)

            out->pts += av_rescale_q(start_sample, (AVRational){ 1, out->sample_rate },

                                     inlink->time_base);

        av_frame_free(&frame);

        frame = out;

    } else

        frame->nb_samples = end_sample;

    s->got_output = 1;

    return ff_filter_frame(ctx->outputs[0], frame);

drop:

    s->nb_samples += frame->nb_samples;

    av_frame_free(&frame);

    return 0;

}


static void tcg_reg_alloc_call(TCGContext *s, int nb_oargs, int nb_iargs,

                               const TCGArg * const args, uint16_t dead_args,

                               uint8_t sync_args)

{

    int flags, nb_regs, i;

    TCGReg reg;

    TCGArg arg;

    TCGTemp *ts;

    intptr_t stack_offset;

    size_t call_stack_size;

    tcg_insn_unit *func_addr;

    int allocate_args;

    TCGRegSet allocated_regs;

    func_addr = (tcg_insn_unit *)(intptr_t)args[nb_oargs + nb_iargs];

    flags = args[nb_oargs + nb_iargs + 1];

    nb_regs = ARRAY_SIZE(tcg_target_call_iarg_regs);

    if (nb_regs > nb_iargs) {

        nb_regs = nb_iargs;

    }

    /* assign stack slots first */

    call_stack_size = (nb_iargs - nb_regs) * sizeof(tcg_target_long);

    call_stack_size = (call_stack_size + TCG_TARGET_STACK_ALIGN - 1) &

        ~(TCG_TARGET_STACK_ALIGN - 1);

    allocate_args = (call_stack_size > TCG_STATIC_CALL_ARGS_SIZE);

    if (allocate_args) {

        /* XXX: if more than TCG_STATIC_CALL_ARGS_SIZE is needed,

           preallocate call stack */

        tcg_abort();

    }

    stack_offset = TCG_TARGET_CALL_STACK_OFFSET;

    for(i = nb_regs; i < nb_iargs; i++) {

        arg = args[nb_oargs + i];

#ifdef TCG_TARGET_STACK_GROWSUP

        stack_offset -= sizeof(tcg_target_long);

#endif

        if (arg != TCG_CALL_DUMMY_ARG) {

            ts = &s->temps[arg];

            temp_load(s, ts, tcg_target_available_regs[ts->type],

                      s->reserved_regs);

            tcg_out_st(s, ts->type, ts->reg, TCG_REG_CALL_STACK, stack_offset);

        }

#ifndef TCG_TARGET_STACK_GROWSUP

        stack_offset += sizeof(tcg_target_long);

#endif

    }

    /* assign input registers */

    tcg_regset_set(allocated_regs, s->reserved_regs);

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

        arg = args[nb_oargs + i];

        if (arg != TCG_CALL_DUMMY_ARG) {

            ts = &s->temps[arg];

            reg = tcg_target_call_iarg_regs[i];

            tcg_reg_free(s, reg, allocated_regs);

            if (ts->val_type == TEMP_VAL_REG) {

                if (ts->reg != reg) {

                    tcg_out_mov(s, ts->type, reg, ts->reg);

                }

            } else {

                TCGRegSet arg_set;

                tcg_regset_clear(arg_set);

                tcg_regset_set_reg(arg_set, reg);

                temp_load(s, ts, arg_set, allocated_regs);

            }

            tcg_regset_set_reg(allocated_regs, reg);

        }

    }

    /* mark dead temporaries and free the associated registers */

    for(i = nb_oargs; i < nb_iargs + nb_oargs; i++) {

        if (IS_DEAD_ARG(i)) {

            temp_dead(s, &s->temps[args[i]]);

        }

    }

    /* clobber call registers */

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

        if (tcg_regset_test_reg(tcg_target_call_clobber_regs, i)) {

            tcg_reg_free(s, i, allocated_regs);

        }

    }

    /* Save globals if they might be written by the helper, sync them if

       they might be read. */

    if (flags & TCG_CALL_NO_READ_GLOBALS) {

        /* Nothing to do */

    } else if (flags & TCG_CALL_NO_WRITE_GLOBALS) {

        sync_globals(s, allocated_regs);

    } else {

        save_globals(s, allocated_regs);

    }

    tcg_out_call(s, func_addr);

    /* assign output registers and emit moves if needed */

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

        arg = args[i];

        ts = &s->temps[arg];

        reg = tcg_target_call_oarg_regs[i];

        assert(s->reg_to_temp[reg] == NULL);

        if (ts->fixed_reg) {

            if (ts->reg != reg) {

                tcg_out_mov(s, ts->type, ts->reg, reg);

            }

        } else {

            if (ts->val_type == TEMP_VAL_REG) {

                s->reg_to_temp[ts->reg] = NULL;

            }

            ts->val_type = TEMP_VAL_REG;

            ts->reg = reg;

            ts->mem_coherent = 0;

            s->reg_to_temp[reg] = ts;

            if (NEED_SYNC_ARG(i)) {

                tcg_reg_sync(s, reg, allocated_regs);

            }

            if (IS_DEAD_ARG(i)) {

                temp_dead(s, ts);

            }

        }

    }

}


static void curl_multi_do(void *arg)

{

    BDRVCURLState *s = (BDRVCURLState *)arg;

    int running;

    int r;

    if (!s->multi) {

        return;

    }

    do {

        r = curl_multi_socket_all(s->multi, &running);

    } while(r == CURLM_CALL_MULTI_PERFORM);

    curl_multi_read(s);

}


static int ffserver_save_avoption(const char *opt, const char *arg, int type, FFServerConfig *config)

{

    static int hinted = 0;

    int ret = 0;

    AVDictionaryEntry *e;

    const AVOption *o = NULL;

    const char *option = NULL;

    const char *codec_name = NULL;

    char buff[1024];

    AVCodecContext *ctx;

    AVDictionary **dict;

    enum AVCodecID guessed_codec_id;

    switch (type) {

    case AV_OPT_FLAG_VIDEO_PARAM:

        ctx = config->dummy_vctx;

        dict = &config->video_opts;

        guessed_codec_id = config->guessed_video_codec_id != AV_CODEC_ID_NONE ?

                           config->guessed_video_codec_id : AV_CODEC_ID_H264;

        break;

    case AV_OPT_FLAG_AUDIO_PARAM:

        ctx = config->dummy_actx;

        dict = &config->audio_opts;

        guessed_codec_id = config->guessed_audio_codec_id != AV_CODEC_ID_NONE ?

                           config->guessed_audio_codec_id : AV_CODEC_ID_AAC;

        break;

    default:

        av_assert0(0);

    }

    if (strchr(opt, ':')) {

        //explicit private option

        snprintf(buff, sizeof(buff), "%s", opt);

        codec_name = buff;

        option = strchr(buff, ':');

        buff[option - buff] = '\0';

        option++;

        if ((ret = ffserver_set_codec(ctx, codec_name, config)) < 0)

            return ret;

        if (!ctx->codec || !ctx->priv_data)

            return -1;

    } else {

        option = opt;

    }

    o = av_opt_find(ctx, option, NULL, type | AV_OPT_FLAG_ENCODING_PARAM, AV_OPT_SEARCH_CHILDREN);

    if (!o && (!strcmp(option, "time_base")  || !strcmp(option, "pixel_format") ||

               !strcmp(option, "video_size") || !strcmp(option, "codec_tag")))

        o = av_opt_find(ctx, option, NULL, 0, 0);

    if (!o) {

        report_config_error(config->filename, config->line_num, AV_LOG_ERROR,

                            &config->errors, "Option not found: %s\n", opt);

        if (!hinted && ctx->codec_id == AV_CODEC_ID_NONE) {

            hinted = 1;

            report_config_error(config->filename, config->line_num, AV_LOG_ERROR, NULL,

                                "If '%s' is a codec private option, then prefix it with codec name, "

                                "for example '%s:%s %s' or define codec earlier.\n",

                                opt, avcodec_get_name(guessed_codec_id) ,opt, arg);

        }

    } else if ((ret = av_opt_set(ctx, option, arg, AV_OPT_SEARCH_CHILDREN)) < 0) {

        report_config_error(config->filename, config->line_num, AV_LOG_ERROR,

                &config->errors, "Invalid value for option %s (%s): %s\n", opt,

                arg, av_err2str(ret));

    } else if ((e = av_dict_get(*dict, option, NULL, 0))) {

        if ((o->type == AV_OPT_TYPE_FLAGS) && arg && (arg[0] == '+' || arg[0] == '-'))

            return av_dict_set(dict, option, arg, AV_DICT_APPEND);

        report_config_error(config->filename, config->line_num, AV_LOG_ERROR,

                &config->errors,

                "Redeclaring value of the option %s, previous value: %s\n",

                opt, e->value);

    } else if (av_dict_set(dict, option, arg, 0) < 0) {

        return AVERROR(ENOMEM);

    }

    return 0;

}


static int decode_opc(MoxieCPU *cpu, DisasContext *ctx)

{

    CPUMoxieState *env = &cpu->env;

    /* Local cache for the instruction opcode.  */

    int opcode;

    /* Set the default instruction length.  */

    int length = 2;

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

        tcg_gen_debug_insn_start(ctx->pc);

    }

    /* Examine the 16-bit opcode.  */

    opcode = ctx->opcode;

    /* Decode instruction.  */

    if (opcode & (1 << 15)) {

        if (opcode & (1 << 14)) {

            /* This is a Form 3 instruction.  */

            int inst = (opcode >> 10 & 0xf);

#define BRANCH(cond)                                                         \

    do {                                                                     \

        int l1 = gen_new_label();                                            \

        tcg_gen_brcond_i32(cond, cc_a, cc_b, l1);                            \

        gen_goto_tb(env, ctx, 1, ctx->pc+2);                                 \

        gen_set_label(l1);                                                   \

        gen_goto_tb(env, ctx, 0, extract_branch_offset(opcode) + ctx->pc+2); \

        ctx->bstate = BS_BRANCH;                                             \

    } while (0)

            switch (inst) {

            case 0x00: /* beq */

                BRANCH(TCG_COND_EQ);

                break;

            case 0x01: /* bne */

                BRANCH(TCG_COND_NE);

                break;

            case 0x02: /* blt */

                BRANCH(TCG_COND_LT);

                break;

            case 0x03: /* bgt */

                BRANCH(TCG_COND_GT);

                break;

            case 0x04: /* bltu */

                BRANCH(TCG_COND_LTU);

                break;

            case 0x05: /* bgtu */

                BRANCH(TCG_COND_GTU);

                break;

            case 0x06: /* bge */

                BRANCH(TCG_COND_GE);

                break;

            case 0x07: /* ble */

                BRANCH(TCG_COND_LE);

                break;

            case 0x08: /* bgeu */

                BRANCH(TCG_COND_GEU);

                break;

            case 0x09: /* bleu */

                BRANCH(TCG_COND_LEU);

                break;

            default:

                {

                    TCGv temp = tcg_temp_new_i32();

                    tcg_gen_movi_i32(cpu_pc, ctx->pc);

                    tcg_gen_movi_i32(temp, MOXIE_EX_BAD);

                    gen_helper_raise_exception(cpu_env, temp);

                    tcg_temp_free_i32(temp);

                }

                break;

            }

        } else {

            /* This is a Form 2 instruction.  */

            int inst = (opcode >> 12 & 0x3);

            switch (inst) {

            case 0x00: /* inc */

                {

                    int a = (opcode >> 8) & 0xf;

                    unsigned int v = (opcode & 0xff);

                    tcg_gen_addi_i32(REG(a), REG(a), v);

                }

                break;

            case 0x01: /* dec */

                {

                    int a = (opcode >> 8) & 0xf;

                    unsigned int v = (opcode & 0xff);

                    tcg_gen_subi_i32(REG(a), REG(a), v);

                }

                break;

            case 0x02: /* gsr */

                {

                    int a = (opcode >> 8) & 0xf;

                    unsigned v = (opcode & 0xff);

                    tcg_gen_ld_i32(REG(a), cpu_env,

                                   offsetof(CPUMoxieState, sregs[v]));

                }

                break;

            case 0x03: /* ssr */

                {

                    int a = (opcode >> 8) & 0xf;

                    unsigned v = (opcode & 0xff);

                    tcg_gen_st_i32(REG(a), cpu_env,

                                   offsetof(CPUMoxieState, sregs[v]));

                }

                break;

            default:

                {

                    TCGv temp = tcg_temp_new_i32();

                    tcg_gen_movi_i32(cpu_pc, ctx->pc);

                    tcg_gen_movi_i32(temp, MOXIE_EX_BAD);

                    gen_helper_raise_exception(cpu_env, temp);

                    tcg_temp_free_i32(temp);

                }

                break;

            }

        }

    } else {

        /* This is a Form 1 instruction.  */

        int inst = opcode >> 8;

        switch (inst) {

        case 0x00: /* nop */

            break;

        case 0x01: /* ldi.l (immediate) */

            {

                int reg = (opcode >> 4) & 0xf;

                int val = cpu_ldl_code(env, ctx->pc+2);

                tcg_gen_movi_i32(REG(reg), val);

                length = 6;

            }

            break;

        case 0x02: /* mov (register-to-register) */

            {

                int dest  = (opcode >> 4) & 0xf;

                int src = opcode & 0xf;

                tcg_gen_mov_i32(REG(dest), REG(src));

            }

            break;

        case 0x03: /* jsra */

            {

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_movi_i32(t1, ctx->pc + 6);

                /* Make space for the static chain and return address.  */

                tcg_gen_subi_i32(t2, REG(1), 8);

                tcg_gen_mov_i32(REG(1), t2);

                tcg_gen_qemu_st32(t1, REG(1), ctx->memidx);

                /* Push the current frame pointer.  */

                tcg_gen_subi_i32(t2, REG(1), 4);

                tcg_gen_mov_i32(REG(1), t2);

                tcg_gen_qemu_st32(REG(0), REG(1), ctx->memidx);

                /* Set the pc and $fp.  */

                tcg_gen_mov_i32(REG(0), REG(1));

                gen_goto_tb(env, ctx, 0, cpu_ldl_code(env, ctx->pc+2));

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                ctx->bstate = BS_BRANCH;

                length = 6;

            }

            break;

        case 0x04: /* ret */

            {

                TCGv t1 = tcg_temp_new_i32();

                /* The new $sp is the old $fp.  */

                tcg_gen_mov_i32(REG(1), REG(0));

                /* Pop the frame pointer.  */

                tcg_gen_qemu_ld32u(REG(0), REG(1), ctx->memidx);

                tcg_gen_addi_i32(t1, REG(1), 4);

                tcg_gen_mov_i32(REG(1), t1);

                /* Pop the return address and skip over the static chain

                   slot.  */

                tcg_gen_qemu_ld32u(cpu_pc, REG(1), ctx->memidx);

                tcg_gen_addi_i32(t1, REG(1), 8);

                tcg_gen_mov_i32(REG(1), t1);

                tcg_temp_free_i32(t1);

                /* Jump... */

                tcg_gen_exit_tb(0);

                ctx->bstate = BS_BRANCH;

            }

            break;

        case 0x05: /* add.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_add_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x06: /* push */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                tcg_gen_subi_i32(t1, REG(a), 4);

                tcg_gen_mov_i32(REG(a), t1);

                tcg_gen_qemu_st32(REG(b), REG(a), ctx->memidx);

                tcg_temp_free_i32(t1);

            }

            break;

        case 0x07: /* pop */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                tcg_gen_qemu_ld32u(REG(b), REG(a), ctx->memidx);

                tcg_gen_addi_i32(t1, REG(a), 4);

                tcg_gen_mov_i32(REG(a), t1);

                tcg_temp_free_i32(t1);

            }

            break;

        case 0x08: /* lda.l */

            {

                int reg = (opcode >> 4) & 0xf;

                TCGv ptr = tcg_temp_new_i32();

                tcg_gen_movi_i32(ptr, cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_ld32u(REG(reg), ptr, ctx->memidx);

                tcg_temp_free_i32(ptr);

                length = 6;

            }

            break;

        case 0x09: /* sta.l */

            {

                int val = (opcode >> 4) & 0xf;

                TCGv ptr = tcg_temp_new_i32();

                tcg_gen_movi_i32(ptr, cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_st32(REG(val), ptr, ctx->memidx);

                tcg_temp_free_i32(ptr);

                length = 6;

            }

            break;

        case 0x0a: /* ld.l (register indirect) */

            {

                int src  = opcode & 0xf;

                int dest = (opcode >> 4) & 0xf;

                tcg_gen_qemu_ld32u(REG(dest), REG(src), ctx->memidx);

            }

            break;

        case 0x0b: /* st.l */

            {

                int dest = (opcode >> 4) & 0xf;

                int val  = opcode & 0xf;

                tcg_gen_qemu_st32(REG(val), REG(dest), ctx->memidx);

            }

            break;

        case 0x0c: /* ldo.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_addi_i32(t1, REG(b), cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_ld32u(t2, t1, ctx->memidx);

                tcg_gen_mov_i32(REG(a), t2);

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                length = 6;

            }

            break;

        case 0x0d: /* sto.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_addi_i32(t1, REG(a), cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_st32(REG(b), t1, ctx->memidx);

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                length = 6;

            }

            break;

        case 0x0e: /* cmp */

            {

                int a  = (opcode >> 4) & 0xf;

                int b  = opcode & 0xf;

                tcg_gen_mov_i32(cc_a, REG(a));

                tcg_gen_mov_i32(cc_b, REG(b));

            }

            break;

        case 0x19: /* jsr */

            {

                int fnreg = (opcode >> 4) & 0xf;

                /* Load the stack pointer into T0.  */

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_movi_i32(t1, ctx->pc+2);

                /* Make space for the static chain and return address.  */

                tcg_gen_subi_i32(t2, REG(1), 8);

                tcg_gen_mov_i32(REG(1), t2);

                tcg_gen_qemu_st32(t1, REG(1), ctx->memidx);

                /* Push the current frame pointer.  */

                tcg_gen_subi_i32(t2, REG(1), 4);

                tcg_gen_mov_i32(REG(1), t2);

                tcg_gen_qemu_st32(REG(0), REG(1), ctx->memidx);

                /* Set the pc and $fp.  */

                tcg_gen_mov_i32(REG(0), REG(1));

                tcg_gen_mov_i32(cpu_pc, REG(fnreg));

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                tcg_gen_exit_tb(0);

                ctx->bstate = BS_BRANCH;

            }

            break;

        case 0x1a: /* jmpa */

            {

                tcg_gen_movi_i32(cpu_pc, cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_exit_tb(0);

                ctx->bstate = BS_BRANCH;

                length = 6;

            }

            break;

        case 0x1b: /* ldi.b (immediate) */

            {

                int reg = (opcode >> 4) & 0xf;

                int val = cpu_ldl_code(env, ctx->pc+2);

                tcg_gen_movi_i32(REG(reg), val);

                length = 6;

            }

            break;

        case 0x1c: /* ld.b (register indirect) */

            {

                int src  = opcode & 0xf;

                int dest = (opcode >> 4) & 0xf;

                tcg_gen_qemu_ld8u(REG(dest), REG(src), ctx->memidx);

            }

            break;

        case 0x1d: /* lda.b */

            {

                int reg = (opcode >> 4) & 0xf;

                TCGv ptr = tcg_temp_new_i32();

                tcg_gen_movi_i32(ptr, cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_ld8u(REG(reg), ptr, ctx->memidx);

                tcg_temp_free_i32(ptr);

                length = 6;

            }

            break;

        case 0x1e: /* st.b */

            {

                int dest = (opcode >> 4) & 0xf;

                int val  = opcode & 0xf;

                tcg_gen_qemu_st8(REG(val), REG(dest), ctx->memidx);

            }

            break;

        case 0x1f: /* sta.b */

            {

                int val = (opcode >> 4) & 0xf;

                TCGv ptr = tcg_temp_new_i32();

                tcg_gen_movi_i32(ptr, cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_st8(REG(val), ptr, ctx->memidx);

                tcg_temp_free_i32(ptr);

                length = 6;

            }

            break;

        case 0x20: /* ldi.s (immediate) */

            {

                int reg = (opcode >> 4) & 0xf;

                int val = cpu_ldl_code(env, ctx->pc+2);

                tcg_gen_movi_i32(REG(reg), val);

                length = 6;

            }

            break;

        case 0x21: /* ld.s (register indirect) */

            {

                int src  = opcode & 0xf;

                int dest = (opcode >> 4) & 0xf;

                tcg_gen_qemu_ld16u(REG(dest), REG(src), ctx->memidx);

            }

            break;

        case 0x22: /* lda.s */

            {

                int reg = (opcode >> 4) & 0xf;

                TCGv ptr = tcg_temp_new_i32();

                tcg_gen_movi_i32(ptr, cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_ld16u(REG(reg), ptr, ctx->memidx);

                tcg_temp_free_i32(ptr);

                length = 6;

            }

            break;

        case 0x23: /* st.s */

            {

                int dest = (opcode >> 4) & 0xf;

                int val  = opcode & 0xf;

                tcg_gen_qemu_st16(REG(val), REG(dest), ctx->memidx);

            }

            break;

        case 0x24: /* sta.s */

            {

                int val = (opcode >> 4) & 0xf;

                TCGv ptr = tcg_temp_new_i32();

                tcg_gen_movi_i32(ptr, cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_st16(REG(val), ptr, ctx->memidx);

                tcg_temp_free_i32(ptr);

                length = 6;

            }

            break;

        case 0x25: /* jmp */

            {

                int reg = (opcode >> 4) & 0xf;

                tcg_gen_mov_i32(cpu_pc, REG(reg));

                tcg_gen_exit_tb(0);

                ctx->bstate = BS_BRANCH;

            }

            break;

        case 0x26: /* and */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_and_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x27: /* lshr */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv sv = tcg_temp_new_i32();

                tcg_gen_andi_i32(sv, REG(b), 0x1f);

                tcg_gen_shr_i32(REG(a), REG(a), sv);

                tcg_temp_free_i32(sv);

            }

            break;

        case 0x28: /* ashl */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv sv = tcg_temp_new_i32();

                tcg_gen_andi_i32(sv, REG(b), 0x1f);

                tcg_gen_shl_i32(REG(a), REG(a), sv);

                tcg_temp_free_i32(sv);

            }

            break;

        case 0x29: /* sub.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_sub_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x2a: /* neg */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_neg_i32(REG(a), REG(b));

            }

            break;

        case 0x2b: /* or */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_or_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x2c: /* not */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_not_i32(REG(a), REG(b));

            }

            break;

        case 0x2d: /* ashr */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv sv = tcg_temp_new_i32();

                tcg_gen_andi_i32(sv, REG(b), 0x1f);

                tcg_gen_sar_i32(REG(a), REG(a), sv);

                tcg_temp_free_i32(sv);

            }

            break;

        case 0x2e: /* xor */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_xor_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x2f: /* mul.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_mul_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x30: /* swi */

            {

                int val = cpu_ldl_code(env, ctx->pc+2);

                TCGv temp = tcg_temp_new_i32();

                tcg_gen_movi_i32(temp, val);

                tcg_gen_st_i32(temp, cpu_env,

                               offsetof(CPUMoxieState, sregs[3]));

                tcg_gen_movi_i32(cpu_pc, ctx->pc);

                tcg_gen_movi_i32(temp, MOXIE_EX_SWI);

                gen_helper_raise_exception(cpu_env, temp);

                tcg_temp_free_i32(temp);

                length = 6;

            }

            break;

        case 0x31: /* div.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_movi_i32(cpu_pc, ctx->pc);

                gen_helper_div(REG(a), cpu_env, REG(a), REG(b));

            }

            break;

        case 0x32: /* udiv.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_movi_i32(cpu_pc, ctx->pc);

                gen_helper_udiv(REG(a), cpu_env, REG(a), REG(b));

            }

            break;

        case 0x33: /* mod.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_rem_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x34: /* umod.l */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                tcg_gen_remu_i32(REG(a), REG(a), REG(b));

            }

            break;

        case 0x35: /* brk */

            {

                TCGv temp = tcg_temp_new_i32();

                tcg_gen_movi_i32(cpu_pc, ctx->pc);

                tcg_gen_movi_i32(temp, MOXIE_EX_BREAK);

                gen_helper_raise_exception(cpu_env, temp);

                tcg_temp_free_i32(temp);

            }

            break;

        case 0x36: /* ldo.b */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_addi_i32(t1, REG(b), cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_ld8u(t2, t1, ctx->memidx);

                tcg_gen_mov_i32(REG(a), t2);

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                length = 6;

            }

            break;

        case 0x37: /* sto.b */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_addi_i32(t1, REG(a), cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_st8(REG(b), t1, ctx->memidx);

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                length = 6;

            }

            break;

        case 0x38: /* ldo.s */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_addi_i32(t1, REG(b), cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_ld16u(t2, t1, ctx->memidx);

                tcg_gen_mov_i32(REG(a), t2);

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                length = 6;

            }

            break;

        case 0x39: /* sto.s */

            {

                int a = (opcode >> 4) & 0xf;

                int b = opcode & 0xf;

                TCGv t1 = tcg_temp_new_i32();

                TCGv t2 = tcg_temp_new_i32();

                tcg_gen_addi_i32(t1, REG(a), cpu_ldl_code(env, ctx->pc+2));

                tcg_gen_qemu_st16(REG(b), t1, ctx->memidx);

                tcg_temp_free_i32(t1);

                tcg_temp_free_i32(t2);

                length = 6;

            }

            break;

        default:

            {

                TCGv temp = tcg_temp_new_i32();

                tcg_gen_movi_i32(cpu_pc, ctx->pc);

                tcg_gen_movi_i32(temp, MOXIE_EX_BAD);

                gen_helper_raise_exception(cpu_env, temp);

                tcg_temp_free_i32(temp);

             }

            break;

        }

    }

    return length;

}


static void tcg_out_opc(TCGContext *s, int opc, int r, int rm, int x)

{

    int rex;

    if (opc & P_GS) {

        tcg_out8(s, 0x65);

    }

    if (opc & P_DATA16) {

        /* We should never be asking for both 16 and 64-bit operation.  */

        assert((opc & P_REXW) == 0);

        tcg_out8(s, 0x66);

    }

    if (opc & P_ADDR32) {

        tcg_out8(s, 0x67);

    }

    rex = 0;

    rex |= (opc & P_REXW) ? 0x8 : 0x0;  /* REX.W */

    rex |= (r & 8) >> 1;                /* REX.R */

    rex |= (x & 8) >> 2;                /* REX.X */

    rex |= (rm & 8) >> 3;               /* REX.B */

    /* P_REXB_{R,RM} indicates that the given register is the low byte.

       For %[abcd]l we need no REX prefix, but for %{si,di,bp,sp}l we do,

       as otherwise the encoding indicates %[abcd]h.  Note that the values

       that are ORed in merely indicate that the REX byte must be present;

       those bits get discarded in output.  */

    rex |= opc & (r >= 4 ? P_REXB_R : 0);

    rex |= opc & (rm >= 4 ? P_REXB_RM : 0);

    if (rex) {

        tcg_out8(s, (uint8_t)(rex | 0x40));

    }

    if (opc & (P_EXT | P_EXT38)) {

        tcg_out8(s, 0x0f);

        if (opc & P_EXT38) {

            tcg_out8(s, 0x38);

        }

    }

    tcg_out8(s, opc);

}


qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,

                            uint64_t bytes, QEMUIOVector *qiov)

{

    BDRVQcow2State *s = bs->opaque;

    QEMUIOVector hd_qiov;

    struct iovec iov;

    z_stream strm;

    int ret, out_len;

    uint8_t *buf, *out_buf;

    uint64_t cluster_offset;

    if (bytes == 0) {

        /* align end of file to a sector boundary to ease reading with

           sector based I/Os */

        cluster_offset = bdrv_getlength(bs->file->bs);

        return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL);

    }

    buf = qemu_blockalign(bs, s->cluster_size);

    if (bytes != s->cluster_size) {

        if (bytes > s->cluster_size ||

            offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)

        {

            qemu_vfree(buf);

            return -EINVAL;

        }

        /* Zero-pad last write if image size is not cluster aligned */

        memset(buf + bytes, 0, s->cluster_size - bytes);

    }

    qemu_iovec_to_buf(qiov, 0, buf, bytes);

    out_buf = g_malloc(s->cluster_size);

    /* best compression, small window, no zlib header */

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

    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,

                       Z_DEFLATED, -12,

                       9, Z_DEFAULT_STRATEGY);

    if (ret != 0) {

        ret = -EINVAL;

        goto fail;

    }

    strm.avail_in = s->cluster_size;

    strm.next_in = (uint8_t *)buf;

    strm.avail_out = s->cluster_size;

    strm.next_out = out_buf;

    ret = deflate(&strm, Z_FINISH);

    if (ret != Z_STREAM_END && ret != Z_OK) {

        deflateEnd(&strm);

        ret = -EINVAL;

        goto fail;

    }

    out_len = strm.next_out - out_buf;

    deflateEnd(&strm);

    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {

        /* could not compress: write normal cluster */

        ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        goto success;

    }

    qemu_co_mutex_lock(&s->lock);

    cluster_offset =

        qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);

    if (!cluster_offset) {

        qemu_co_mutex_unlock(&s->lock);

        ret = -EIO;

        goto fail;

    }

    cluster_offset &= s->cluster_offset_mask;

    ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);

    qemu_co_mutex_unlock(&s->lock);

    if (ret < 0) {

        goto fail;

    }

    iov = (struct iovec) {

        .iov_base   = out_buf,

        .iov_len    = out_len,

    };

    qemu_iovec_init_external(&hd_qiov, &iov, 1);

    BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);

    ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);

    if (ret < 0) {

        goto fail;

    }

success:

    ret = 0;

fail:

    qemu_vfree(buf);

    g_free(out_buf);

    return ret;

}


static void gen_mfrom(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

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

#endif

}


static inline void RENAME(yuv422ptouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

                                         long width, long height,

                                         long lumStride, long chromStride, long dstStride)

{

    RENAME(yuvPlanartouyvy)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 1);

}


static gboolean ga_channel_open(GAChannel *c, const gchar *path,

                                GAChannelMethod method, int fd)

{

    int ret;

    c->method = method;

    switch (c->method) {

    case GA_CHANNEL_VIRTIO_SERIAL: {

        assert(fd < 0);

        fd = qemu_open(path, O_RDWR | O_NONBLOCK

#ifndef CONFIG_SOLARIS

                           | O_ASYNC

#endif

                           );

        if (fd == -1) {

            g_critical("error opening channel: %s", strerror(errno));

            return false;

        }

#ifdef CONFIG_SOLARIS

        ret = ioctl(fd, I_SETSIG, S_OUTPUT | S_INPUT | S_HIPRI);

        if (ret == -1) {

            g_critical("error setting event mask for channel: %s",

                       strerror(errno));

            close(fd);

            return false;

        }

#endif

        ret = ga_channel_client_add(c, fd);

        if (ret) {

            g_critical("error adding channel to main loop");

            close(fd);

            return false;

        }

        break;

    }

    case GA_CHANNEL_ISA_SERIAL: {

        struct termios tio;

        assert(fd < 0);

        fd = qemu_open(path, O_RDWR | O_NOCTTY | O_NONBLOCK);

        if (fd == -1) {

            g_critical("error opening channel: %s", strerror(errno));

            return false;

        }

        tcgetattr(fd, &tio);

        /* set up serial port for non-canonical, dumb byte streaming */

        tio.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |

                         INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY |

                         IMAXBEL);

        tio.c_oflag = 0;

        tio.c_lflag = 0;

        tio.c_cflag |= GA_CHANNEL_BAUDRATE_DEFAULT;

        /* 1 available byte min or reads will block (we'll set non-blocking

         * elsewhere, else we have to deal with read()=0 instead)

         */

        tio.c_cc[VMIN] = 1;

        tio.c_cc[VTIME] = 0;

        /* flush everything waiting for read/xmit, it's garbage at this point */

        tcflush(fd, TCIFLUSH);

        tcsetattr(fd, TCSANOW, &tio);

        ret = ga_channel_client_add(c, fd);

        if (ret) {

            g_critical("error adding channel to main loop");

            close(fd);

            return false;

        }

        break;

    }

    case GA_CHANNEL_UNIX_LISTEN: {

        if (fd < 0) {

            Error *local_err = NULL;

            fd = unix_listen(path, NULL, strlen(path), &local_err);

            if (local_err != NULL) {

                g_critical("%s", error_get_pretty(local_err));

                error_free(local_err);

                return false;

            }

        }

        ga_channel_listen_add(c, fd, true);

        break;

    }

    case GA_CHANNEL_VSOCK_LISTEN: {

        if (fd < 0) {

            Error *local_err = NULL;

            SocketAddress *addr;

            char *addr_str;

            addr_str = g_strdup_printf("vsock:%s", path);

            addr = socket_parse(addr_str, &local_err);

            g_free(addr_str);

            if (local_err != NULL) {

                g_critical("%s", error_get_pretty(local_err));

                error_free(local_err);

                return false;

            }

            fd = socket_listen(addr, &local_err);

            qapi_free_SocketAddress(addr);

            if (local_err != NULL) {

                g_critical("%s", error_get_pretty(local_err));

                error_free(local_err);

                return false;

            }

        }

        ga_channel_listen_add(c, fd, true);

        break;

    }

    default:

        g_critical("error binding/listening to specified socket");

        return false;

    }

    return true;

}


static int ram_save_block(QEMUFile *f)

{

    RAMBlock *block = last_block;

    ram_addr_t offset = last_offset;

    int bytes_sent = -1;

    MemoryRegion *mr;

    if (!block)

        block = QLIST_FIRST(&ram_list.blocks);

    do {

        mr = block->mr;

        if (memory_region_get_dirty(mr, offset, TARGET_PAGE_SIZE,

                                    DIRTY_MEMORY_MIGRATION)) {

            uint8_t *p;

            int cont = (block == last_block) ? RAM_SAVE_FLAG_CONTINUE : 0;

            memory_region_reset_dirty(mr, offset, TARGET_PAGE_SIZE,

                                      DIRTY_MEMORY_MIGRATION);

            p = memory_region_get_ram_ptr(mr) + offset;

            if (is_dup_page(p)) {

                save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_COMPRESS);

                qemu_put_byte(f, *p);

                bytes_sent = 1;

            } else {

                save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_PAGE);

                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);

                bytes_sent = TARGET_PAGE_SIZE;

            }

            break;

        }

        offset += TARGET_PAGE_SIZE;

        if (offset >= block->length) {

            offset = 0;

            block = QLIST_NEXT(block, next);

            if (!block)

                block = QLIST_FIRST(&ram_list.blocks);

        }

    } while (block != last_block || offset != last_offset);

    last_block = block;

    last_offset = offset;

    return bytes_sent;

}


bool net_tx_pkt_add_raw_fragment(struct NetTxPkt *pkt, hwaddr pa,

    size_t len)

{

    hwaddr mapped_len = 0;

    struct iovec *ventry;

    assert(pkt);

    assert(pkt->max_raw_frags > pkt->raw_frags);

    if (!len) {

        return true;

     }

    ventry = &pkt->raw[pkt->raw_frags];

    mapped_len = len;

    ventry->iov_base = cpu_physical_memory_map(pa, &mapped_len, false);

    ventry->iov_len = mapped_len;

    pkt->raw_frags += !!ventry->iov_base;

    if ((ventry->iov_base == NULL) || (len != mapped_len)) {

        return false;

    }

    return true;

}


yuv2422_2_c_template(SwsContext *c, const uint16_t *buf0,

                     const uint16_t *buf1, const uint16_t *ubuf0,

                     const uint16_t *ubuf1, const uint16_t *vbuf0,

                     const uint16_t *vbuf1, const uint16_t *abuf0,

                     const uint16_t *abuf1, uint8_t *dest, int dstW,

                     int yalpha, int uvalpha, int y,

                     enum PixelFormat target)

{

    int  yalpha1 = 4095 - yalpha;

    int uvalpha1 = 4095 - uvalpha;

    int i;

    for (i = 0; i < (dstW >> 1); i++) {

        int Y1 = (buf0[i * 2]     * yalpha1  + buf1[i * 2]     * yalpha)  >> 19;

        int Y2 = (buf0[i * 2 + 1] * yalpha1  + buf1[i * 2 + 1] * yalpha)  >> 19;

        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha) >> 19;

        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha) >> 19;

        output_pixels(i * 4, Y1, U, Y2, V);

    }

}