static int virtio_serial_load(QEMUFile *f, void *opaque, int version_id)

{

    VirtIOSerial *s = opaque;

    VirtIOSerialPort *port;

    uint32_t max_nr_ports, nr_active_ports, ports_map;

    unsigned int i;

    int ret;

    if (version_id > 3) {

        return -EINVAL;

    }

    /* The virtio device */

    ret = virtio_load(&s->vdev, f);

    if (ret) {

        return ret;

    }

    if (version_id < 2) {

        return 0;

    }

    /* The config space */

    qemu_get_be16s(f, &s->config.cols);

    qemu_get_be16s(f, &s->config.rows);

    qemu_get_be32s(f, &max_nr_ports);

    tswap32s(&max_nr_ports);

    if (max_nr_ports > tswap32(s->config.max_nr_ports)) {

        /* Source could have had more ports than us. Fail migration. */

        return -EINVAL;

    }

    for (i = 0; i < (max_nr_ports + 31) / 32; i++) {

        qemu_get_be32s(f, &ports_map);

        if (ports_map != s->ports_map[i]) {

            /*

             * Ports active on source and destination don't

             * match. Fail migration.

             */

            return -EINVAL;

        }

    }

    qemu_get_be32s(f, &nr_active_ports);

    /* Items in struct VirtIOSerialPort */

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

        uint32_t id;

        bool host_connected;

        id = qemu_get_be32(f);

        port = find_port_by_id(s, id);

        if (!port) {

            return -EINVAL;

        }

        port->guest_connected = qemu_get_byte(f);

        host_connected = qemu_get_byte(f);

        if (host_connected != port->host_connected) {

            /*

             * We have to let the guest know of the host connection

             * status change

             */

            send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN,

                               port->host_connected);

        }

        if (version_id > 2) {

            uint32_t elem_popped;

            qemu_get_be32s(f, &elem_popped);

            if (elem_popped) {

                qemu_get_be32s(f, &port->iov_idx);

                qemu_get_be64s(f, &port->iov_offset);

                qemu_get_buffer(f, (unsigned char *)&port->elem,

                                sizeof(port->elem));

                virtqueue_map_sg(port->elem.in_sg, port->elem.in_addr,

                                 port->elem.in_num, 1);

                virtqueue_map_sg(port->elem.out_sg, port->elem.out_addr,

                                 port->elem.out_num, 1);

                /*

                 *  Port was throttled on source machine.  Let's

                 *  unthrottle it here so data starts flowing again.

                 */

                virtio_serial_throttle_port(port, false);

            }

        }

    }

    return 0;

}


static CharDriverState *qemu_chr_open_spice_port(const char *id,

                                                 ChardevBackend *backend,

                                                 ChardevReturn *ret,

                                                 Error **errp)

{

    const char *name = backend->spiceport->fqdn;

    CharDriverState *chr;

    SpiceCharDriver *s;

    if (name == NULL) {

        fprintf(stderr, "spice-qemu-char: missing name parameter\n");

        return NULL;

    }

    chr = chr_open("port", spice_port_set_fe_open);

    s = chr->opaque;

    s->sin.portname = g_strdup(name);

    return chr;

}


void cpu_breakpoint_remove_by_ref(CPUState *cpu, CPUBreakpoint *breakpoint)

{

#if defined(TARGET_HAS_ICE)

    QTAILQ_REMOVE(&cpu->breakpoints, breakpoint, entry);

    breakpoint_invalidate(cpu, breakpoint->pc);

    g_free(breakpoint);

#endif

}


static int flv_write_trailer(AVFormatContext *s)

{

    int64_t file_size;

    AVIOContext *pb = s->pb;

    FLVContext *flv = s->priv_data;

    int i;

    /* Add EOS tag */

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

        AVCodecContext *enc = s->streams[i]->codec;

        FLVStreamContext *sc = s->streams[i]->priv_data;

        if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&

            enc->codec_id == AV_CODEC_ID_H264)

            put_avc_eos_tag(pb, sc->last_ts);

    }

    file_size = avio_tell(pb);

    /* update information */

    avio_seek(pb, flv->duration_offset, SEEK_SET);

    put_amf_double(pb, flv->duration / (double)1000);

    avio_seek(pb, flv->filesize_offset, SEEK_SET);

    put_amf_double(pb, file_size);

    avio_seek(pb, file_size, SEEK_SET);

    return 0;

}


static const void *boston_fdt_filter(void *opaque, const void *fdt_orig,

                                     const void *match_data, hwaddr *load_addr)

{

    BostonState *s = BOSTON(opaque);

    MachineState *machine = s->mach;

    const char *cmdline;

    int err;

    void *fdt;

    size_t fdt_sz, ram_low_sz, ram_high_sz;

    fdt_sz = fdt_totalsize(fdt_orig) * 2;

    fdt = g_malloc0(fdt_sz);

    err = fdt_open_into(fdt_orig, fdt, fdt_sz);

    if (err) {

        fprintf(stderr, "unable to open FDT\n");

        return NULL;

    }

    cmdline = (machine->kernel_cmdline && machine->kernel_cmdline[0])

            ? machine->kernel_cmdline : " ";

    err = qemu_fdt_setprop_string(fdt, "/chosen", "bootargs", cmdline);

    if (err < 0) {

        fprintf(stderr, "couldn't set /chosen/bootargs\n");

        return NULL;

    }

    ram_low_sz = MIN(256 * M_BYTE, machine->ram_size);

    ram_high_sz = machine->ram_size - ram_low_sz;

    qemu_fdt_setprop_sized_cells(fdt, "/memory@0", "reg",

                                 1, 0x00000000, 1, ram_low_sz,

                                 1, 0x90000000, 1, ram_high_sz);

    fdt = g_realloc(fdt, fdt_totalsize(fdt));

    qemu_fdt_dumpdtb(fdt, fdt_sz);

    s->fdt_base = *load_addr;

    return fdt;

}


static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

#if CONFIG_ZLIB

    AVIOContext ctx;

    uint8_t *cmov_data;

    uint8_t *moov_data; /* uncompressed data */

    long cmov_len, moov_len;

    int ret = -1;

    avio_rb32(pb); /* dcom atom */

    if (avio_rl32(pb) != MKTAG('d','c','o','m'))

        return AVERROR_INVALIDDATA;

    if (avio_rl32(pb) != MKTAG('z','l','i','b')) {

        av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");

        return AVERROR_INVALIDDATA;

    }

    avio_rb32(pb); /* cmvd atom */

    if (avio_rl32(pb) != MKTAG('c','m','v','d'))

        return AVERROR_INVALIDDATA;

    moov_len = avio_rb32(pb); /* uncompressed size */

    cmov_len = atom.size - 6 * 4;

    cmov_data = av_malloc(cmov_len);

    if (!cmov_data)

        return AVERROR(ENOMEM);

    moov_data = av_malloc(moov_len);

    if (!moov_data) {

        av_free(cmov_data);

        return AVERROR(ENOMEM);

    }

    avio_read(pb, cmov_data, cmov_len);

    if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)

        goto free_and_return;

    if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)

        goto free_and_return;

    atom.type = MKTAG('m','o','o','v');

    atom.size = moov_len;

    ret = mov_read_default(c, &ctx, atom);

free_and_return:

    av_free(moov_data);

    av_free(cmov_data);

    return ret;

#else

    av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");

    return AVERROR(ENOSYS);

#endif

}


static int sdp_parse_rtpmap(AVFormatContext *s,

                            AVCodecContext *codec, RTSPStream *rtsp_st,

                            int payload_type, const char *p)

{

    char buf[256];

    int i;

    AVCodec *c;

    const char *c_name;

    /* Loop into AVRtpDynamicPayloadTypes[] and AVRtpPayloadTypes[] and

     * see if we can handle this kind of payload.

     * The space should normally not be there but some Real streams or

     * particular servers ("RealServer Version 6.1.3.970", see issue 1658)

     * have a trailing space. */

    get_word_sep(buf, sizeof(buf), "/ ", &p);

    if (payload_type >= RTP_PT_PRIVATE) {

        RTPDynamicProtocolHandler *handler;

        for (handler = RTPFirstDynamicPayloadHandler;

             handler; handler = handler->next) {

            if (!strcasecmp(buf, handler->enc_name) &&

                codec->codec_type == handler->codec_type) {

                codec->codec_id          = handler->codec_id;

                rtsp_st->dynamic_handler = handler;

                if (handler->open)

                    rtsp_st->dynamic_protocol_context = handler->open();

                break;

            }

        }

    } else {

        /* We are in a standard case

         * (from http://www.iana.org/assignments/rtp-parameters). */

        /* search into AVRtpPayloadTypes[] */

        codec->codec_id = ff_rtp_codec_id(buf, codec->codec_type);

    }

    c = avcodec_find_decoder(codec->codec_id);

    if (c && c->name)

        c_name = c->name;

    else

        c_name = (char *) NULL;

    if (c_name) {

        get_word_sep(buf, sizeof(buf), "/", &p);

        i = atoi(buf);

        switch (codec->codec_type) {

        case CODEC_TYPE_AUDIO:

            av_log(s, AV_LOG_DEBUG, "audio codec set to: %s\n", c_name);

            codec->sample_rate = RTSP_DEFAULT_AUDIO_SAMPLERATE;

            codec->channels = RTSP_DEFAULT_NB_AUDIO_CHANNELS;

            if (i > 0) {

                codec->sample_rate = i;

                get_word_sep(buf, sizeof(buf), "/", &p);

                i = atoi(buf);

                if (i > 0)

                    codec->channels = i;

                // TODO: there is a bug here; if it is a mono stream, and

                // less than 22000Hz, faad upconverts to stereo and twice

                // the frequency.  No problem, but the sample rate is being

                // set here by the sdp line. Patch on its way. (rdm)

            }

            av_log(s, AV_LOG_DEBUG, "audio samplerate set to: %i\n",

                   codec->sample_rate);

            av_log(s, AV_LOG_DEBUG, "audio channels set to: %i\n",

                   codec->channels);

            break;

        case CODEC_TYPE_VIDEO:

            av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);

            break;

        default:

            break;

        }

        return 0;

    }

    return -1;

}


void ff_mpv_frame_end(MpegEncContext *s)

{

#if FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

    /* redraw edges for the frame if decoding didn't complete */

    // just to make sure that all data is rendered.

    if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration) {

        ff_xvmc_field_end(s);

    } else

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    emms_c();

    if (s->current_picture.reference)

        ff_thread_report_progress(&s->current_picture_ptr->tf, INT_MAX, 0);

}


static int read_ffserver_streams(AVFormatContext *s, const char *filename)

{

    int i, err;

    AVFormatContext *ic;

    int nopts = 0;

    err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);

    if (err < 0)

        return err;

    /* copy stream format */

    s->nb_streams = ic->nb_streams;

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

        AVStream *st;

        AVCodec *codec;

        // FIXME: a more elegant solution is needed

        st = av_mallocz(sizeof(AVStream));

        memcpy(st, ic->streams[i], sizeof(AVStream));

        st->codec = avcodec_alloc_context();

        if (!st->codec) {

            print_error(filename, AVERROR(ENOMEM));

            ffmpeg_exit(1);

        }

        avcodec_copy_context(st->codec, ic->streams[i]->codec);

        s->streams[i] = st;

        codec = avcodec_find_encoder(st->codec->codec_id);

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

            if (audio_stream_copy) {

                st->stream_copy = 1;

            } else

                choose_sample_fmt(st, codec);

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

            if (video_stream_copy) {

                st->stream_copy = 1;

            } else

                choose_pixel_fmt(st, codec);

        }

        if(!st->codec->thread_count)

            st->codec->thread_count = 1;

        if(st->codec->thread_count>1)

            avcodec_thread_init(st->codec, st->codec->thread_count);

        if(st->codec->flags & CODEC_FLAG_BITEXACT)

            nopts = 1;

    }

    if (!nopts)

        s->timestamp = av_gettime();

    av_close_input_file(ic);

    return 0;

}


static void uninit(AVFilterContext *ctx)

{

    ZScaleContext *s = ctx->priv;

    zimg_filter_graph_free(s->graph);

    av_freep(&s->tmp);

    s->tmp_size = 0;

}


static void decode_bo_addrmode_post_pre_base(CPUTriCoreState *env,

                                             DisasContext *ctx)

{

    uint32_t op2;

    uint32_t off10;

    int32_t r1, r2;

    TCGv temp;

    r1 = MASK_OP_BO_S1D(ctx->opcode);

    r2  = MASK_OP_BO_S2(ctx->opcode);

    off10 = MASK_OP_BO_OFF10_SEXT(ctx->opcode);

    op2 = MASK_OP_BO_OP2(ctx->opcode);

    switch (op2) {

    case OPC2_32_BO_CACHEA_WI_SHORTOFF:

    case OPC2_32_BO_CACHEA_W_SHORTOFF:

    case OPC2_32_BO_CACHEA_I_SHORTOFF:

        /* instruction to access the cache */

        break;

    case OPC2_32_BO_CACHEA_WI_POSTINC:

    case OPC2_32_BO_CACHEA_W_POSTINC:

    case OPC2_32_BO_CACHEA_I_POSTINC:

        /* instruction to access the cache, but we still need to handle

           the addressing mode */

        tcg_gen_addi_tl(cpu_gpr_d[r2], cpu_gpr_d[r2], off10);

        break;

    case OPC2_32_BO_CACHEA_WI_PREINC:

    case OPC2_32_BO_CACHEA_W_PREINC:

    case OPC2_32_BO_CACHEA_I_PREINC:

        /* instruction to access the cache, but we still need to handle

           the addressing mode */

        tcg_gen_addi_tl(cpu_gpr_d[r2], cpu_gpr_d[r2], off10);

        break;

    case OPC2_32_BO_CACHEI_WI_SHORTOFF:

    case OPC2_32_BO_CACHEI_W_SHORTOFF:

        /* TODO: Raise illegal opcode trap,

                 if tricore_feature(TRICORE_FEATURE_13) */

        break;

    case OPC2_32_BO_CACHEI_W_POSTINC:

    case OPC2_32_BO_CACHEI_WI_POSTINC:

        if (!tricore_feature(env, TRICORE_FEATURE_13)) {

            tcg_gen_addi_tl(cpu_gpr_d[r2], cpu_gpr_d[r2], off10);

        } /* TODO: else raise illegal opcode trap */

        break;

    case OPC2_32_BO_CACHEI_W_PREINC:

    case OPC2_32_BO_CACHEI_WI_PREINC:

        if (!tricore_feature(env, TRICORE_FEATURE_13)) {

            tcg_gen_addi_tl(cpu_gpr_d[r2], cpu_gpr_d[r2], off10);

        } /* TODO: else raise illegal opcode trap */

        break;

    case OPC2_32_BO_ST_A_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_a[r1], cpu_gpr_a[r2], off10, MO_LESL);

        break;

    case OPC2_32_BO_ST_A_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_a[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LESL);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_A_PREINC:

        gen_st_preincr(ctx, cpu_gpr_a[r1], cpu_gpr_a[r2], off10, MO_LESL);

        break;

    case OPC2_32_BO_ST_B_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_UB);

        break;

    case OPC2_32_BO_ST_B_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_UB);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_B_PREINC:

        gen_st_preincr(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_UB);

        break;

    case OPC2_32_BO_ST_D_SHORTOFF:

        gen_offset_st_2regs(cpu_gpr_d[r1+1], cpu_gpr_d[r1], cpu_gpr_a[r2],

                            off10, ctx);

        break;

    case OPC2_32_BO_ST_D_POSTINC:

        gen_st_2regs_64(cpu_gpr_d[r1+1], cpu_gpr_d[r1], cpu_gpr_a[r2], ctx);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_D_PREINC:

        temp = tcg_temp_new();

        tcg_gen_addi_tl(temp, cpu_gpr_a[r2], off10);

        gen_st_2regs_64(cpu_gpr_d[r1+1], cpu_gpr_d[r1], temp, ctx);

        tcg_gen_mov_tl(cpu_gpr_a[r2], temp);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_DA_SHORTOFF:

        gen_offset_st_2regs(cpu_gpr_a[r1+1], cpu_gpr_a[r1], cpu_gpr_a[r2],

                            off10, ctx);

        break;

    case OPC2_32_BO_ST_DA_POSTINC:

        gen_st_2regs_64(cpu_gpr_a[r1+1], cpu_gpr_a[r1], cpu_gpr_a[r2], ctx);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_DA_PREINC:

        temp = tcg_temp_new();

        tcg_gen_addi_tl(temp, cpu_gpr_a[r2], off10);

        gen_st_2regs_64(cpu_gpr_a[r1+1], cpu_gpr_a[r1], temp, ctx);

        tcg_gen_mov_tl(cpu_gpr_a[r2], temp);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_H_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUW);

        break;

    case OPC2_32_BO_ST_H_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LEUW);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_H_PREINC:

        gen_st_preincr(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUW);

        break;

    case OPC2_32_BO_ST_Q_SHORTOFF:

        temp = tcg_temp_new();

        tcg_gen_shri_tl(temp, cpu_gpr_d[r1], 16);

        gen_offset_st(ctx, temp, cpu_gpr_a[r2], off10, MO_LEUW);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_Q_POSTINC:

        temp = tcg_temp_new();

        tcg_gen_shri_tl(temp, cpu_gpr_d[r1], 16);

        tcg_gen_qemu_st_tl(temp, cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LEUW);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_Q_PREINC:

        temp = tcg_temp_new();

        tcg_gen_shri_tl(temp, cpu_gpr_d[r1], 16);

        gen_st_preincr(ctx, temp, cpu_gpr_a[r2], off10, MO_LEUW);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_W_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUL);

        break;

    case OPC2_32_BO_ST_W_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LEUL);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_W_PREINC:

        gen_st_preincr(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUL);

        break;

    }

}


static int kvm_mips_get_fpu_registers(CPUState *cs)

{

    MIPSCPU *cpu = MIPS_CPU(cs);

    CPUMIPSState *env = &cpu->env;

    int err, ret = 0;

    unsigned int i;

    /* Only get FPU state if we're emulating a CPU with an FPU */

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

        /* FPU Control Registers */

        err = kvm_mips_get_one_ureg(cs, KVM_REG_MIPS_FCR_IR,

                                    &env->active_fpu.fcr0);

        if (err < 0) {

            DPRINTF("%s: Failed to get FCR_IR (%d)\n", __func__, err);

            ret = err;

        }

        err = kvm_mips_get_one_ureg(cs, KVM_REG_MIPS_FCR_CSR,

                                    &env->active_fpu.fcr31);

        if (err < 0) {

            DPRINTF("%s: Failed to get FCR_CSR (%d)\n", __func__, err);

            ret = err;

        } else {

            restore_fp_status(env);

        }

        /* Floating point registers */

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

            if (env->CP0_Status & (1 << CP0St_FR)) {

                err = kvm_mips_get_one_ureg64(cs, KVM_REG_MIPS_FPR_64(i),

                                              &env->active_fpu.fpr[i].d);

            } else {

                err = kvm_mips_get_one_ureg(cs, KVM_REG_MIPS_FPR_32(i),

                                      &env->active_fpu.fpr[i].w[FP_ENDIAN_IDX]);

            }

            if (err < 0) {

                DPRINTF("%s: Failed to get FPR%u (%d)\n", __func__, i, err);

                ret = err;

            }

        }

    }

    return ret;

}


static void gen_loongson_integer(DisasContext *ctx, uint32_t opc,

                                 int rd, int rs, int rt)

{

    const char *opn = "loongson";

    TCGv t0, t1;

    if (rd == 0) {

        /* Treat as NOP. */

        MIPS_DEBUG("NOP");

        return;

    }

    switch (opc) {

    case OPC_MULT_G_2E:

    case OPC_MULT_G_2F:

    case OPC_MULTU_G_2E:

    case OPC_MULTU_G_2F:

#if defined(TARGET_MIPS64)

    case OPC_DMULT_G_2E:

    case OPC_DMULT_G_2F:

    case OPC_DMULTU_G_2E:

    case OPC_DMULTU_G_2F:

#endif

        t0 = tcg_temp_new();

        t1 = tcg_temp_new();

        break;

    default:

        t0 = tcg_temp_local_new();

        t1 = tcg_temp_local_new();

        break;

    }

    gen_load_gpr(t0, rs);

    gen_load_gpr(t1, rt);

    switch (opc) {

    case OPC_MULT_G_2E:

    case OPC_MULT_G_2F:

        tcg_gen_mul_tl(cpu_gpr[rd], t0, t1);

        tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

        opn = "mult.g";

        break;

    case OPC_MULTU_G_2E:

    case OPC_MULTU_G_2F:

        tcg_gen_ext32u_tl(t0, t0);

        tcg_gen_ext32u_tl(t1, t1);

        tcg_gen_mul_tl(cpu_gpr[rd], t0, t1);

        tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

        opn = "multu.g";

        break;

    case OPC_DIV_G_2E:

    case OPC_DIV_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            int l3 = gen_new_label();

            tcg_gen_ext32s_tl(t0, t0);

            tcg_gen_ext32s_tl(t1, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, 0, l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l3);

            gen_set_label(l1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, INT_MIN, l2);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, -1, l2);

            tcg_gen_mov_tl(cpu_gpr[rd], t0);

            tcg_gen_br(l3);

            gen_set_label(l2);

            tcg_gen_div_tl(cpu_gpr[rd], t0, t1);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

            gen_set_label(l3);

        }

        opn = "div.g";

        break;

    case OPC_DIVU_G_2E:

    case OPC_DIVU_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            tcg_gen_ext32u_tl(t0, t0);

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, 0, l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_divu_tl(cpu_gpr[rd], t0, t1);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

            gen_set_label(l2);

        }

        opn = "divu.g";

        break;

    case OPC_MOD_G_2E:

    case OPC_MOD_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            int l3 = gen_new_label();

            tcg_gen_ext32u_tl(t0, t0);

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, INT_MIN, l2);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, -1, l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l3);

            gen_set_label(l2);

            tcg_gen_rem_tl(cpu_gpr[rd], t0, t1);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

            gen_set_label(l3);

        }

        opn = "mod.g";

        break;

    case OPC_MODU_G_2E:

    case OPC_MODU_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            tcg_gen_ext32u_tl(t0, t0);

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, 0, l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_remu_tl(cpu_gpr[rd], t0, t1);

            tcg_gen_ext32s_tl(cpu_gpr[rd], cpu_gpr[rd]);

            gen_set_label(l2);

        }

        opn = "modu.g";

        break;

#if defined(TARGET_MIPS64)

    case OPC_DMULT_G_2E:

    case OPC_DMULT_G_2F:

        tcg_gen_mul_tl(cpu_gpr[rd], t0, t1);

        opn = "dmult.g";

        break;

    case OPC_DMULTU_G_2E:

    case OPC_DMULTU_G_2F:

        tcg_gen_mul_tl(cpu_gpr[rd], t0, t1);

        opn = "dmultu.g";

        break;

    case OPC_DDIV_G_2E:

    case OPC_DDIV_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            int l3 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, 0, l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l3);

            gen_set_label(l1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, -1LL << 63, l2);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, -1LL, l2);

            tcg_gen_mov_tl(cpu_gpr[rd], t0);

            tcg_gen_br(l3);

            gen_set_label(l2);

            tcg_gen_div_tl(cpu_gpr[rd], t0, t1);

            gen_set_label(l3);

        }

        opn = "ddiv.g";

        break;

    case OPC_DDIVU_G_2E:

    case OPC_DDIVU_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, 0, l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_divu_tl(cpu_gpr[rd], t0, t1);

            gen_set_label(l2);

        }

        opn = "ddivu.g";

        break;

    case OPC_DMOD_G_2E:

    case OPC_DMOD_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            int l3 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, -1LL << 63, l2);

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, -1LL, l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l3);

            gen_set_label(l2);

            tcg_gen_rem_tl(cpu_gpr[rd], t0, t1);

            gen_set_label(l3);

        }

        opn = "dmod.g";

        break;

    case OPC_DMODU_G_2E:

    case OPC_DMODU_G_2F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, 0, l1);

            tcg_gen_movi_tl(cpu_gpr[rd], 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_remu_tl(cpu_gpr[rd], t0, t1);

            gen_set_label(l2);

        }

        opn = "dmodu.g";

        break;

#endif

    }

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s %s, %s", opn, regnames[rd], regnames[rs]);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


static void vfio_pci_load_rom(VFIOPCIDevice *vdev)

{

    struct vfio_region_info reg_info = {

        .argsz = sizeof(reg_info),

        .index = VFIO_PCI_ROM_REGION_INDEX

    };

    uint64_t size;

    off_t off = 0;

    size_t bytes;

    if (ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info)) {

        error_report("vfio: Error getting ROM info: %m");

        return;

    }

    trace_vfio_pci_load_rom(vdev->vbasedev.name, (unsigned long)reg_info.size,

                            (unsigned long)reg_info.offset,

                            (unsigned long)reg_info.flags);

    vdev->rom_size = size = reg_info.size;

    vdev->rom_offset = reg_info.offset;

    if (!vdev->rom_size) {

        vdev->rom_read_failed = true;

        error_report("vfio-pci: Cannot read device rom at "

                    "%s", vdev->vbasedev.name);

        error_printf("Device option ROM contents are probably invalid "

                    "(check dmesg).\nSkip option ROM probe with rombar=0, "

                    "or load from file with romfile=\n");

        return;

    }

    vdev->rom = g_malloc(size);

    memset(vdev->rom, 0xff, size);

    while (size) {

        bytes = pread(vdev->vbasedev.fd, vdev->rom + off,

                      size, vdev->rom_offset + off);

        if (bytes == 0) {

            break;

        } else if (bytes > 0) {

            off += bytes;

            size -= bytes;

        } else {

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

                continue;

            }

            error_report("vfio: Error reading device ROM: %m");

            break;

        }

    }

}


static bool try_poll_mode(AioContext *ctx, bool blocking)

{

    if (blocking && ctx->poll_max_ns && ctx->poll_disable_cnt == 0) {

        /* See qemu_soonest_timeout() uint64_t hack */

        int64_t max_ns = MIN((uint64_t)aio_compute_timeout(ctx),

                             (uint64_t)ctx->poll_max_ns);

        if (max_ns) {

            if (run_poll_handlers(ctx, max_ns)) {

                return true;

            }

        }

    }

    return false;

}


static void pci_basic(gconstpointer data)

{

    QVirtioPCIDevice *dev;

    QPCIBus *bus;

    QVirtQueuePCI *tx, *rx;

    QGuestAllocator *alloc;

    void (*func) (const QVirtioBus *bus,

                  QVirtioDevice *dev,

                  QGuestAllocator *alloc,

                  QVirtQueue *rvq,

                  QVirtQueue *tvq,

                  int socket) = data;

    int sv[2], ret;

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

    g_assert_cmpint(ret, !=, -1);

    bus = pci_test_start(sv[1]);

    dev = virtio_net_pci_init(bus, PCI_SLOT);

    alloc = pc_alloc_init();

    rx = (QVirtQueuePCI *)qvirtqueue_setup(&qvirtio_pci, &dev->vdev,

                                           alloc, 0);

    tx = (QVirtQueuePCI *)qvirtqueue_setup(&qvirtio_pci, &dev->vdev,

                                           alloc, 1);

    driver_init(&qvirtio_pci, &dev->vdev);

    func(&qvirtio_pci, &dev->vdev, alloc, &rx->vq, &tx->vq, sv[0]);

    /* End test */

    close(sv[0]);

    guest_free(alloc, tx->vq.desc);

    pc_alloc_uninit(alloc);

    qvirtio_pci_device_disable(dev);

    g_free(dev);

    qpci_free_pc(bus);

    test_end();

}


static void test_qemu_strtoul_full_negative(void)

{

    const char *str = " \t -321";

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, -321ul);

}


static int vnc_validate_certificate(struct VncState *vs)

{

    int ret;

    unsigned int status;

    const gnutls_datum_t *certs;

    unsigned int nCerts, i;

    time_t now;

    VNC_DEBUG("Validating client certificate\n");

    if ((ret = gnutls_certificate_verify_peers2 (vs->tls_session, &status)) < 0) {

	VNC_DEBUG("Verify failed %s\n", gnutls_strerror(ret));

	return -1;

    }

    if ((now = time(NULL)) == ((time_t)-1)) {

	return -1;

    }

    if (status != 0) {

	if (status & GNUTLS_CERT_INVALID)

	    VNC_DEBUG("The certificate is not trusted.\n");

	if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)

	    VNC_DEBUG("The certificate hasn't got a known issuer.\n");

	if (status & GNUTLS_CERT_REVOKED)

	    VNC_DEBUG("The certificate has been revoked.\n");

	if (status & GNUTLS_CERT_INSECURE_ALGORITHM)

	    VNC_DEBUG("The certificate uses an insecure algorithm\n");

	return -1;

    } else {

	VNC_DEBUG("Certificate is valid!\n");

    }

    /* Only support x509 for now */

    if (gnutls_certificate_type_get(vs->tls_session) != GNUTLS_CRT_X509)

	return -1;

    if (!(certs = gnutls_certificate_get_peers(vs->tls_session, &nCerts)))

	return -1;

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

	gnutls_x509_crt_t cert;

	VNC_DEBUG ("Checking certificate chain %d\n", i);

	if (gnutls_x509_crt_init (&cert) < 0)

	    return -1;

	if (gnutls_x509_crt_import(cert, &certs[i], GNUTLS_X509_FMT_DER) < 0) {

	    gnutls_x509_crt_deinit (cert);

	    return -1;

	}

	if (gnutls_x509_crt_get_expiration_time (cert) < now) {

	    VNC_DEBUG("The certificate has expired\n");

	    gnutls_x509_crt_deinit (cert);

	    return -1;

	}

	if (gnutls_x509_crt_get_activation_time (cert) > now) {

	    VNC_DEBUG("The certificate is not yet activated\n");

	    gnutls_x509_crt_deinit (cert);

	    return -1;

	}

	if (gnutls_x509_crt_get_activation_time (cert) > now) {

	    VNC_DEBUG("The certificate is not yet activated\n");

	    gnutls_x509_crt_deinit (cert);

	    return -1;

	}

	gnutls_x509_crt_deinit (cert);

    }

    return 0;

}


int fw_cfg_add_callback(void *opaque, uint16_t key, FWCfgCallback callback,

                        void *callback_opaque, uint8_t *data, size_t len)

{

    FWCfgState *s = opaque;

    int arch = !!(key & FW_CFG_ARCH_LOCAL);

    key &= FW_CFG_ENTRY_MASK;

    if (key >= FW_CFG_MAX_ENTRY || !(key & FW_CFG_WRITE_CHANNEL)

        || len > 65535)

        return 0;

    s->entries[arch][key].data = data;

    s->entries[arch][key].len = len;

    s->entries[arch][key].callback_opaque = callback_opaque;

    s->entries[arch][key].callback = callback;

    return 1;

}


static void lpc_analyze_remodulate(int32_t *decoded, const int coeffs[32],

                                   int order, int qlevel, int len, int bps)

{

    int i, j;

    int ebps = 1 << (bps-1);

    unsigned sigma = 0;

    for (i = order; i < len; i++)

        sigma |= decoded[i] + ebps;

    if (sigma < 2*ebps)

        return;

    for (i = len - 1; i >= order; i--) {

        int64_t p = 0;

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

            p += coeffs[j] * (int64_t)decoded[i-order+j];

        decoded[i] -= p >> qlevel;

    }

    for (i = order; i < len; i++, decoded++) {

        int32_t p = 0;

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

            p += coeffs[j] * (uint32_t)decoded[j];

        decoded[j] += p >> qlevel;

    }

}


static int read_thread(void *arg)

{

    VideoState *is = arg;

    AVFormatContext *ic = NULL;

    int err, i, ret;

    int st_index[AVMEDIA_TYPE_NB];

    AVPacket pkt1, *pkt = &pkt1;

    int eof = 0;

    int pkt_in_play_range = 0;

    AVDictionaryEntry *t;

    AVDictionary **opts;

    int orig_nb_streams;

    SDL_mutex *wait_mutex = SDL_CreateMutex();

    memset(st_index, -1, sizeof(st_index));

    is->last_video_stream = is->video_stream = -1;

    is->last_audio_stream = is->audio_stream = -1;

    is->last_subtitle_stream = is->subtitle_stream = -1;

    ic = avformat_alloc_context();

    ic->interrupt_callback.callback = decode_interrupt_cb;

    ic->interrupt_callback.opaque = is;

    err = avformat_open_input(&ic, is->filename, is->iformat, &format_opts);

    if (err < 0) {

        print_error(is->filename, err);

        ret = -1;

        goto fail;

    }

    if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {

        av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);

        ret = AVERROR_OPTION_NOT_FOUND;

        goto fail;

    }

    is->ic = ic;

    if (genpts)

        ic->flags |= AVFMT_FLAG_GENPTS;

    opts = setup_find_stream_info_opts(ic, codec_opts);

    orig_nb_streams = ic->nb_streams;

    err = avformat_find_stream_info(ic, opts);

    if (err < 0) {

        fprintf(stderr, "%s: could not find codec parameters\n", is->filename);

        ret = -1;

        goto fail;

    }

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

        av_dict_free(&opts[i]);

    av_freep(&opts);

    if (ic->pb)

        ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end

    if (seek_by_bytes < 0)

        seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT);

    is->max_frame_duration = (ic->iformat->flags & AVFMT_TS_DISCONT) ? 10.0 : 3600.0;

    /* if seeking requested, we execute it */

    if (start_time != AV_NOPTS_VALUE) {

        int64_t timestamp;

        timestamp = start_time;

        /* add the stream start time */

        if (ic->start_time != AV_NOPTS_VALUE)

            timestamp += ic->start_time;

        ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);

        if (ret < 0) {

            fprintf(stderr, "%s: could not seek to position %0.3f\n",

                    is->filename, (double)timestamp / AV_TIME_BASE);

        }

    }

    is->realtime = is_realtime(ic);

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

        ic->streams[i]->discard = AVDISCARD_ALL;

    if (!video_disable)

        st_index[AVMEDIA_TYPE_VIDEO] =

            av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,

                                wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);

    if (!audio_disable)

        st_index[AVMEDIA_TYPE_AUDIO] =

            av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,

                                wanted_stream[AVMEDIA_TYPE_AUDIO],

                                st_index[AVMEDIA_TYPE_VIDEO],

                                NULL, 0);

    if (!video_disable)

        st_index[AVMEDIA_TYPE_SUBTITLE] =

            av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,

                                wanted_stream[AVMEDIA_TYPE_SUBTITLE],

                                (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?

                                 st_index[AVMEDIA_TYPE_AUDIO] :

                                 st_index[AVMEDIA_TYPE_VIDEO]),

                                NULL, 0);

    if (show_status) {

        av_dump_format(ic, 0, is->filename, 0);

    }

    is->show_mode = show_mode;

    /* open the streams */

    if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {

        stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);

    }

    ret = -1;

    if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {

        ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);

    }

    if (is->show_mode == SHOW_MODE_NONE)

        is->show_mode = ret >= 0 ? SHOW_MODE_VIDEO : SHOW_MODE_RDFT;

    is->refresh_tid = SDL_CreateThread(refresh_thread, is);

    if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {

        stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);

    }

    if (is->video_stream < 0 && is->audio_stream < 0) {

        fprintf(stderr, "%s: could not open codecs\n", is->filename);

        ret = -1;

        goto fail;

    }

    if (infinite_buffer < 0 && is->realtime)

        infinite_buffer = 1;

    for (;;) {

        if (is->abort_request)

            break;

        if (is->paused != is->last_paused) {

            is->last_paused = is->paused;

            if (is->paused)

                is->read_pause_return = av_read_pause(ic);

            else

                av_read_play(ic);

        }

#if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL

        if (is->paused &&

                (!strcmp(ic->iformat->name, "rtsp") ||

                 (ic->pb && !strncmp(input_filename, "mmsh:", 5)))) {

            /* wait 10 ms to avoid trying to get another packet */

            /* XXX: horrible */

            SDL_Delay(10);

            continue;

        }

#endif

        if (is->seek_req) {

            int64_t seek_target = is->seek_pos;

            int64_t seek_min    = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;

            int64_t seek_max    = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;

// FIXME the +-2 is due to rounding being not done in the correct direction in generation

//      of the seek_pos/seek_rel variables

            ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);

            if (ret < 0) {

                fprintf(stderr, "%s: error while seeking\n", is->ic->filename);

            } else {

                if (is->audio_stream >= 0) {

                    packet_queue_flush(&is->audioq);

                    packet_queue_put(&is->audioq, &flush_pkt);

                }

                if (is->subtitle_stream >= 0) {

                    packet_queue_flush(&is->subtitleq);

                    packet_queue_put(&is->subtitleq, &flush_pkt);

                }

                if (is->video_stream >= 0) {

                    packet_queue_flush(&is->videoq);

                    packet_queue_put(&is->videoq, &flush_pkt);

                }

                if (is->seek_flags & AVSEEK_FLAG_BYTE) {

                   //FIXME: use a cleaner way to signal obsolete external clock...

                   update_external_clock_pts(is, (double)AV_NOPTS_VALUE);

                } else {

                   update_external_clock_pts(is, seek_target / (double)AV_TIME_BASE);

                }

            }

            is->seek_req = 0;

            eof = 0;

            if (is->paused)

                step_to_next_frame(is);

        }

        if (is->queue_attachments_req) {

            avformat_queue_attached_pictures(ic);

            is->queue_attachments_req = 0;

        }

        /* if the queue are full, no need to read more */

        if (infinite_buffer<1 &&

              (is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE

            || (   (is->audioq   .nb_packets > MIN_FRAMES || is->audio_stream < 0 || is->audioq.abort_request)

                && (is->videoq   .nb_packets > MIN_FRAMES || is->video_stream < 0 || is->videoq.abort_request)

                && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream < 0 || is->subtitleq.abort_request)))) {

            /* wait 10 ms */

            SDL_LockMutex(wait_mutex);

            SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);

            SDL_UnlockMutex(wait_mutex);

            continue;

        }

        if (eof) {

            if (is->video_stream >= 0) {

                av_init_packet(pkt);

                pkt->data = NULL;

                pkt->size = 0;

                pkt->stream_index = is->video_stream;

                packet_queue_put(&is->videoq, pkt);

            }

            if (is->audio_stream >= 0 &&

                is->audio_st->codec->codec->capabilities & CODEC_CAP_DELAY) {

                av_init_packet(pkt);

                pkt->data = NULL;

                pkt->size = 0;

                pkt->stream_index = is->audio_stream;

                packet_queue_put(&is->audioq, pkt);

            }

            SDL_Delay(10);

            if (is->audioq.size + is->videoq.size + is->subtitleq.size == 0) {

                if (loop != 1 && (!loop || --loop)) {

                    stream_seek(is, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);

                } else if (autoexit) {

                    ret = AVERROR_EOF;

                    goto fail;

                }

            }

            eof=0;

            continue;

        }

        ret = av_read_frame(ic, pkt);

        if (ret < 0) {

            if (ret == AVERROR_EOF || url_feof(ic->pb))

                eof = 1;

            if (ic->pb && ic->pb->error)

                break;

            SDL_LockMutex(wait_mutex);

            SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);

            SDL_UnlockMutex(wait_mutex);

            continue;

        }

        /* check if packet is in play range specified by user, then queue, otherwise discard */

        pkt_in_play_range = duration == AV_NOPTS_VALUE ||

                (pkt->pts - ic->streams[pkt->stream_index]->start_time) *

                av_q2d(ic->streams[pkt->stream_index]->time_base) -

                (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000

                <= ((double)duration / 1000000);

        if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {

            packet_queue_put(&is->audioq, pkt);

        } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {

            packet_queue_put(&is->videoq, pkt);

        } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {

            packet_queue_put(&is->subtitleq, pkt);

        } else {

            av_free_packet(pkt);

        }

    }

    /* wait until the end */

    while (!is->abort_request) {

        SDL_Delay(100);

    }

    ret = 0;

 fail:

    /* close each stream */

    if (is->audio_stream >= 0)

        stream_component_close(is, is->audio_stream);

    if (is->video_stream >= 0)

        stream_component_close(is, is->video_stream);

    if (is->subtitle_stream >= 0)

        stream_component_close(is, is->subtitle_stream);

    if (is->ic) {

        avformat_close_input(&is->ic);

    }

    if (ret != 0) {

        SDL_Event event;

        event.type = FF_QUIT_EVENT;

        event.user.data1 = is;

        SDL_PushEvent(&event);

    }

    SDL_DestroyMutex(wait_mutex);

    return 0;

}


int ff_xvmc_field_start(MpegEncContext *s, AVCodecContext *avctx)

{

    struct xvmc_pix_fmt *last, *next, *render = (struct xvmc_pix_fmt*)s->current_picture.data[2];

    const int mb_block_count = 4 + (1 << s->chroma_format);

    assert(avctx);

    if (!render || render->xvmc_id != AV_XVMC_ID ||

        !render->data_blocks || !render->mv_blocks) {

        av_log(avctx, AV_LOG_ERROR,

               "Render token doesn't look as expected.\n");

        return -1; // make sure that this is a render packet

    }

    if (render->filled_mv_blocks_num) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface contains %i unprocessed blocks.\n",

               render->filled_mv_blocks_num);

        return -1;

    }

    if (render->allocated_mv_blocks   < 1 ||

        render->allocated_data_blocks <  render->allocated_mv_blocks*mb_block_count ||

        render->start_mv_blocks_num   >= render->allocated_mv_blocks                ||

        render->next_free_data_block_num >

                        render->allocated_data_blocks -

                        mb_block_count*(render->allocated_mv_blocks-render->start_mv_blocks_num)) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface doesn't provide enough block structures to work with.\n");

        return -1;

    }

    render->picture_structure = s->picture_structure;

    render->flags             = s->first_field ? 0 : XVMC_SECOND_FIELD;

    render->p_future_surface  = NULL;

    render->p_past_surface    = NULL;

    switch(s->pict_type) {

        case  FF_I_TYPE:

            return 0; // no prediction from other frames

        case  FF_B_TYPE:

            next = (struct xvmc_pix_fmt*)s->next_picture.data[2];

            if (!next)

                return -1;

            if (next->xvmc_id != AV_XVMC_ID)

                return -1;

            render->p_future_surface = next->p_surface;

            // no return here, going to set forward prediction

        case  FF_P_TYPE:

            last = (struct xvmc_pix_fmt*)s->last_picture.data[2];

            if (!last)

                last = render; // predict second field from the first

            if (last->xvmc_id != AV_XVMC_ID)

                return -1;

            render->p_past_surface = last->p_surface;

            return 0;

    }

return -1;

}


static int calculate_bitrate(AVFormatContext *s)

{

    AVIContext *avi = s->priv_data;

    int i, j;

    int64_t lensum = 0;

    int64_t maxpos = 0;

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

        int64_t len = 0;

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

        if (!st->nb_index_entries)

            continue;

        for (j = 0; j < st->nb_index_entries; j++)

            len += st->index_entries[j].size;

        maxpos = FFMAX(maxpos, st->index_entries[j-1].pos);

        lensum += len;

    }

    if (maxpos < avi->io_fsize*9/10) // index does not cover the whole file

        return 0;

    if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch

        return 0;

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

        int64_t len = 0;

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

        int64_t duration;

        for (j = 0; j < st->nb_index_entries; j++)

            len += st->index_entries[j].size;

        if (st->nb_index_entries < 2 || st->codec->bit_rate > 0)

            continue;

        duration = st->index_entries[j-1].timestamp - st->index_entries[0].timestamp;

        st->codec->bit_rate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num);

    }

    return 1;

}


static inline void gen_st16(TCGv val, TCGv addr, int index)

{

    tcg_gen_qemu_st16(val, addr, index);

    dead_tmp(val);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIHostBridgeClass *hc = PCI_HOST_BRIDGE_CLASS(klass);

    hc->root_bus_path = q35_host_root_bus_path;

    dc->realize = q35_host_realize;

    dc->props = mch_props;

    /* Reason: needs to be wired up by pc_q35_init */

    dc->user_creatable = false;

    set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);

    dc->fw_name = "pci";

}


static struct addrinfo *inet_parse_connect_saddr(InetSocketAddress *saddr,

                                                 Error **errp)

{

    struct addrinfo ai, *res;

    int rc;

    Error *err = NULL;

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

    ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;

    ai.ai_family = inet_ai_family_from_address(saddr, &err);

    ai.ai_socktype = SOCK_STREAM;

    if (err) {

        error_propagate(errp, err);

        return NULL;

    }

    if (saddr->host == NULL || saddr->port == NULL) {

        error_setg(errp, "host and/or port not specified");

        return NULL;

    }

    /* lookup */

    rc = getaddrinfo(saddr->host, saddr->port, &ai, &res);

    if (rc != 0) {

        error_setg(errp, "address resolution failed for %s:%s: %s",

                   saddr->host, saddr->port, gai_strerror(rc));

        return NULL;

    }

    return res;

}


static void bamboo_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    unsigned int pci_irq_nrs[4] = { 28, 27, 26, 25 };

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *isa = g_new(MemoryRegion, 1);

    MemoryRegion *ram_memories

        = g_malloc(PPC440EP_SDRAM_NR_BANKS * sizeof(*ram_memories));

    hwaddr ram_bases[PPC440EP_SDRAM_NR_BANKS];

    hwaddr ram_sizes[PPC440EP_SDRAM_NR_BANKS];

    qemu_irq *pic;

    qemu_irq *irqs;

    PCIBus *pcibus;

    PowerPCCPU *cpu;

    CPUPPCState *env;

    uint64_t elf_entry;

    uint64_t elf_lowaddr;

    hwaddr loadaddr = 0;

    target_long initrd_size = 0;

    DeviceState *dev;

    int success;

    int i;

    /* Setup CPU. */

    if (machine->cpu_model == NULL) {

        machine->cpu_model = "440EP";

    }

    cpu = POWERPC_CPU(cpu_generic_init(TYPE_POWERPC_CPU, machine->cpu_model));

    if (cpu == NULL) {

        fprintf(stderr, "Unable to initialize CPU!\n");

        exit(1);

    }

    env = &cpu->env;

    if (env->mmu_model != POWERPC_MMU_BOOKE) {

        fprintf(stderr, "MMU model %i not supported by this machine.\n",

            env->mmu_model);

        exit(1);

    }

    qemu_register_reset(main_cpu_reset, cpu);

    ppc_booke_timers_init(cpu, 400000000, 0);

    ppc_dcr_init(env, NULL, NULL);

    /* interrupt controller */

    irqs = g_malloc0(sizeof(qemu_irq) * PPCUIC_OUTPUT_NB);

    irqs[PPCUIC_OUTPUT_INT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_INT];

    irqs[PPCUIC_OUTPUT_CINT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_CINT];

    pic = ppcuic_init(env, irqs, 0x0C0, 0, 1);

    /* SDRAM controller */

    memset(ram_bases, 0, sizeof(ram_bases));

    memset(ram_sizes, 0, sizeof(ram_sizes));

    ram_size = ppc4xx_sdram_adjust(ram_size, PPC440EP_SDRAM_NR_BANKS,

                                   ram_memories,

                                   ram_bases, ram_sizes,

                                   ppc440ep_sdram_bank_sizes);

    /* XXX 440EP's ECC interrupts are on UIC1, but we've only created UIC0. */

    ppc4xx_sdram_init(env, pic[14], PPC440EP_SDRAM_NR_BANKS, ram_memories,

                      ram_bases, ram_sizes, 1);

    /* PCI */

    dev = sysbus_create_varargs(TYPE_PPC4xx_PCI_HOST_BRIDGE,

                                PPC440EP_PCI_CONFIG,

                                pic[pci_irq_nrs[0]], pic[pci_irq_nrs[1]],

                                pic[pci_irq_nrs[2]], pic[pci_irq_nrs[3]],

                                NULL);

    pcibus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");

    if (!pcibus) {

        fprintf(stderr, "couldn't create PCI controller!\n");

        exit(1);

    }

    memory_region_init_alias(isa, NULL, "isa_mmio",

                             get_system_io(), 0, PPC440EP_PCI_IOLEN);

    memory_region_add_subregion(get_system_memory(), PPC440EP_PCI_IO, isa);

    if (serial_hds[0] != NULL) {

        serial_mm_init(address_space_mem, 0xef600300, 0, pic[0],

                       PPC_SERIAL_MM_BAUDBASE, serial_hds[0],

                       DEVICE_BIG_ENDIAN);

    }

    if (serial_hds[1] != NULL) {

        serial_mm_init(address_space_mem, 0xef600400, 0, pic[1],

                       PPC_SERIAL_MM_BAUDBASE, serial_hds[1],

                       DEVICE_BIG_ENDIAN);

    }

    if (pcibus) {

        /* Register network interfaces. */

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

            /* There are no PCI NICs on the Bamboo board, but there are

             * PCI slots, so we can pick whatever default model we want. */

            pci_nic_init_nofail(&nd_table[i], pcibus, "e1000", NULL);

        }

    }

    /* Load kernel. */

    if (kernel_filename) {

        success = load_uimage(kernel_filename, &entry, &loadaddr, NULL,

                              NULL, NULL);

        if (success < 0) {

            success = load_elf(kernel_filename, NULL, NULL, &elf_entry,

                               &elf_lowaddr, NULL, 1, PPC_ELF_MACHINE,

                               0, 0);

            entry = elf_entry;

            loadaddr = elf_lowaddr;

        }

        /* XXX try again as binary */

        if (success < 0) {

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

                    kernel_filename);

            exit(1);

        }

    }

    /* Load initrd. */

    if (initrd_filename) {

        initrd_size = load_image_targphys(initrd_filename, RAMDISK_ADDR,

                                          ram_size - RAMDISK_ADDR);

        if (initrd_size < 0) {

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

                    initrd_filename, RAMDISK_ADDR);

            exit(1);

        }

    }

    /* If we're loading a kernel directly, we must load the device tree too. */

    if (kernel_filename) {

        if (bamboo_load_device_tree(FDT_ADDR, ram_size, RAMDISK_ADDR,

                                    initrd_size, kernel_cmdline) < 0) {

            fprintf(stderr, "couldn't load device tree\n");

            exit(1);

        }

    }

}


void HELPER(stpq)(CPUS390XState *env, uint64_t addr,

                  uint64_t low, uint64_t high)

{

    uintptr_t ra = GETPC();

    if (parallel_cpus) {

#ifndef CONFIG_ATOMIC128

        cpu_loop_exit_atomic(ENV_GET_CPU(env), ra);

#else

        int mem_idx = cpu_mmu_index(env, false);

        TCGMemOpIdx oi = make_memop_idx(MO_TEQ | MO_ALIGN_16, mem_idx);

        Int128 v = int128_make128(low, high);

        helper_atomic_sto_be_mmu(env, addr, v, oi, ra);

#endif

    } else {

        check_alignment(env, addr, 16, ra);

        cpu_stq_data_ra(env, addr + 0, high, ra);

        cpu_stq_data_ra(env, addr + 8, low, ra);

    }

}


static inline void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, long width)

{

#ifdef HAVE_MMX

	asm volatile(

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

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

		"1:				\n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

		" js 1b				\n\t"

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

		: "%"REG_a

	);

#else

	int i;

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

	{

		dstU[i]= src1[4*i + 1];

		dstV[i]= src1[4*i + 3];

	}

#endif

        assert(src1 == src2);

}


static void h261_v_loop_filter_c(uint8_t *dest,uint8_t *src, int stride){

    int i,j,xy,yz;

    int res;

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

        for(j=1; j<7; j++){

            xy = j * stride + i;

            yz = j * 8 + i;

            res = (int)src[yz-1*8] + ((int)(src[yz+0*8]) * 2) + (int)src[yz+1*8];

            res +=2;

            res >>=2;

            dest[xy] = (uint8_t)res;

        }

    }

}


static inline void RENAME(uyvyToY)(uint8_t *dst, const uint8_t *src, int width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

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

        "1:                                         \n\t"

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

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

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

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

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

        "movq              %%mm0, (%2, %%"REG_a")   \n\t"

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

        " js                  1b                    \n\t"

        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)

        : "%"REG_a

    );

#else

    int i;

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

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

#endif

}


static void simple_number(void)

{

    int i;

    struct {

        const char *encoded;

        int64_t decoded;

        int skip;

    } test_cases[] = {

        { "0", 0 },

        { "1234", 1234 },

        { "1", 1 },

        { "-32", -32 },

        { "-0", 0, .skip = 1 },

        { },

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QInt *qint;

        qint = qobject_to_qint(qobject_from_json(test_cases[i].encoded, NULL));

        g_assert(qint);

        g_assert(qint_get_int(qint) == test_cases[i].decoded);

        if (test_cases[i].skip == 0) {

            QString *str;

            str = qobject_to_json(QOBJECT(qint));

            g_assert(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0);

            QDECREF(str);

        }

        QDECREF(qint);

    }

}


static int video_thread(void *arg)

{

    VideoState *is = arg;

    AVFrame *frame = avcodec_alloc_frame();

    int64_t pts_int;

    double pts;

    int ret;

#if CONFIG_AVFILTER

    AVFilterGraph *graph = avfilter_graph_alloc();

    AVFilterContext *filt_out = NULL;

    int64_t pos;

    int last_w = is->video_st->codec->width;

    int last_h = is->video_st->codec->height;

    if ((ret = configure_video_filters(graph, is, vfilters)) < 0)

        goto the_end;

    filt_out = is->out_video_filter;

#endif

    for (;;) {

#if !CONFIG_AVFILTER

        AVPacket pkt;

#else

        AVFilterBufferRef *picref;

        AVRational tb;

#endif

        while (is->paused && !is->videoq.abort_request)

            SDL_Delay(10);

#if CONFIG_AVFILTER

        if (   last_w != is->video_st->codec->width

            || last_h != is->video_st->codec->height) {

            av_dlog(NULL, "Changing size %dx%d -> %dx%d\n", last_w, last_h,

                    is->video_st->codec->width, is->video_st->codec->height);

            avfilter_graph_free(&graph);

            graph = avfilter_graph_alloc();

            if ((ret = configure_video_filters(graph, is, vfilters)) < 0)

                goto the_end;

            filt_out = is->out_video_filter;

            last_w = is->video_st->codec->width;

            last_h = is->video_st->codec->height;

        }

        ret = get_filtered_video_frame(filt_out, frame, &picref, &tb);

        if (picref) {

            pts_int = picref->pts;

            pos     = picref->pos;

            frame->opaque = picref;

        }

        if (av_cmp_q(tb, is->video_st->time_base)) {

            av_unused int64_t pts1 = pts_int;

            pts_int = av_rescale_q(pts_int, tb, is->video_st->time_base);

            av_dlog(NULL, "video_thread(): "

                    "tb:%d/%d pts:%"PRId64" -> tb:%d/%d pts:%"PRId64"\n",

                    tb.num, tb.den, pts1,

                    is->video_st->time_base.num, is->video_st->time_base.den, pts_int);

        }

#else

        ret = get_video_frame(is, frame, &pts_int, &pkt);

#endif

        if (ret < 0)

            goto the_end;

        if (!ret)

            continue;

        pts = pts_int * av_q2d(is->video_st->time_base);

#if CONFIG_AVFILTER

        ret = output_picture2(is, frame, pts, pos);

#else

        ret = output_picture2(is, frame, pts,  pkt.pos);

        av_free_packet(&pkt);

#endif

        if (ret < 0)

            goto the_end;

        if (step)

            if (cur_stream)

                stream_pause(cur_stream);

    }

 the_end:

#if CONFIG_AVFILTER

    avfilter_graph_free(&graph);

#endif

    av_free(frame);

    return 0;

}


static int ccid_initfn(USBDevice *dev)

{

    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);

    s->bus = ccid_bus_new(&dev->qdev);

    s->card = NULL;

    s->cardinfo = NULL;

    s->migration_state = MIGRATION_NONE;

    s->migration_target_ip = 0;

    s->migration_target_port = 0;

    s->dev.speed = USB_SPEED_FULL;

    s->notify_slot_change = false;

    s->powered = true;

    s->pending_answers_num = 0;

    s->last_answer_error = 0;

    s->bulk_in_pending_start = 0;

    s->bulk_in_pending_end = 0;

    s->current_bulk_in = NULL;

    ccid_reset_error_status(s);

    s->bulk_out_pos = 0;

    ccid_reset_parameters(s);

    ccid_reset(s);

    return 0;

}


static void ppc4xx_pob_reset (void *opaque)

{

    ppc4xx_pob_t *pob;

    pob = opaque;

    /* No error */

    pob->bear = 0x00000000;

    pob->besr[0] = 0x0000000;

    pob->besr[1] = 0x0000000;

}


int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)

{

    int i, j, t, rconpointer = 0;

    uint8_t tk[8][4];

    int KC = key_bits >> 5;

    int rounds = KC + 6;

    uint8_t log8[256];

    uint8_t alog8[512];

    if (!enc_multbl[FF_ARRAY_ELEMS(enc_multbl)-1][FF_ARRAY_ELEMS(enc_multbl[0])-1]) {

        j = 1;

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

            alog8[i] = alog8[i + 255] = j;

            log8[j] = i;

            j ^= j + j;

            if (j > 255)

                j ^= 0x11B;

        }

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

            j = i ? alog8[255 - log8[i]] : 0;

            j ^= (j << 1) ^ (j << 2) ^ (j << 3) ^ (j << 4);

            j = (j ^ (j >> 8) ^ 99) & 255;

            inv_sbox[j] = i;

            sbox[i] = j;

        }

        init_multbl2(dec_multbl[0], (const int[4]) { 0xe, 0x9, 0xd, 0xb },

                     log8, alog8, inv_sbox);

        init_multbl2(enc_multbl[0], (const int[4]) { 0x2, 0x1, 0x1, 0x3 },

                     log8, alog8, sbox);

    }

    if (key_bits != 128 && key_bits != 192 && key_bits != 256)

        return -1;

    a->rounds = rounds;

    memcpy(tk, key, KC * 4);

    for (t = 0; t < (rounds + 1) * 16;) {

        memcpy(a->round_key[0].u8 + t, tk, KC * 4);

        t += KC * 4;

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

            tk[0][i] ^= sbox[tk[KC - 1][(i + 1) & 3]];

        tk[0][0] ^= rcon[rconpointer++];

        for (j = 1; j < KC; j++) {

            if (KC != 8 || j != KC >> 1)

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

                    tk[j][i] ^= tk[j - 1][i];

            else

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

                    tk[j][i] ^= sbox[tk[j - 1][i]];

        }

    }

    if (decrypt) {

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

            av_aes_block tmp[3];

            tmp[2] = a->round_key[i];

            subshift(&tmp[1], 0, sbox);

            mix(tmp, dec_multbl, 1, 3);

            a->round_key[i] = tmp[0];

        }

    } else {

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

            FFSWAP(av_aes_block, a->round_key[i], a->round_key[rounds-i]);

        }

    }

    return 0;

}


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

	unsigned int width, unsigned int height,

	int lumStride, int chromStride, int dstStride)

{

	//FIXME interpolate chroma

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

}


static void spapr_populate_cpu_dt(CPUState *cs, void *fdt, int offset,

                                  sPAPRMachineState *spapr)

{

    PowerPCCPU *cpu = POWERPC_CPU(cs);

    CPUPPCState *env = &cpu->env;

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);

    int index = ppc_get_vcpu_dt_id(cpu);

    uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),

                       0xffffffff, 0xffffffff};

    uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq()

        : SPAPR_TIMEBASE_FREQ;

    uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;

    uint32_t page_sizes_prop[64];

    size_t page_sizes_prop_size;

    uint32_t vcpus_per_socket = smp_threads * smp_cores;

    uint32_t pft_size_prop[] = {0, cpu_to_be32(spapr->htab_shift)};

    int compat_smt = MIN(smp_threads, ppc_compat_max_threads(cpu));

    sPAPRDRConnector *drc;

    int drc_index;

    uint32_t radix_AP_encodings[PPC_PAGE_SIZES_MAX_SZ];

    int i;

    drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU, index);

    if (drc) {

        drc_index = spapr_drc_index(drc);

        _FDT((fdt_setprop_cell(fdt, offset, "ibm,my-drc-index", drc_index)));

    }

    _FDT((fdt_setprop_cell(fdt, offset, "reg", index)));

    _FDT((fdt_setprop_string(fdt, offset, "device_type", "cpu")));

    _FDT((fdt_setprop_cell(fdt, offset, "cpu-version", env->spr[SPR_PVR])));

    _FDT((fdt_setprop_cell(fdt, offset, "d-cache-block-size",

                           env->dcache_line_size)));

    _FDT((fdt_setprop_cell(fdt, offset, "d-cache-line-size",

                           env->dcache_line_size)));

    _FDT((fdt_setprop_cell(fdt, offset, "i-cache-block-size",

                           env->icache_line_size)));

    _FDT((fdt_setprop_cell(fdt, offset, "i-cache-line-size",

                           env->icache_line_size)));

    if (pcc->l1_dcache_size) {

        _FDT((fdt_setprop_cell(fdt, offset, "d-cache-size",

                               pcc->l1_dcache_size)));

    } else {

        error_report("Warning: Unknown L1 dcache size for cpu");

    }

    if (pcc->l1_icache_size) {

        _FDT((fdt_setprop_cell(fdt, offset, "i-cache-size",

                               pcc->l1_icache_size)));

    } else {

        error_report("Warning: Unknown L1 icache size for cpu");

    }

    _FDT((fdt_setprop_cell(fdt, offset, "timebase-frequency", tbfreq)));

    _FDT((fdt_setprop_cell(fdt, offset, "clock-frequency", cpufreq)));

    _FDT((fdt_setprop_cell(fdt, offset, "slb-size", env->slb_nr)));

    _FDT((fdt_setprop_cell(fdt, offset, "ibm,slb-size", env->slb_nr)));

    _FDT((fdt_setprop_string(fdt, offset, "status", "okay")));

    _FDT((fdt_setprop(fdt, offset, "64-bit", NULL, 0)));

    if (env->spr_cb[SPR_PURR].oea_read) {

        _FDT((fdt_setprop(fdt, offset, "ibm,purr", NULL, 0)));

    }

    if (env->mmu_model & POWERPC_MMU_1TSEG) {

        _FDT((fdt_setprop(fdt, offset, "ibm,processor-segment-sizes",

                          segs, sizeof(segs))));

    }

    /* Advertise VMX/VSX (vector extensions) if available

     *   0 / no property == no vector extensions

     *   1               == VMX / Altivec available

     *   2               == VSX available */

    if (env->insns_flags & PPC_ALTIVEC) {

        uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;

        _FDT((fdt_setprop_cell(fdt, offset, "ibm,vmx", vmx)));

    }

    /* Advertise DFP (Decimal Floating Point) if available

     *   0 / no property == no DFP

     *   1               == DFP available */

    if (env->insns_flags2 & PPC2_DFP) {

        _FDT((fdt_setprop_cell(fdt, offset, "ibm,dfp", 1)));

    }

    page_sizes_prop_size = ppc_create_page_sizes_prop(env, page_sizes_prop,

                                                  sizeof(page_sizes_prop));

    if (page_sizes_prop_size) {

        _FDT((fdt_setprop(fdt, offset, "ibm,segment-page-sizes",

                          page_sizes_prop, page_sizes_prop_size)));

    }

    spapr_populate_pa_features(env, fdt, offset, false);

    _FDT((fdt_setprop_cell(fdt, offset, "ibm,chip-id",

                           cs->cpu_index / vcpus_per_socket)));

    _FDT((fdt_setprop(fdt, offset, "ibm,pft-size",

                      pft_size_prop, sizeof(pft_size_prop))));

    if (nb_numa_nodes > 1) {

        _FDT(spapr_fixup_cpu_numa_dt(fdt, offset, cpu));

    }

    _FDT(spapr_fixup_cpu_smt_dt(fdt, offset, cpu, compat_smt));

    if (pcc->radix_page_info) {

        for (i = 0; i < pcc->radix_page_info->count; i++) {

            radix_AP_encodings[i] =

                cpu_to_be32(pcc->radix_page_info->entries[i]);

        }

        _FDT((fdt_setprop(fdt, offset, "ibm,processor-radix-AP-encodings",

                          radix_AP_encodings,

                          pcc->radix_page_info->count *

                          sizeof(radix_AP_encodings[0]))));

    }

}


static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid)

{

    XHCIState *xhci = epctx->xhci;

    XHCIStreamContext *stctx;

    XHCITransfer *xfer;

    XHCIRing *ring;

    USBEndpoint *ep = NULL;

    uint64_t mfindex;

    int length;

    int i;

    trace_usb_xhci_ep_kick(epctx->slotid, epctx->epid, streamid);

    /* If the device has been detached, but the guest has not noticed this

       yet the 2 above checks will succeed, but we must NOT continue */

    if (!xhci->slots[epctx->slotid - 1].uport ||

        !xhci->slots[epctx->slotid - 1].uport->dev ||

        !xhci->slots[epctx->slotid - 1].uport->dev->attached) {

        return;

    }

    if (epctx->retry) {

        XHCITransfer *xfer = epctx->retry;

        trace_usb_xhci_xfer_retry(xfer);

        assert(xfer->running_retry);

        if (xfer->timed_xfer) {

            /* time to kick the transfer? */

            mfindex = xhci_mfindex_get(xhci);

            xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);

            if (xfer->running_retry) {

                return;

            }

            xfer->timed_xfer = 0;

            xfer->running_retry = 1;

        }

        if (xfer->iso_xfer) {

            /* retry iso transfer */

            if (xhci_setup_packet(xfer) < 0) {

                return;

            }

            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

            assert(xfer->packet.status != USB_RET_NAK);

            xhci_complete_packet(xfer);

        } else {

            /* retry nak'ed transfer */

            if (xhci_setup_packet(xfer) < 0) {

                return;

            }

            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

            if (xfer->packet.status == USB_RET_NAK) {

                return;

            }

            xhci_complete_packet(xfer);

        }

        assert(!xfer->running_retry);

        xhci_ep_free_xfer(epctx->retry);

        epctx->retry = NULL;

    }

    if (epctx->state == EP_HALTED) {

        DPRINTF("xhci: ep halted, not running schedule\n");

        return;

    }

    if (epctx->nr_pstreams) {

        uint32_t err;

        stctx = xhci_find_stream(epctx, streamid, &err);

        if (stctx == NULL) {

            return;

        }

        ring = &stctx->ring;

        xhci_set_ep_state(xhci, epctx, stctx, EP_RUNNING);

    } else {

        ring = &epctx->ring;

        streamid = 0;

        xhci_set_ep_state(xhci, epctx, NULL, EP_RUNNING);

    }

    assert(ring->dequeue != 0);

    while (1) {

        length = xhci_ring_chain_length(xhci, ring);

        if (length <= 0) {

            break;

        }

        xfer = xhci_ep_alloc_xfer(epctx, length);

        if (xfer == NULL) {

            break;

        }

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

            TRBType type;

            type = xhci_ring_fetch(xhci, ring, &xfer->trbs[i], NULL);

            assert(type);

        }

        xfer->streamid = streamid;

        if (epctx->epid == 1) {

            xhci_fire_ctl_transfer(xhci, xfer);

        } else {

            xhci_fire_transfer(xhci, xfer, epctx);

        }

        if (xfer->complete) {

            xhci_ep_free_xfer(xfer);

            xfer = NULL;

        }

        if (epctx->state == EP_HALTED) {

            break;

        }

        if (xfer != NULL && xfer->running_retry) {

            DPRINTF("xhci: xfer nacked, stopping schedule\n");

            epctx->retry = xfer;

            break;

        }

    }

    ep = xhci_epid_to_usbep(epctx);

    if (ep) {

        usb_device_flush_ep_queue(ep->dev, ep);

    }

}


static int opt_preset(const char *opt, const char *arg)

{

    FILE *f=NULL;

    char filename[1000], tmp[1000], tmp2[1000], line[1000];

    int i;

    const char *base[3]= { getenv("HOME"),

                           "/usr/local/share",

                           "/usr/share",

                         };

    for(i=!base[0]; i<3 && !f; i++){

        snprintf(filename, sizeof(filename), "%s/%sffmpeg/%s.ffpreset", base[i], i ? "" : ".", arg);

        f= fopen(filename, "r");

        if(!f){

            char *codec_name= *opt == 'v' ? video_codec_name :

                              *opt == 'a' ? audio_codec_name :

                                            subtitle_codec_name;

            snprintf(filename, sizeof(filename), "%s/%sffmpeg/%s-%s.ffpreset", base[i],  i ? "" : ".", codec_name, arg);

            f= fopen(filename, "r");

        }

    }

    if(!f && ((arg[0]=='.' && arg[1]=='/') || arg[0]=='/' ||

              is_dos_path(arg))){

        snprintf(filename, sizeof(filename), arg);

        f= fopen(filename, "r");

    }

    if(!f){

        fprintf(stderr, "File for preset '%s' not found\n", arg);

        av_exit(1);

    }

    while(!feof(f)){

        int e= fscanf(f, "%999[^\n]\n", line) - 1;

        if(line[0] == '#' && !e)

            continue;

        e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;

        if(e){

            fprintf(stderr, "%s: Preset file invalid\n", filename);

            av_exit(1);

        }

        if(!strcmp(tmp, "acodec")){

            opt_audio_codec(tmp2);

        }else if(!strcmp(tmp, "vcodec")){

            opt_video_codec(tmp2);

        }else if(!strcmp(tmp, "scodec")){

            opt_subtitle_codec(tmp2);

        }else if(opt_default(tmp, tmp2) < 0){

            fprintf(stderr, "%s: Invalid option or argument: %s=%s\n", filename, tmp, tmp2);

            av_exit(1);

        }

    }

    fclose(f);

    return 0;

}


static int asf_read_ext_content(AVFormatContext *s, const GUIDParseTable *g)

{

    ASFContext *asf  = s->priv_data;

    AVIOContext *pb  = s->pb;

    uint64_t size    = avio_rl64(pb);

    uint16_t nb_desc = avio_rl16(pb);

    int i, ret;

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

        uint16_t name_len, type, val_len;

        uint8_t *name = NULL;

        name_len = avio_rl16(pb);

        if (!name_len)

            return AVERROR_INVALIDDATA;

        name = av_malloc(name_len);

        if (!name)

            return AVERROR(ENOMEM);

        avio_get_str16le(pb, name_len, name,

                         name_len);

        type    = avio_rl16(pb);

        val_len = avio_rl16(pb);

        if ((ret = process_metadata(s, name, name_len, val_len, type, &s->metadata)) < 0)

            return ret;

    }

    align_position(pb, asf->offset, size);

    return 0;

}


static int vhdx_log_write(BlockDriverState *bs, BDRVVHDXState *s,

                          void *data, uint32_t length, uint64_t offset)

{

    int ret = 0;

    void *buffer = NULL;

    void *merged_sector = NULL;

    void *data_tmp, *sector_write;

    unsigned int i;

    int sector_offset;

    uint32_t desc_sectors, sectors, total_length;

    uint32_t sectors_written = 0;

    uint32_t aligned_length;

    uint32_t leading_length = 0;

    uint32_t trailing_length = 0;

    uint32_t partial_sectors = 0;

    uint32_t bytes_written = 0;

    uint64_t file_offset;

    VHDXHeader *header;

    VHDXLogEntryHeader new_hdr;

    VHDXLogDescriptor *new_desc = NULL;

    VHDXLogDataSector *data_sector = NULL;

    MSGUID new_guid = { 0 };

    header = s->headers[s->curr_header];

    /* need to have offset read data, and be on 4096 byte boundary */

    if (length > header->log_length) {

        /* no log present.  we could create a log here instead of failing */

        ret = -EINVAL;

        goto exit;

    }

    if (guid_eq(header->log_guid, zero_guid)) {

        vhdx_guid_generate(&new_guid);

        vhdx_update_headers(bs, s, false, &new_guid);

    } else {

        /* currently, we require that the log be flushed after

         * every write. */

        ret = -ENOTSUP;

        goto exit;

    }

    /* 0 is an invalid sequence number, but may also represent the first

     * log write (or a wrapped seq) */

    if (s->log.sequence == 0) {

        s->log.sequence = 1;

    }

    sector_offset = offset % VHDX_LOG_SECTOR_SIZE;

    file_offset = (offset / VHDX_LOG_SECTOR_SIZE) * VHDX_LOG_SECTOR_SIZE;

    aligned_length = length;

    /* add in the unaligned head and tail bytes */

    if (sector_offset) {

        leading_length = (VHDX_LOG_SECTOR_SIZE - sector_offset);

        leading_length = leading_length > length ? length : leading_length;

        aligned_length -= leading_length;

        partial_sectors++;

    }

    sectors = aligned_length / VHDX_LOG_SECTOR_SIZE;

    trailing_length = aligned_length - (sectors * VHDX_LOG_SECTOR_SIZE);

    if (trailing_length) {

        partial_sectors++;

    }

    sectors += partial_sectors;

    /* sectors is now how many sectors the data itself takes, not

     * including the header and descriptor metadata */

    new_hdr = (VHDXLogEntryHeader) {

                .signature           = VHDX_LOG_SIGNATURE,

                .tail                = s->log.tail,

                .sequence_number     = s->log.sequence,

                .descriptor_count    = sectors,

                .reserved            = 0,

                .flushed_file_offset = bdrv_getlength(bs->file->bs),

                .last_file_offset    = bdrv_getlength(bs->file->bs),

              };

    new_hdr.log_guid = header->log_guid;

    desc_sectors = vhdx_compute_desc_sectors(new_hdr.descriptor_count);

    total_length = (desc_sectors + sectors) * VHDX_LOG_SECTOR_SIZE;

    new_hdr.entry_length = total_length;

    vhdx_log_entry_hdr_le_export(&new_hdr);

    buffer = qemu_blockalign(bs, total_length);

    memcpy(buffer, &new_hdr, sizeof(new_hdr));

    new_desc = buffer + sizeof(new_hdr);

    data_sector = buffer + (desc_sectors * VHDX_LOG_SECTOR_SIZE);

    data_tmp = data;

    /* All log sectors are 4KB, so for any partial sectors we must

     * merge the data with preexisting data from the final file

     * destination */

    merged_sector = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);

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

        new_desc->signature       = VHDX_LOG_DESC_SIGNATURE;

        new_desc->sequence_number = s->log.sequence;

        new_desc->file_offset     = file_offset;

        if (i == 0 && leading_length) {

            /* partial sector at the front of the buffer */

            ret = bdrv_pread(bs->file, file_offset, merged_sector,

                             VHDX_LOG_SECTOR_SIZE);

            if (ret < 0) {

                goto exit;

            }

            memcpy(merged_sector + sector_offset, data_tmp, leading_length);

            bytes_written = leading_length;

            sector_write = merged_sector;

        } else if (i == sectors - 1 && trailing_length) {

            /* partial sector at the end of the buffer */

            ret = bdrv_pread(bs->file,

                            file_offset,

                            merged_sector + trailing_length,

                            VHDX_LOG_SECTOR_SIZE - trailing_length);

            if (ret < 0) {

                goto exit;

            }

            memcpy(merged_sector, data_tmp, trailing_length);

            bytes_written = trailing_length;

            sector_write = merged_sector;

        } else {

            bytes_written = VHDX_LOG_SECTOR_SIZE;

            sector_write = data_tmp;

        }

        /* populate the raw sector data into the proper structures,

         * as well as update the descriptor, and convert to proper

         * endianness */

        vhdx_log_raw_to_le_sector(new_desc, data_sector, sector_write,

                                  s->log.sequence);

        data_tmp += bytes_written;

        data_sector++;

        new_desc++;

        file_offset += VHDX_LOG_SECTOR_SIZE;

    }

    /* checksum covers entire entry, from the log header through the

     * last data sector */

    vhdx_update_checksum(buffer, total_length,

                         offsetof(VHDXLogEntryHeader, checksum));

    /* now write to the log */

    ret = vhdx_log_write_sectors(bs, &s->log, &sectors_written, buffer,

                                 desc_sectors + sectors);

    if (ret < 0) {

        goto exit;

    }

    if (sectors_written != desc_sectors + sectors) {

        /* instead of failing, we could flush the log here */

        ret = -EINVAL;

        goto exit;

    }

    s->log.sequence++;

    /* write new tail */

    s->log.tail = s->log.write;

exit:

    qemu_vfree(buffer);

    qemu_vfree(merged_sector);

    return ret;

}


static void vmxnet3_net_uninit(VMXNET3State *s)

{

    g_free(s->mcast_list);

    vmxnet_tx_pkt_reset(s->tx_pkt);

    vmxnet_tx_pkt_uninit(s->tx_pkt);

    vmxnet_rx_pkt_uninit(s->rx_pkt);

    qemu_del_nic(s->nic);

}


static int http_prepare_data(HTTPContext *c)

{

    int i;

    switch(c->state) {

    case HTTPSTATE_SEND_DATA_HEADER:

        memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));

        if (c->stream->feed) {

            /* open output stream by using specified codecs */

            c->fmt_ctx.oformat = c->stream->fmt;

            c->fmt_ctx.nb_streams = c->stream->nb_streams;

            for(i=0;i<c->fmt_ctx.nb_streams;i++) {

                AVStream *st;

                st = av_mallocz(sizeof(AVStream));

                c->fmt_ctx.streams[i] = st;

                if (c->stream->feed == c->stream)

                    memcpy(st, c->stream->streams[i], sizeof(AVStream));

                else

                    memcpy(st, c->stream->feed->streams[c->stream->feed_streams[i]], sizeof(AVStream));

                st->codec.frame_number = 0; /* XXX: should be done in

                                               AVStream, not in codec */

            }

            c->got_key_frame = 0;

        } else {

            /* open output stream by using codecs in specified file */

            c->fmt_ctx.oformat = c->stream->fmt;

            c->fmt_ctx.nb_streams = c->fmt_in->nb_streams;

            for(i=0;i<c->fmt_ctx.nb_streams;i++) {

                AVStream *st;

                st = av_mallocz(sizeof(AVStream));

                c->fmt_ctx.streams[i] = st;

                memcpy(st, c->fmt_in->streams[i], sizeof(AVStream));

                st->codec.frame_number = 0; /* XXX: should be done in

                                               AVStream, not in codec */

            }

            c->got_key_frame = 0;

        }

        init_put_byte(&c->fmt_ctx.pb, c->pbuffer, PACKET_MAX_SIZE,

                      1, c, NULL, http_write_packet, NULL);

        c->fmt_ctx.pb.is_streamed = 1;

        /* prepare header */

        av_write_header(&c->fmt_ctx);

        c->state = HTTPSTATE_SEND_DATA;

        c->last_packet_sent = 0;

        break;

    case HTTPSTATE_SEND_DATA:

        /* find a new packet */

#if 0

        fifo_total_size = http_fifo_write_count - c->last_http_fifo_write_count;

        if (fifo_total_size >= ((3 * FIFO_MAX_SIZE) / 4)) {

            /* overflow : resync. We suppose that wptr is at this

               point a pointer to a valid packet */

            c->rptr = http_fifo.wptr;

            c->got_key_frame = 0;

        }

        start_rptr = c->rptr;

        if (fifo_read(&http_fifo, (UINT8 *)&hdr, sizeof(hdr), &c->rptr) < 0)

            return 0;

        payload_size = ntohs(hdr.payload_size);

        payload = av_malloc(payload_size);

        if (fifo_read(&http_fifo, payload, payload_size, &c->rptr) < 0) {

            /* cannot read all the payload */

            av_free(payload);

            c->rptr = start_rptr;

            return 0;

        }

        c->last_http_fifo_write_count = http_fifo_write_count -

            fifo_size(&http_fifo, c->rptr);

        if (c->stream->stream_type != STREAM_TYPE_MASTER) {

            /* test if the packet can be handled by this format */

            ret = 0;

            for(i=0;i<c->fmt_ctx.nb_streams;i++) {

                AVStream *st = c->fmt_ctx.streams[i];

                if (test_header(&hdr, &st->codec)) {

                    /* only begin sending when got a key frame */

                    if (st->codec.key_frame)

                        c->got_key_frame |= 1 << i;

                    if (c->got_key_frame & (1 << i)) {

                        ret = c->fmt_ctx.format->write_packet(&c->fmt_ctx, i,

                                                                   payload, payload_size);

                    }

                    break;

                }

            }

            if (ret) {

                /* must send trailer now */

                c->state = HTTPSTATE_SEND_DATA_TRAILER;

            }

        } else {

            /* master case : send everything */

            char *q;

            q = c->buffer;

            memcpy(q, &hdr, sizeof(hdr));

            q += sizeof(hdr);

            memcpy(q, payload, payload_size);

            q += payload_size;

            c->buffer_ptr = c->buffer;

            c->buffer_end = q;

        }

        av_free(payload);

#endif

        {

            AVPacket pkt;

            /* read a packet from the input stream */

            if (c->stream->feed) {

                ffm_set_write_index(c->fmt_in,

                                    c->stream->feed->feed_write_index,

                                    c->stream->feed->feed_size);

            }

            if (av_read_packet(c->fmt_in, &pkt) < 0) {

                if (c->stream->feed && c->stream->feed->feed_opened) {

                    /* if coming from feed, it means we reached the end of the

                       ffm file, so must wait for more data */

                    c->state = HTTPSTATE_WAIT_FEED;

                    return 1; /* state changed */

                } else {

                    /* must send trailer now because eof or error */

                    c->state = HTTPSTATE_SEND_DATA_TRAILER;

                }

            } else {

                /* send it to the appropriate stream */

                if (c->stream->feed) {

                    /* if coming from a feed, select the right stream */

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

                        if (c->stream->feed_streams[i] == pkt.stream_index) {

                            pkt.stream_index = i;

                            if (pkt.flags & PKT_FLAG_KEY) {

                                c->got_key_frame |= 1 << i;

                            }

                            /* See if we have all the key frames, then

                             * we start to send. This logic is not quite

                             * right, but it works for the case of a

                             * single video stream with one or more

                             * audio streams (for which every frame is

                             * typically a key frame).

                             */

                            if (!c->stream->send_on_key || ((c->got_key_frame + 1) >> c->stream->nb_streams)) {

                                goto send_it;

                            }

                        }

                    }

                } else {

                    AVCodecContext *codec;

                send_it:

                    /* Fudge here */

                    codec = &c->fmt_ctx.streams[pkt.stream_index]->codec;

                    codec->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);

#ifdef PJSG

                    if (codec->codec_type == CODEC_TYPE_AUDIO) {

                        codec->frame_size = (codec->sample_rate * pkt.duration + 500000) / 1000000;

                        /* printf("Calculated size %d, from sr %d, duration %d\n", codec->frame_size, codec->sample_rate, pkt.duration); */

                    }

#endif

                    if (av_write_packet(&c->fmt_ctx, &pkt, 0))

                        c->state = HTTPSTATE_SEND_DATA_TRAILER;

                    codec->frame_number++;

                }

                av_free_packet(&pkt);

            }

        }

        break;

    default:

    case HTTPSTATE_SEND_DATA_TRAILER:

        /* last packet test ? */

        if (c->last_packet_sent)

            return -1;

        /* prepare header */

        av_write_trailer(&c->fmt_ctx);

        c->last_packet_sent = 1;

        break;

    }

    return 0;

}


static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)

{

    if (!buffer->cmd) {

        AVBufferRef *buf = buffer->user_data;

        av_buffer_unref(&buf);

    }

    mmal_buffer_header_release(buffer);

}


CPUArchState *cpu_copy(CPUArchState *env)

{

    CPUState *cpu = ENV_GET_CPU(env);

    CPUState *new_cpu = cpu_init(cpu_model);

    CPUArchState *new_env = cpu->env_ptr;

    CPUBreakpoint *bp;

    CPUWatchpoint *wp;

    /* Reset non arch specific state */

    cpu_reset(new_cpu);

    memcpy(new_env, env, sizeof(CPUArchState));

    /* Clone all break/watchpoints.

       Note: Once we support ptrace with hw-debug register access, make sure

       BP_CPU break/watchpoints are handled correctly on clone. */

    QTAILQ_INIT(&cpu->breakpoints);

    QTAILQ_INIT(&cpu->watchpoints);

    QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {

        cpu_breakpoint_insert(new_cpu, bp->pc, bp->flags, NULL);

    }

    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {

        cpu_watchpoint_insert(new_cpu, wp->vaddr, wp->len, wp->flags, NULL);

    }

    return new_env;

}


static void avc_luma_vt_and_aver_dst_16x16_msa(const uint8_t *src,

                                               int32_t src_stride,

                                               uint8_t *dst, int32_t dst_stride)

{

    int32_t loop_cnt;

    int16_t filt_const0 = 0xfb01;

    int16_t filt_const1 = 0x1414;

    int16_t filt_const2 = 0x1fb;

    v16u8 dst0, dst1, dst2, dst3;

    v16i8 src0, src1, src2, src3, src4, src5, src6, src7, src8;

    v16i8 src10_r, src32_r, src54_r, src76_r, src21_r, src43_r, src65_r;

    v16i8 src87_r, src10_l, src32_l, src54_l, src76_l, src21_l, src43_l;

    v16i8 src65_l, src87_l;

    v8i16 out0_r, out1_r, out2_r, out3_r, out0_l, out1_l, out2_l, out3_l;

    v16i8 filt0, filt1, filt2;

    v16u8 res0, res1, res2, res3;

    filt0 = (v16i8) __msa_fill_h(filt_const0);

    filt1 = (v16i8) __msa_fill_h(filt_const1);

    filt2 = (v16i8) __msa_fill_h(filt_const2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    ILVR_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3,

               src10_r, src21_r, src32_r, src43_r);

    ILVL_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3,

               src10_l, src21_l, src32_l, src43_l);

    for (loop_cnt = 4; loop_cnt--;) {

        LD_SB4(src, src_stride, src5, src6, src7, src8);

        src += (4 * src_stride);

        XORI_B4_128_SB(src5, src6, src7, src8);

        ILVR_B4_SB(src5, src4, src6, src5, src7, src6, src8, src7,

                   src54_r, src65_r, src76_r, src87_r);

        ILVL_B4_SB(src5, src4, src6, src5, src7, src6, src8, src7,

                   src54_l, src65_l, src76_l, src87_l);

        out0_r = DPADD_SH3_SH(src10_r, src32_r, src54_r, filt0, filt1, filt2);

        out1_r = DPADD_SH3_SH(src21_r, src43_r, src65_r, filt0, filt1, filt2);

        out2_r = DPADD_SH3_SH(src32_r, src54_r, src76_r, filt0, filt1, filt2);

        out3_r = DPADD_SH3_SH(src43_r, src65_r, src87_r, filt0, filt1, filt2);

        out0_l = DPADD_SH3_SH(src10_l, src32_l, src54_l, filt0, filt1, filt2);

        out1_l = DPADD_SH3_SH(src21_l, src43_l, src65_l, filt0, filt1, filt2);

        out2_l = DPADD_SH3_SH(src32_l, src54_l, src76_l, filt0, filt1, filt2);

        out3_l = DPADD_SH3_SH(src43_l, src65_l, src87_l, filt0, filt1, filt2);

        SRARI_H4_SH(out0_r, out1_r, out2_r, out3_r, 5);

        SRARI_H4_SH(out0_l, out1_l, out2_l, out3_l, 5);

        SAT_SH4_SH(out0_r, out1_r, out2_r, out3_r, 7);

        SAT_SH4_SH(out0_l, out1_l, out2_l, out3_l, 7);

        LD_UB4(dst, dst_stride, dst0, dst1, dst2, dst3);

        PCKEV_B4_UB(out0_l, out0_r, out1_l, out1_r, out2_l, out2_r, out3_l,

                    out3_r, res0, res1, res2, res3);

        XORI_B4_128_UB(res0, res1, res2, res3);

        AVER_UB4_UB(res0, dst0, res1, dst1, res2, dst2, res3, dst3,

                    res0, res1, res2, res3);

        ST_UB4(res0, res1, res2, res3, dst, dst_stride);

        dst += (4 * dst_stride);

        src10_r = src54_r;

        src32_r = src76_r;

        src21_r = src65_r;

        src43_r = src87_r;

        src10_l = src54_l;

        src32_l = src76_l;

        src21_l = src65_l;

        src43_l = src87_l;

        src4 = src8;

    }

}


static int net_socket_can_send(void *opaque)

{

    NetSocketState *s = opaque;

    return qemu_can_send_packet(&s->nc);

}