static int rm_read_audio_stream_info(AVFormatContext *s, AVIOContext *pb,

                                     AVStream *st, RMStream *ast, int read_all)

{

    char buf[256];

    uint32_t version;

    int ret;

    /* ra type header */

    version = avio_rb16(pb); /* version */

    if (version == 3) {

        int header_size = avio_rb16(pb);

        int64_t startpos = avio_tell(pb);

        avio_skip(pb, 14);

        rm_read_metadata(s, 0);

        if ((startpos + header_size) >= avio_tell(pb) + 2) {

            // fourcc (should always be "lpcJ")

            avio_r8(pb);

            get_str8(pb, buf, sizeof(buf));

        }

        // Skip extra header crap (this should never happen)

        if ((startpos + header_size) > avio_tell(pb))

            avio_skip(pb, header_size + startpos - avio_tell(pb));

        st->codec->sample_rate = 8000;

        st->codec->channels = 1;

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id = CODEC_ID_RA_144;

        ast->deint_id = DEINT_ID_INT0;

    } else {

        int flavor, sub_packet_h, coded_framesize, sub_packet_size;

        int codecdata_length;

        /* old version (4) */

        avio_skip(pb, 2); /* unused */

        avio_rb32(pb); /* .ra4 */

        avio_rb32(pb); /* data size */

        avio_rb16(pb); /* version2 */

        avio_rb32(pb); /* header size */

        flavor= avio_rb16(pb); /* add codec info / flavor */

        ast->coded_framesize = coded_framesize = avio_rb32(pb); /* coded frame size */

        avio_rb32(pb); /* ??? */

        avio_rb32(pb); /* ??? */

        avio_rb32(pb); /* ??? */

        ast->sub_packet_h = sub_packet_h = avio_rb16(pb); /* 1 */

        st->codec->block_align= avio_rb16(pb); /* frame size */

        ast->sub_packet_size = sub_packet_size = avio_rb16(pb); /* sub packet size */

        avio_rb16(pb); /* ??? */

        if (version == 5) {

            avio_rb16(pb); avio_rb16(pb); avio_rb16(pb);

        }

        st->codec->sample_rate = avio_rb16(pb);

        avio_rb32(pb);

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

        if (version == 5) {

            ast->deint_id = avio_rl32(pb);

            avio_read(pb, buf, 4);

            buf[4] = 0;

        } else {

            get_str8(pb, buf, sizeof(buf)); /* desc */

            ast->deint_id = AV_RL32(buf);

            get_str8(pb, buf, sizeof(buf)); /* desc */

        }

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_tag  = AV_RL32(buf);

        st->codec->codec_id   = ff_codec_get_id(ff_rm_codec_tags,

                                                st->codec->codec_tag);

        switch (ast->deint_id) {

        case DEINT_ID_GENR:

        case DEINT_ID_INT0:

        case DEINT_ID_INT4:

        case DEINT_ID_SIPR:

        case DEINT_ID_VBRS:

        case DEINT_ID_VBRF:

            break;

        default:

            av_log(NULL,0,"Unknown interleaver %X\n", ast->deint_id);

            return AVERROR_INVALIDDATA;

        }

        switch (st->codec->codec_id) {

        case CODEC_ID_AC3:

            st->need_parsing = AVSTREAM_PARSE_FULL;

            break;

        case CODEC_ID_RA_288:

            st->codec->extradata_size= 0;

            ast->audio_framesize = st->codec->block_align;

            st->codec->block_align = coded_framesize;

            if(ast->audio_framesize >= UINT_MAX / sub_packet_h){

                av_log(s, AV_LOG_ERROR, "ast->audio_framesize * sub_packet_h too large\n");

                return -1;

            }

            av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h);

            break;

        case CODEC_ID_COOK:

        case CODEC_ID_ATRAC3:

        case CODEC_ID_SIPR:

            avio_rb16(pb); avio_r8(pb);

            if (version == 5)

                avio_r8(pb);

            codecdata_length = avio_rb32(pb);

            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){

                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");

                return -1;

            }

            ast->audio_framesize = st->codec->block_align;

            if (st->codec->codec_id == CODEC_ID_SIPR) {

                if (flavor > 3) {

                    av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",

                           flavor);

                    return -1;

                }

                st->codec->block_align = ff_sipr_subpk_size[flavor];

            } else {

                if(sub_packet_size <= 0){

                    av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");

                    return -1;

                }

                st->codec->block_align = ast->sub_packet_size;

            }

            if ((ret = rm_read_extradata(pb, st->codec, codecdata_length)) < 0)

                return ret;

            if(ast->audio_framesize >= UINT_MAX / sub_packet_h){

                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");

                return -1;

            }

            av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h);

            break;

        case CODEC_ID_AAC:

            avio_rb16(pb); avio_r8(pb);

            if (version == 5)

                avio_r8(pb);

            codecdata_length = avio_rb32(pb);

            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){

                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");

                return -1;

            }

            if (codecdata_length >= 1) {

                avio_r8(pb);

                if ((ret = rm_read_extradata(pb, st->codec, codecdata_length - 1)) < 0)

                    return ret;

            }

            break;

        default:

            av_strlcpy(st->codec->codec_name, buf, sizeof(st->codec->codec_name));

        }

        if (read_all) {

            avio_r8(pb);

            avio_r8(pb);

            avio_r8(pb);

            rm_read_metadata(s, 0);

        }

    }

    return 0;

}


SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun,

                          uint8_t *buf, void *hba_private)

{

    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, d->qdev.parent_bus);

    SCSIRequest *req;

    SCSICommand cmd;

    if (scsi_req_parse(&cmd, d, buf) != 0) {

        trace_scsi_req_parse_bad(d->id, lun, tag, buf[0]);

        req = scsi_req_alloc(&reqops_invalid_opcode, d, tag, lun, hba_private);

    } else {

        trace_scsi_req_parsed(d->id, lun, tag, buf[0],

                              cmd.mode, cmd.xfer);

        if (req->cmd.lba != -1) {

            trace_scsi_req_parsed_lba(d->id, lun, tag, buf[0],

                                      cmd.lba);

        }

        if ((d->unit_attention.key == UNIT_ATTENTION ||

             bus->unit_attention.key == UNIT_ATTENTION) &&

            (buf[0] != INQUIRY &&

             buf[0] != REPORT_LUNS &&

             buf[0] != GET_CONFIGURATION &&

             buf[0] != GET_EVENT_STATUS_NOTIFICATION)) {

            req = scsi_req_alloc(&reqops_unit_attention, d, tag, lun,

                                 hba_private);

        } else if (lun != d->lun ||

            buf[0] == REPORT_LUNS ||

            buf[0] == REQUEST_SENSE) {

            req = scsi_req_alloc(&reqops_target_command, d, tag, lun,

                                 hba_private);

        } else {

            req = d->info->alloc_req(d, tag, lun, hba_private);

        }

    }

    req->cmd = cmd;

    switch (buf[0]) {

    case INQUIRY:

        trace_scsi_inquiry(d->id, lun, tag, cmd.buf[1], cmd.buf[2]);

        break;

    case TEST_UNIT_READY:

        trace_scsi_test_unit_ready(d->id, lun, tag);

        break;

    case REPORT_LUNS:

        trace_scsi_report_luns(d->id, lun, tag);

        break;

    case REQUEST_SENSE:

        trace_scsi_request_sense(d->id, lun, tag);

        break;

    default:

        break;

    }

    return req;

}


av_cold int ff_msmpeg4_decode_init(AVCodecContext *avctx)
{
    MpegEncContext *s = avctx->priv_data;
    static volatile int done = 0;
    int i;
    MVTable *mv;
    if (ff_h263_decode_init(avctx) < 0)
    ff_msmpeg4_common_init(s);
    if (!done) {
        for(i=0;i<NB_RL_TABLES;i++) {
            ff_init_rl(&ff_rl_table[i], ff_static_rl_table_store[i]);
        INIT_VLC_RL(ff_rl_table[0], 642);
        INIT_VLC_RL(ff_rl_table[1], 1104);
        INIT_VLC_RL(ff_rl_table[2], 554);
        INIT_VLC_RL(ff_rl_table[3], 940);
        INIT_VLC_RL(ff_rl_table[4], 962);
        INIT_VLC_RL(ff_rl_table[5], 554);
        mv = &ff_mv_tables[0];
        INIT_VLC_STATIC(&mv->vlc, MV_VLC_BITS, mv->n + 1,
                    mv->table_mv_bits, 1, 1,
                    mv->table_mv_code, 2, 2, 3714);
        mv = &ff_mv_tables[1];
        INIT_VLC_STATIC(&mv->vlc, MV_VLC_BITS, mv->n + 1,
                    mv->table_mv_bits, 1, 1,
                    mv->table_mv_code, 2, 2, 2694);
        INIT_VLC_STATIC(&ff_msmp4_dc_luma_vlc[0], DC_VLC_BITS, 120,
                 &ff_table0_dc_lum[0][1], 8, 4,
                 &ff_table0_dc_lum[0][0], 8, 4, 1158);
        INIT_VLC_STATIC(&ff_msmp4_dc_chroma_vlc[0], DC_VLC_BITS, 120,
                 &ff_table0_dc_chroma[0][1], 8, 4,
                 &ff_table0_dc_chroma[0][0], 8, 4, 1118);
        INIT_VLC_STATIC(&ff_msmp4_dc_luma_vlc[1], DC_VLC_BITS, 120,
                 &ff_table1_dc_lum[0][1], 8, 4,
                 &ff_table1_dc_lum[0][0], 8, 4, 1476);
        INIT_VLC_STATIC(&ff_msmp4_dc_chroma_vlc[1], DC_VLC_BITS, 120,
                 &ff_table1_dc_chroma[0][1], 8, 4,
                 &ff_table1_dc_chroma[0][0], 8, 4, 1216);
        INIT_VLC_STATIC(&v2_dc_lum_vlc, DC_VLC_BITS, 512,
                 &ff_v2_dc_lum_table[0][1], 8, 4,
                 &ff_v2_dc_lum_table[0][0], 8, 4, 1472);
        INIT_VLC_STATIC(&v2_dc_chroma_vlc, DC_VLC_BITS, 512,
                 &ff_v2_dc_chroma_table[0][1], 8, 4,
                 &ff_v2_dc_chroma_table[0][0], 8, 4, 1506);
        INIT_VLC_STATIC(&v2_intra_cbpc_vlc, V2_INTRA_CBPC_VLC_BITS, 4,
                 &ff_v2_intra_cbpc[0][1], 2, 1,
                 &ff_v2_intra_cbpc[0][0], 2, 1, 8);
        INIT_VLC_STATIC(&v2_mb_type_vlc, V2_MB_TYPE_VLC_BITS, 8,
                 &ff_v2_mb_type[0][1], 2, 1,
                 &ff_v2_mb_type[0][0], 2, 1, 128);
        INIT_VLC_STATIC(&v2_mv_vlc, V2_MV_VLC_BITS, 33,
                 &ff_mvtab[0][1], 2, 1,
                 &ff_mvtab[0][0], 2, 1, 538);
        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[0], MB_NON_INTRA_VLC_BITS, 128,
                     &ff_wmv2_inter_table[0][0][1], 8, 4,
                     &ff_wmv2_inter_table[0][0][0], 8, 4, 1636);
        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[1], MB_NON_INTRA_VLC_BITS, 128,
                     &ff_wmv2_inter_table[1][0][1], 8, 4,
                     &ff_wmv2_inter_table[1][0][0], 8, 4, 2648);
        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[2], MB_NON_INTRA_VLC_BITS, 128,
                     &ff_wmv2_inter_table[2][0][1], 8, 4,
                     &ff_wmv2_inter_table[2][0][0], 8, 4, 1532);
        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[3], MB_NON_INTRA_VLC_BITS, 128,
                     &ff_wmv2_inter_table[3][0][1], 8, 4,
                     &ff_wmv2_inter_table[3][0][0], 8, 4, 2488);
        INIT_VLC_STATIC(&ff_msmp4_mb_i_vlc, MB_INTRA_VLC_BITS, 64,
                 &ff_msmp4_mb_i_table[0][1], 4, 2,
                 &ff_msmp4_mb_i_table[0][0], 4, 2, 536);
        INIT_VLC_STATIC(&ff_inter_intra_vlc, INTER_INTRA_VLC_BITS, 4,
                 &ff_table_inter_intra[0][1], 2, 1,
                 &ff_table_inter_intra[0][0], 2, 1, 8);
        done = 1;
    switch(s->msmpeg4_version){
    case 1:
    case 2:
        s->decode_mb= msmpeg4v12_decode_mb;
        break;
    case 3:
    case 4:
        s->decode_mb= msmpeg4v34_decode_mb;
        break;
    case 5:
        if (CONFIG_WMV2_DECODER)
            s->decode_mb= ff_wmv2_decode_mb;
    case 6:
        //FIXME + TODO VC1 decode mb
        break;
    s->slice_height= s->mb_height; //to avoid 1/0 if the first frame is not a keyframe
    return 0;


void qemu_thread_exit(void *arg)

{

    QemuThread *thread = TlsGetValue(qemu_thread_tls_index);

    thread->ret = arg;

    CloseHandle(thread->thread);

    thread->thread = NULL;

    ExitThread(0);

}


int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);

    AVPicture dummy_pict;

    int ret;

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

        return ret;

    if (desc->flags & PIX_FMT_PSEUDOPAL)

        // do not include palette for these pseudo-paletted formats

        return width * height;

    return avpicture_fill(&dummy_pict, NULL, pix_fmt, width, height);

}


static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
                     Error **errp)
{
    BDRVQcowState *s = bs->opaque;
    int len, i, shift, ret;
    QCowHeader header;
    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
    if (ret < 0) {
    be32_to_cpus(&header.magic);
    be32_to_cpus(&header.version);
    be64_to_cpus(&header.backing_file_offset);
    be32_to_cpus(&header.backing_file_size);
    be32_to_cpus(&header.mtime);
    be64_to_cpus(&header.size);
    be32_to_cpus(&header.crypt_method);
    be64_to_cpus(&header.l1_table_offset);
    if (header.magic != QCOW_MAGIC) {
        error_setg(errp, "Image not in qcow format");
    if (header.version != QCOW_VERSION) {
        char version[64];
        snprintf(version, sizeof(version), "QCOW version %" PRIu32,
                 header.version);
        error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
                  bs->device_name, "qcow", version);
        ret = -ENOTSUP;
    if (header.size <= 1) {
        error_setg(errp, "Image size is too small (must be at least 2 bytes)");
    if (header.cluster_bits < 9 || header.cluster_bits > 16) {
        error_setg(errp, "Cluster size must be between 512 and 64k");
    if (header.crypt_method > QCOW_CRYPT_AES) {
        error_setg(errp, "invalid encryption method in qcow header");
    s->crypt_method_header = header.crypt_method;
    if (s->crypt_method_header) {
        bs->encrypted = 1;
    s->cluster_bits = header.cluster_bits;
    s->cluster_size = 1 << s->cluster_bits;
    s->cluster_sectors = 1 << (s->cluster_bits - 9);
    s->l2_bits = header.l2_bits;
    s->l2_size = 1 << s->l2_bits;
    bs->total_sectors = header.size / 512;
    s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
    /* read the level 1 table */
    shift = s->cluster_bits + s->l2_bits;
    s->l1_size = (header.size + (1LL << shift) - 1) >> shift;
    s->l1_table_offset = header.l1_table_offset;
    s->l1_table = g_malloc(s->l1_size * sizeof(uint64_t));
    ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
               s->l1_size * sizeof(uint64_t));
    if (ret < 0) {
    for(i = 0;i < s->l1_size; i++) {
        be64_to_cpus(&s->l1_table[i]);
    /* alloc L2 cache */
    s->l2_cache = g_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
    s->cluster_cache = g_malloc(s->cluster_size);
    s->cluster_data = g_malloc(s->cluster_size);
    s->cluster_cache_offset = -1;
    /* read the backing file name */
    if (header.backing_file_offset != 0) {
        len = header.backing_file_size;
        if (len > 1023) {
            len = 1023;
        ret = bdrv_pread(bs->file, header.backing_file_offset,
                   bs->backing_file, len);
        if (ret < 0) {
        bs->backing_file[len] = '\0';
    /* Disable migration when qcow images are used */
    error_set(&s->migration_blocker,
              QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
              "qcow", bs->device_name, "live migration");
    migrate_add_blocker(s->migration_blocker);
    qemu_co_mutex_init(&s->lock);
    return 0;
 fail:
    g_free(s->l1_table);
    g_free(s->l2_cache);
    g_free(s->cluster_cache);
    g_free(s->cluster_data);
    return ret;


void OPPROTO op_idivw_AX_T0(void)

{

    int num, den, q, r;

    num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);

    den = (int16_t)T0;

    if (den == 0) {

        raise_exception(EXCP00_DIVZ);

    }

    q = (num / den) & 0xffff;

    r = (num % den) & 0xffff;

    EAX = (EAX & ~0xffff) | q;

    EDX = (EDX & ~0xffff) | r;

}


static always_inline void gen_op_subfco_64 (void)

{

    gen_op_move_T2_T0();

    gen_op_subf();

    gen_op_check_subfc_64();

    gen_op_check_subfo_64();

}


static av_cold int wmv2_encode_init(AVCodecContext *avctx){

    Wmv2Context * const w= avctx->priv_data;

    if(ff_MPV_encode_init(avctx) < 0)

        return -1;

    ff_wmv2_common_init(w);

    avctx->extradata_size= 4;

    avctx->extradata= av_mallocz(avctx->extradata_size + 10);

    encode_ext_header(w);

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    ARMGICCommonClass *agcc = ARM_GIC_COMMON_CLASS(klass);

    KVMARMGICClass *kgc = KVM_ARM_GIC_CLASS(klass);

    agcc->pre_save = kvm_arm_gic_get;

    agcc->post_load = kvm_arm_gic_put;

    kgc->parent_realize = dc->realize;

    kgc->parent_reset = dc->reset;

    dc->realize = kvm_arm_gic_realize;

    dc->reset = kvm_arm_gic_reset;

    dc->no_user = 1;

}


test_tls_get_ipaddr(const char *addrstr,

                    char **data,

                    int *datalen)

{

    struct addrinfo *res;

    struct addrinfo hints;

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

    hints.ai_flags = AI_NUMERICHOST;

    g_assert(getaddrinfo(addrstr, NULL, &hints, &res) == 0);

    *datalen = res->ai_addrlen;

    *data = g_new(char, *datalen);

    memcpy(*data, res->ai_addr, *datalen);

}


static int adaptive_cb_search(const int16_t *adapt_cb, float *work,

                              const float *coefs, float *data)

{

    int i, best_vect;

    float score, gain, best_score, best_gain;

    float exc[BLOCKSIZE];

    gain = best_score = 0;

    for (i = BLOCKSIZE / 2; i <= BUFFERSIZE; i++) {

        create_adapt_vect(exc, adapt_cb, i);

        get_match_score(work, coefs, exc, NULL, NULL, data, &score, &gain);

        if (score > best_score) {

            best_score = score;

            best_vect = i;

            best_gain = gain;

        }

    }

    if (!best_score)

        return 0;

    /**

     * Re-calculate the filtered vector from the vector with maximum match score

     * and remove its contribution from input data.

     */

    create_adapt_vect(exc, adapt_cb, best_vect);

    ff_celp_lp_synthesis_filterf(work, coefs, exc, BLOCKSIZE, LPC_ORDER);

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

        data[i] -= best_gain * work[i];

    return best_vect - BLOCKSIZE / 2 + 1;

}


static void pc_cpu_plug(HotplugHandler *hotplug_dev,

                        DeviceState *dev, Error **errp)

{

    CPUArchId *found_cpu;

    HotplugHandlerClass *hhc;

    Error *local_err = NULL;

    PCMachineState *pcms = PC_MACHINE(hotplug_dev);

    if (pcms->acpi_dev) {

        hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev);

        hhc->plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);

        if (local_err) {

            goto out;

        }

    }

    /* increment the number of CPUs */

    pcms->boot_cpus++;

    if (dev->hotplugged) {

        rtc_set_cpus_count(pcms->rtc, pcms->boot_cpus);

        fw_cfg_modify_i16(pcms->fw_cfg, FW_CFG_NB_CPUS, pcms->boot_cpus);

    }

    found_cpu = pc_find_cpu_slot(pcms, CPU(dev), NULL);

    found_cpu->cpu = CPU(dev);

out:

    error_propagate(errp, local_err);

}


static int transcode(void)

{

    int ret, i;

    AVFormatContext *is, *os;

    OutputStream *ost;

    InputStream *ist;

    uint8_t *no_packet;

    int no_packet_count = 0;

    int64_t timer_start;

    if (!(no_packet = av_mallocz(nb_input_files)))

        exit_program(1);

    ret = transcode_init();

    if (ret < 0)

        goto fail;

    av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");

    term_init();

    timer_start = av_gettime();

    for (; received_sigterm == 0;) {

        int file_index, ist_index, past_recording_time = 1;

        AVPacket pkt;

        int64_t ipts_min;

        ipts_min = INT64_MAX;

        /* check if there's any stream where output is still needed */

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

            OutputFile *of;

            ost = output_streams[i];

            of  = output_files[ost->file_index];

            os  = output_files[ost->file_index]->ctx;

            if (ost->is_past_recording_time ||

                (os->pb && avio_tell(os->pb) >= of->limit_filesize))

                continue;

            if (ost->frame_number > ost->max_frames) {

                int j;

                for (j = 0; j < of->ctx->nb_streams; j++)

                    output_streams[of->ost_index + j]->is_past_recording_time = 1;

                continue;

            }

            past_recording_time = 0;

        }

        if (past_recording_time)

            break;

        /* select the stream that we must read now by looking at the

           smallest output pts */

        file_index = -1;

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

            int64_t ipts;

            ist = input_streams[i];

            ipts = ist->last_dts;

            if (ist->discard || no_packet[ist->file_index])

                continue;

            if (!input_files[ist->file_index]->eof_reached) {

                if (ipts < ipts_min) {

                    ipts_min = ipts;

                    file_index = ist->file_index;

                }

            }

        }

        /* if none, if is finished */

        if (file_index < 0) {

            if (no_packet_count) {

                no_packet_count = 0;

                memset(no_packet, 0, nb_input_files);

                usleep(10000);

                continue;

            }

            break;

        }

        /* read a frame from it and output it in the fifo */

        is  = input_files[file_index]->ctx;

        ret = av_read_frame(is, &pkt);

        if (ret == AVERROR(EAGAIN)) {

            no_packet[file_index] = 1;

            no_packet_count++;

            continue;

        }

        if (ret < 0) {

            input_files[file_index]->eof_reached = 1;

            for (i = 0; i < input_files[file_index]->nb_streams; i++) {

                ist = input_streams[input_files[file_index]->ist_index + i];

                if (ist->decoding_needed)

                    output_packet(ist, NULL);

            }

            if (opt_shortest)

                break;

            else

                continue;

        }

        no_packet_count = 0;

        memset(no_packet, 0, nb_input_files);

        if (do_pkt_dump) {

            av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,

                             is->streams[pkt.stream_index]);

        }

        /* the following test is needed in case new streams appear

           dynamically in stream : we ignore them */

        if (pkt.stream_index >= input_files[file_index]->nb_streams)

            goto discard_packet;

        ist_index = input_files[file_index]->ist_index + pkt.stream_index;

        ist = input_streams[ist_index];

        if (ist->discard)

            goto discard_packet;

        if (pkt.dts != AV_NOPTS_VALUE)

            pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);

        if (pkt.pts != AV_NOPTS_VALUE)

            pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);

        if (pkt.pts != AV_NOPTS_VALUE)

            pkt.pts *= ist->ts_scale;

        if (pkt.dts != AV_NOPTS_VALUE)

            pkt.dts *= ist->ts_scale;

        //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",

        //        ist->next_dts,

        //        pkt.dts, input_files[ist->file_index].ts_offset,

        //        ist->st->codec->codec_type);

        if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE

            && (is->iformat->flags & AVFMT_TS_DISCONT)) {

            int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);

            int64_t delta   = pkt_dts - ist->next_dts;

            if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {

                input_files[ist->file_index]->ts_offset -= delta;

                av_log(NULL, AV_LOG_DEBUG,

                       "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",

                       delta, input_files[ist->file_index]->ts_offset);

                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

                if (pkt.pts != AV_NOPTS_VALUE)

                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

            }

        }

        // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);

        if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",

                   ist->file_index, ist->st->index);

            if (exit_on_error)

                exit_program(1);

            av_free_packet(&pkt);

            continue;

        }

    discard_packet:

        av_free_packet(&pkt);

        /* dump report by using the output first video and audio streams */

        print_report(0, timer_start);

    }

    /* at the end of stream, we must flush the decoder buffers */

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

        ist = input_streams[i];

        if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {

            output_packet(ist, NULL);

        }

    }

    poll_filters();

    flush_encoders();

    term_exit();

    /* write the trailer if needed and close file */

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

        os = output_files[i]->ctx;

        av_write_trailer(os);

    }

    /* dump report by using the first video and audio streams */

    print_report(1, timer_start);

    /* close each encoder */

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

        ost = output_streams[i];

        if (ost->encoding_needed) {

            av_freep(&ost->st->codec->stats_in);

            avcodec_close(ost->st->codec);

        }

    }

    /* close each decoder */

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

        ist = input_streams[i];

        if (ist->decoding_needed) {

            avcodec_close(ist->st->codec);

        }

    }

    /* finished ! */

    ret = 0;

 fail:

    av_freep(&no_packet);

    if (output_streams) {

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

            ost = output_streams[i];

            if (ost) {

                if (ost->stream_copy)

                    av_freep(&ost->st->codec->extradata);

                if (ost->logfile) {

                    fclose(ost->logfile);

                    ost->logfile = NULL;

                }

                av_fifo_free(ost->fifo); /* works even if fifo is not

                                             initialized but set to zero */

                av_freep(&ost->st->codec->subtitle_header);

                av_free(ost->forced_kf_pts);

                if (ost->avr)

                    avresample_free(&ost->avr);

                av_dict_free(&ost->opts);

            }

        }

    }

    return ret;

}


static void pc_dimm_plug(HotplugHandler *hotplug_dev,

                         DeviceState *dev, Error **errp)

{

    HotplugHandlerClass *hhc;

    Error *local_err = NULL;

    PCMachineState *pcms = PC_MACHINE(hotplug_dev);

    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);

    PCDIMMDevice *dimm = PC_DIMM(dev);

    PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);

    MemoryRegion *mr = ddc->get_memory_region(dimm);

    uint64_t align = TARGET_PAGE_SIZE;

    bool is_nvdimm = object_dynamic_cast(OBJECT(dev), TYPE_NVDIMM);

    if (memory_region_get_alignment(mr) && pcmc->enforce_aligned_dimm) {

        align = memory_region_get_alignment(mr);

    }

    if (!pcms->acpi_dev) {

        error_setg(&local_err,

                   "memory hotplug is not enabled: missing acpi device");

        goto out;

    }

    if (is_nvdimm && !pcms->acpi_nvdimm_state.is_enabled) {

        error_setg(&local_err,

                   "nvdimm is not enabled: missing 'nvdimm' in '-M'");

        goto out;

    }

    pc_dimm_memory_plug(dev, &pcms->hotplug_memory, mr, align, &local_err);

    if (local_err) {

        goto out;

    }

    if (is_nvdimm) {

        nvdimm_plug(&pcms->acpi_nvdimm_state);

    }

    hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev);

    hhc->plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &error_abort);

out:

    error_propagate(errp, local_err);

}


static inline void doVertLowPass_altivec(uint8_t *src, int stride, PPContext *c) {

    /*

    this code makes no assumption on src or stride.

    One could remove the recomputation of the perm

    vector by assuming (stride % 16) == 0, unfortunately

    this is not always true. Quite a lot of load/stores

    can be removed by assuming proper alignment of

    src & stride :-(

    */

    uint8_t *src2 = src;

    const vector signed int zero = vec_splat_s32(0);

    const int properStride = (stride % 16);

    const int srcAlign = ((unsigned long)src2 % 16);

    DECLARE_ALIGNED(16, short, qp[8]) = {c->QP};

    vector signed short vqp = vec_ld(0, qp);

    vector signed short vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7, vb8, vb9;

    vector unsigned char vbA0, vbA1, vbA2, vbA3, vbA4, vbA5, vbA6, vbA7, vbA8, vbA9;

    vector unsigned char vbB0, vbB1, vbB2, vbB3, vbB4, vbB5, vbB6, vbB7, vbB8, vbB9;

    vector unsigned char vbT0, vbT1, vbT2, vbT3, vbT4, vbT5, vbT6, vbT7, vbT8, vbT9;

    vector unsigned char perml0, perml1, perml2, perml3, perml4,

                         perml5, perml6, perml7, perml8, perml9;

    register int j0 = 0,

                 j1 = stride,

                 j2 = 2 * stride,

                 j3 = 3 * stride,

                 j4 = 4 * stride,

                 j5 = 5 * stride,

                 j6 = 6 * stride,

                 j7 = 7 * stride,

                 j8 = 8 * stride,

                 j9 = 9 * stride;

    vqp = vec_splat(vqp, 0);

    src2 += stride*3;

#define LOAD_LINE(i)                                                    \

    perml##i = vec_lvsl(i * stride, src2);                              \

    vbA##i = vec_ld(i * stride, src2);                                  \

    vbB##i = vec_ld(i * stride + 16, src2);                             \

    vbT##i = vec_perm(vbA##i, vbB##i, perml##i);                        \

    vb##i =                                                             \

        (vector signed short)vec_mergeh((vector unsigned char)zero,     \

                                        (vector unsigned char)vbT##i)

#define LOAD_LINE_ALIGNED(i)                                            \

    vbT##i = vec_ld(j##i, src2);                                        \

    vb##i =                                                             \

        (vector signed short)vec_mergeh((vector signed char)zero,       \

                                        (vector signed char)vbT##i)

      /* Special-casing the aligned case is worthwhile, as all calls from

       * the (transposed) horizontable deblocks will be aligned, in addition

       * to the naturally aligned vertical deblocks. */

    if (properStride && srcAlign) {

          LOAD_LINE_ALIGNED(0);

          LOAD_LINE_ALIGNED(1);

          LOAD_LINE_ALIGNED(2);

          LOAD_LINE_ALIGNED(3);

          LOAD_LINE_ALIGNED(4);

          LOAD_LINE_ALIGNED(5);

          LOAD_LINE_ALIGNED(6);

          LOAD_LINE_ALIGNED(7);

          LOAD_LINE_ALIGNED(8);

          LOAD_LINE_ALIGNED(9);

    } else {

          LOAD_LINE(0);

          LOAD_LINE(1);

          LOAD_LINE(2);

          LOAD_LINE(3);

          LOAD_LINE(4);

          LOAD_LINE(5);

          LOAD_LINE(6);

          LOAD_LINE(7);

          LOAD_LINE(8);

          LOAD_LINE(9);

    }

#undef LOAD_LINE

#undef LOAD_LINE_ALIGNED

    {

        const vector unsigned short v_2 = vec_splat_u16(2);

        const vector unsigned short v_4 = vec_splat_u16(4);

        const vector signed short v_diff01 = vec_sub(vb0, vb1);

        const vector unsigned short v_cmp01 =

            (const vector unsigned short) vec_cmplt(vec_abs(v_diff01), vqp);

        const vector signed short v_first = vec_sel(vb1, vb0, v_cmp01);

        const vector signed short v_diff89 = vec_sub(vb8, vb9);

        const vector unsigned short v_cmp89 =

            (const vector unsigned short) vec_cmplt(vec_abs(v_diff89), vqp);

        const vector signed short v_last = vec_sel(vb8, vb9, v_cmp89);

        const vector signed short temp01 = vec_mladd(v_first, (vector signed short)v_4, vb1);

        const vector signed short temp02 = vec_add(vb2, vb3);

        const vector signed short temp03 = vec_add(temp01, (vector signed short)v_4);

        const vector signed short v_sumsB0 = vec_add(temp02, temp03);

        const vector signed short temp11 = vec_sub(v_sumsB0, v_first);

        const vector signed short v_sumsB1 = vec_add(temp11, vb4);

        const vector signed short temp21 = vec_sub(v_sumsB1, v_first);

        const vector signed short v_sumsB2 = vec_add(temp21, vb5);

        const vector signed short temp31 = vec_sub(v_sumsB2, v_first);

        const vector signed short v_sumsB3 = vec_add(temp31, vb6);

        const vector signed short temp41 = vec_sub(v_sumsB3, v_first);

        const vector signed short v_sumsB4 = vec_add(temp41, vb7);

        const vector signed short temp51 = vec_sub(v_sumsB4, vb1);

        const vector signed short v_sumsB5 = vec_add(temp51, vb8);

        const vector signed short temp61 = vec_sub(v_sumsB5, vb2);

        const vector signed short v_sumsB6 = vec_add(temp61, v_last);

        const vector signed short temp71 = vec_sub(v_sumsB6, vb3);

        const vector signed short v_sumsB7 = vec_add(temp71, v_last);

        const vector signed short temp81 = vec_sub(v_sumsB7, vb4);

        const vector signed short v_sumsB8 = vec_add(temp81, v_last);

        const vector signed short temp91 = vec_sub(v_sumsB8, vb5);

        const vector signed short v_sumsB9 = vec_add(temp91, v_last);

    #define COMPUTE_VR(i, j, k)                                             \

        const vector signed short temps1##i =                               \

            vec_add(v_sumsB##i, v_sumsB##k);                                \

        const vector signed short temps2##i =                               \

            vec_mladd(vb##j, (vector signed short)v_2, temps1##i);          \

        const vector signed short  vr##j = vec_sra(temps2##i, v_4)

        COMPUTE_VR(0, 1, 2);

        COMPUTE_VR(1, 2, 3);

        COMPUTE_VR(2, 3, 4);

        COMPUTE_VR(3, 4, 5);

        COMPUTE_VR(4, 5, 6);

        COMPUTE_VR(5, 6, 7);

        COMPUTE_VR(6, 7, 8);

        COMPUTE_VR(7, 8, 9);

        const vector signed char neg1 = vec_splat_s8(-1);

        const vector unsigned char permHH = (const vector unsigned char){0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,

                                                                         0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};

#define PACK_AND_STORE(i)                                       \

{   const vector unsigned char perms##i =                       \

        vec_lvsr(i * stride, src2);                             \

    const vector unsigned char vf##i =                          \

        vec_packsu(vr##i, (vector signed short)zero);           \

    const vector unsigned char vg##i =                          \

        vec_perm(vf##i, vbT##i, permHH);                        \

    const vector unsigned char mask##i =                        \

        vec_perm((vector unsigned char)zero, (vector unsigned char)neg1, perms##i); \

    const vector unsigned char vg2##i =                         \

        vec_perm(vg##i, vg##i, perms##i);                       \

    const vector unsigned char svA##i =                         \

        vec_sel(vbA##i, vg2##i, mask##i);                       \

    const vector unsigned char svB##i =                         \

        vec_sel(vg2##i, vbB##i, mask##i);                       \

    vec_st(svA##i, i * stride, src2);                           \

    vec_st(svB##i, i * stride + 16, src2);}

#define PACK_AND_STORE_ALIGNED(i)                               \

{   const vector unsigned char vf##i =                          \

        vec_packsu(vr##i, (vector signed short)zero);           \

    const vector unsigned char vg##i =                          \

        vec_perm(vf##i, vbT##i, permHH);                        \

    vec_st(vg##i, i * stride, src2);}

        /* Special-casing the aligned case is worthwhile, as all calls from

         * the (transposed) horizontable deblocks will be aligned, in addition

         * to the naturally aligned vertical deblocks. */

        if (properStride && srcAlign) {

            PACK_AND_STORE_ALIGNED(1)

            PACK_AND_STORE_ALIGNED(2)

            PACK_AND_STORE_ALIGNED(3)

            PACK_AND_STORE_ALIGNED(4)

            PACK_AND_STORE_ALIGNED(5)

            PACK_AND_STORE_ALIGNED(6)

            PACK_AND_STORE_ALIGNED(7)

            PACK_AND_STORE_ALIGNED(8)

        } else {

            PACK_AND_STORE(1)

            PACK_AND_STORE(2)

            PACK_AND_STORE(3)

            PACK_AND_STORE(4)

            PACK_AND_STORE(5)

            PACK_AND_STORE(6)

            PACK_AND_STORE(7)

            PACK_AND_STORE(8)

        }

    #undef PACK_AND_STORE

    #undef PACK_AND_STORE_ALIGNED

    }

}


static void decode_hrd(HEVCContext *s, int common_inf_present,

                       int max_sublayers)

{

    GetBitContext *gb = &s->HEVClc.gb;

    int nal_params_present = 0, vcl_params_present = 0;

    int subpic_params_present = 0;

    int i;

    if (common_inf_present) {

        nal_params_present = get_bits1(gb);

        vcl_params_present = get_bits1(gb);

        if (nal_params_present || vcl_params_present) {

            subpic_params_present = get_bits1(gb);

            if (subpic_params_present) {

                skip_bits(gb, 8); // tick_divisor_minus2

                skip_bits(gb, 5); // du_cpb_removal_delay_increment_length_minus1

                skip_bits(gb, 1); // sub_pic_cpb_params_in_pic_timing_sei_flag

                skip_bits(gb, 5); // dpb_output_delay_du_length_minus1

            }

            skip_bits(gb, 4); // bit_rate_scale

            skip_bits(gb, 4); // cpb_size_scale

            if (subpic_params_present)

                skip_bits(gb, 4);  // cpb_size_du_scale

            skip_bits(gb, 5); // initial_cpb_removal_delay_length_minus1

            skip_bits(gb, 5); // au_cpb_removal_delay_length_minus1

            skip_bits(gb, 5); // dpb_output_delay_length_minus1

        }

    }

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

        int low_delay = 0;

        int nb_cpb = 1;

        int fixed_rate = get_bits1(gb);

        if (!fixed_rate)

            fixed_rate = get_bits1(gb);

        if (fixed_rate)

            get_ue_golomb_long(gb);  // elemental_duration_in_tc_minus1

        else

            low_delay = get_bits1(gb);

        if (!low_delay)

            nb_cpb = get_ue_golomb_long(gb) + 1;

        if (nal_params_present)

            decode_sublayer_hrd(s, nb_cpb, subpic_params_present);

        if (vcl_params_present)

            decode_sublayer_hrd(s, nb_cpb, subpic_params_present);

    }

}


static uint8_t eepro100_read1(EEPRO100State * s, uint32_t addr)

{

    uint8_t val;

    if (addr <= sizeof(s->mem) - sizeof(val)) {

        memcpy(&val, &s->mem[addr], sizeof(val));

    }

    switch (addr) {

    case SCBStatus:

    case SCBAck:

        TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));

        break;

    case SCBCmd:

        TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));

#if 0

        val = eepro100_read_command(s);

#endif

        break;

    case SCBIntmask:

        TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));

        break;

    case SCBPort + 3:

        TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));

        break;

    case SCBeeprom:

        val = eepro100_read_eeprom(s);

        break;

    case SCBpmdr:       /* Power Management Driver Register */

        val = 0;

        TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));

        break;

    case SCBgstat:      /* General Status Register */

        /* 100 Mbps full duplex, valid link */

        val = 0x07;

        TRACE(OTHER, logout("addr=General Status val=%02x\n", val));

        break;

    default:

        logout("addr=%s val=0x%02x\n", regname(addr), val);

        missing("unknown byte read");

    }

    return val;

}


void qmp_migrate_set_parameters(MigrationParameters *params, Error **errp)

{

    MigrationState *s = migrate_get_current();

    if (params->has_compress_level &&

        (params->compress_level < 0 || params->compress_level > 9)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",

                   "is invalid, it should be in the range of 0 to 9");

    }

    if (params->has_compress_threads &&

        (params->compress_threads < 1 || params->compress_threads > 255)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "compress_threads",

                   "is invalid, it should be in the range of 1 to 255");

    }

    if (params->has_decompress_threads &&

        (params->decompress_threads < 1 || params->decompress_threads > 255)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "decompress_threads",

                   "is invalid, it should be in the range of 1 to 255");

    }

    if (params->has_cpu_throttle_initial &&

        (params->cpu_throttle_initial < 1 ||

         params->cpu_throttle_initial > 99)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "cpu_throttle_initial",

                   "an integer in the range of 1 to 99");

    }

    if (params->has_cpu_throttle_increment &&

        (params->cpu_throttle_increment < 1 ||

         params->cpu_throttle_increment > 99)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "cpu_throttle_increment",

                   "an integer in the range of 1 to 99");

    }

    if (params->has_compress_level) {

        s->parameters.compress_level = params->compress_level;

    }

    if (params->has_compress_threads) {

        s->parameters.compress_threads = params->compress_threads;

    }

    if (params->has_decompress_threads) {

        s->parameters.decompress_threads = params->decompress_threads;

    }

    if (params->has_cpu_throttle_initial) {

        s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;

    }

    if (params->has_cpu_throttle_increment) {

        s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;

    }

    if (params->has_tls_creds) {

        g_free(s->parameters.tls_creds);

        s->parameters.tls_creds = g_strdup(params->tls_creds);

    }

    if (params->has_tls_hostname) {

        g_free(s->parameters.tls_hostname);

        s->parameters.tls_hostname = g_strdup(params->tls_hostname);

    }

}


static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)

{

    GetBitContext *gb = &vc->gb;

    int i,j,k;

    vc->floor_count = get_bits(gb, 6) + 1;

    vc->floors = av_mallocz(vc->floor_count * sizeof(*vc->floors));

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

        vorbis_floor *floor_setup = &vc->floors[i];

        floor_setup->floor_type = get_bits(gb, 16);

        av_dlog(NULL, " %d. floor type %d \n", i, floor_setup->floor_type);

        if (floor_setup->floor_type == 1) {

            int maximum_class = -1;

            unsigned rangebits, rangemax, floor1_values = 2;

            floor_setup->decode = vorbis_floor1_decode;

            floor_setup->data.t1.partitions = get_bits(gb, 5);

            av_dlog(NULL, " %d.floor: %d partitions \n",

                    i, floor_setup->data.t1.partitions);

            for (j = 0; j < floor_setup->data.t1.partitions; ++j) {

                floor_setup->data.t1.partition_class[j] = get_bits(gb, 4);

                if (floor_setup->data.t1.partition_class[j] > maximum_class)

                    maximum_class = floor_setup->data.t1.partition_class[j];

                av_dlog(NULL, " %d. floor %d partition class %d \n",

                        i, j, floor_setup->data.t1.partition_class[j]);

            av_dlog(NULL, " maximum class %d \n", maximum_class);

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

                floor_setup->data.t1.class_dimensions[j] = get_bits(gb, 3) + 1;

                floor_setup->data.t1.class_subclasses[j] = get_bits(gb, 2);

                av_dlog(NULL, " %d floor %d class dim: %d subclasses %d \n", i, j,

                        floor_setup->data.t1.class_dimensions[j],

                        floor_setup->data.t1.class_subclasses[j]);

                if (floor_setup->data.t1.class_subclasses[j]) {

                    GET_VALIDATED_INDEX(floor_setup->data.t1.class_masterbook[j], 8, vc->codebook_count)

                    av_dlog(NULL, "   masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);

                for (k = 0; k < (1 << floor_setup->data.t1.class_subclasses[j]); ++k) {

                    int16_t bits = get_bits(gb, 8) - 1;

                    if (bits != -1)

                        VALIDATE_INDEX(bits, vc->codebook_count)

                    floor_setup->data.t1.subclass_books[j][k] = bits;

                    av_dlog(NULL, "    book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);

            floor_setup->data.t1.multiplier = get_bits(gb, 2) + 1;

            floor_setup->data.t1.x_list_dim = 2;

            for (j = 0; j < floor_setup->data.t1.partitions; ++j)

                floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];

            floor_setup->data.t1.list = av_mallocz(floor_setup->data.t1.x_list_dim *

                                                   sizeof(*floor_setup->data.t1.list));

            rangebits = get_bits(gb, 4);

            rangemax = (1 << rangebits);

            if (rangemax > vc->blocksize[1] / 2) {

                       "Floor value is too large for blocksize: %u (%"PRIu32")\n",

                       rangemax, vc->blocksize[1] / 2);

            floor_setup->data.t1.list[0].x = 0;

            floor_setup->data.t1.list[1].x = rangemax;

            for (j = 0; j < floor_setup->data.t1.partitions; ++j) {

                for (k = 0; k < floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]]; ++k, ++floor1_values) {

                    floor_setup->data.t1.list[floor1_values].x = get_bits(gb, rangebits);

                    av_dlog(NULL, " %u. floor1 Y coord. %d\n", floor1_values,

                            floor_setup->data.t1.list[floor1_values].x);

// Precalculate order of x coordinates - needed for decode

            if (ff_vorbis_ready_floor1_list(vc->avccontext,

                                            floor_setup->data.t1.list,

                                            floor_setup->data.t1.x_list_dim)) {

        } else if (floor_setup->floor_type == 0) {

            unsigned max_codebook_dim = 0;

            floor_setup->decode = vorbis_floor0_decode;

            floor_setup->data.t0.order          = get_bits(gb,  8);

            floor_setup->data.t0.rate           = get_bits(gb, 16);

            floor_setup->data.t0.bark_map_size  = get_bits(gb, 16);

            floor_setup->data.t0.amplitude_bits = get_bits(gb,  6);

            /* zero would result in a div by zero later *

             * 2^0 - 1 == 0                             */

            if (floor_setup->data.t0.amplitude_bits == 0) {

                       "Floor 0 amplitude bits is 0.\n");

            floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);

            floor_setup->data.t0.num_books        = get_bits(gb, 4) + 1;

            /* allocate mem for booklist */

            floor_setup->data.t0.book_list =

                av_malloc(floor_setup->data.t0.num_books);

            if (!floor_setup->data.t0.book_list)

                return AVERROR(ENOMEM);

            /* read book indexes */

            {

                int idx;

                unsigned book_idx;

                for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {

                    GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)

                    floor_setup->data.t0.book_list[idx] = book_idx;

                    if (vc->codebooks[book_idx].dimensions > max_codebook_dim)

                        max_codebook_dim = vc->codebooks[book_idx].dimensions;

            create_map(vc, i);

            /* codebook dim is for padding if codebook dim doesn't *

             * divide order+1 then we need to read more data       */

            floor_setup->data.t0.lsp =

                av_malloc((floor_setup->data.t0.order + 1 + max_codebook_dim)

                          * sizeof(*floor_setup->data.t0.lsp));

            if (!floor_setup->data.t0.lsp)

                return AVERROR(ENOMEM);

            /* debug output parsed headers */

            av_dlog(NULL, "floor0 order: %u\n", floor_setup->data.t0.order);

            av_dlog(NULL, "floor0 rate: %u\n", floor_setup->data.t0.rate);

            av_dlog(NULL, "floor0 bark map size: %u\n",

                    floor_setup->data.t0.bark_map_size);

            av_dlog(NULL, "floor0 amplitude bits: %u\n",

                    floor_setup->data.t0.amplitude_bits);

            av_dlog(NULL, "floor0 amplitude offset: %u\n",

                    floor_setup->data.t0.amplitude_offset);

            av_dlog(NULL, "floor0 number of books: %u\n",

                    floor_setup->data.t0.num_books);

            av_dlog(NULL, "floor0 book list pointer: %p\n",

                    floor_setup->data.t0.book_list);

            {

                int idx;

                for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {

                    av_dlog(NULL, "  Book %d: %u\n", idx + 1,

                            floor_setup->data.t0.book_list[idx]);

        } else {

            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");

    return 0;


static void ppc_core99_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;

    const char *boot_device = machine->boot_order;

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    char *filename;

    qemu_irq *pic, **openpic_irqs;

    MemoryRegion *isa = g_new(MemoryRegion, 1);

    MemoryRegion *unin_memory = g_new(MemoryRegion, 1);

    MemoryRegion *unin2_memory = g_new(MemoryRegion, 1);

    int linux_boot, i, j, k;

    MemoryRegion *ram = g_new(MemoryRegion, 1), *bios = g_new(MemoryRegion, 1);

    hwaddr kernel_base, initrd_base, cmdline_base = 0;

    long kernel_size, initrd_size;

    PCIBus *pci_bus;

    PCIDevice *macio;

    MACIOIDEState *macio_ide;

    BusState *adb_bus;

    MacIONVRAMState *nvr;

    int bios_size, ndrv_size;

    uint8_t *ndrv_file;

    MemoryRegion *pic_mem, *escc_mem;

    MemoryRegion *escc_bar = g_new(MemoryRegion, 1);

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    void *fw_cfg;

    int machine_arch;

    SysBusDevice *s;

    DeviceState *dev;

    int *token = g_new(int, 1);

    hwaddr nvram_addr = 0xFFF04000;

    uint64_t tbfreq;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (machine->cpu_model == NULL) {

#ifdef TARGET_PPC64

        machine->cpu_model = "970fx";

#else

        machine->cpu_model = "G4";

#endif

    }

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

        cpu = POWERPC_CPU(cpu_generic_init(TYPE_POWERPC_CPU,

                                           machine->cpu_model));

        if (cpu == NULL) {

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

            exit(1);

        }

        env = &cpu->env;

        /* Set time-base frequency to 100 Mhz */

        cpu_ppc_tb_init(env, TBFREQ);

        qemu_register_reset(ppc_core99_reset, cpu);

    }

    /* allocate RAM */

    memory_region_allocate_system_memory(ram, NULL, "ppc_core99.ram", ram_size);

    memory_region_add_subregion(get_system_memory(), 0, ram);

    /* allocate and load BIOS */

    memory_region_init_ram(bios, NULL, "ppc_core99.bios", BIOS_SIZE,

                           &error_fatal);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    memory_region_set_readonly(bios, true);

    memory_region_add_subregion(get_system_memory(), PROM_ADDR, bios);

    /* Load OpenBIOS (ELF) */

    if (filename) {

        bios_size = load_elf(filename, NULL, NULL, NULL,

                             NULL, NULL, 1, PPC_ELF_MACHINE, 0, 0);

        g_free(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        error_report("could not load PowerPC bios '%s'", bios_name);

        exit(1);

    }

    if (linux_boot) {

        uint64_t lowaddr = 0;

        int bswap_needed;

#ifdef BSWAP_NEEDED

        bswap_needed = 1;

#else

        bswap_needed = 0;

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,

                               NULL, &lowaddr, NULL, 1, PPC_ELF_MACHINE,

                               0, 0);

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, kernel_base,

                                    ram_size - kernel_base, bswap_needed,

                                    TARGET_PAGE_SIZE);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              kernel_base,

                                              ram_size - kernel_base);

        if (kernel_size < 0) {

            error_report("could not load kernel '%s'", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                error_report("could not load initial ram disk '%s'",

                             initrd_filename);

                exit(1);

            }

            cmdline_base = round_page(initrd_base + initrd_size);

        } else {

            initrd_base = 0;

            initrd_size = 0;

            cmdline_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* We consider that NewWorld PowerMac never have any floppy drive

         * For now, OHW cannot boot from the network.

         */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'c' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    /* Register 8 MB of ISA IO space */

    memory_region_init_alias(isa, NULL, "isa_mmio",

                             get_system_io(), 0, 0x00800000);

    memory_region_add_subregion(get_system_memory(), 0xf2000000, isa);

    /* UniN init: XXX should be a real device */

    memory_region_init_io(unin_memory, NULL, &unin_ops, token, "unin", 0x1000);

    memory_region_add_subregion(get_system_memory(), 0xf8000000, unin_memory);

    memory_region_init_io(unin2_memory, NULL, &unin_ops, token, "unin", 0x1000);

    memory_region_add_subregion(get_system_memory(), 0xf3000000, unin2_memory);

    openpic_irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));

    openpic_irqs[0] =

        g_malloc0(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);

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

        /* Mac99 IRQ connection between OpenPIC outputs pins

         * and PowerPC input pins

         */

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

            openpic_irqs[i] = openpic_irqs[0] + (i * OPENPIC_OUTPUT_NB);

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_HRESET];

            break;

#if defined(TARGET_PPC64)

        case PPC_FLAGS_INPUT_970:

            openpic_irqs[i] = openpic_irqs[0] + (i * OPENPIC_OUTPUT_NB);

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_HRESET];

            break;

#endif /* defined(TARGET_PPC64) */

        default:

            error_report("Bus model not supported on mac99 machine");

            exit(1);

        }

    }

    pic = g_new0(qemu_irq, 64);

    dev = qdev_create(NULL, TYPE_OPENPIC);

    qdev_prop_set_uint32(dev, "model", OPENPIC_MODEL_RAVEN);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    pic_mem = s->mmio[0].memory;

    k = 0;

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

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

            sysbus_connect_irq(s, k++, openpic_irqs[i][j]);

        }

    }

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

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

    }

    if (PPC_INPUT(env) == PPC_FLAGS_INPUT_970) {

        /* 970 gets a U3 bus */

        pci_bus = pci_pmac_u3_init(pic, get_system_memory(), get_system_io());

        machine_arch = ARCH_MAC99_U3;

    } else {

        pci_bus = pci_pmac_init(pic, get_system_memory(), get_system_io());

        machine_arch = ARCH_MAC99;

    }

    object_property_set_bool(OBJECT(pci_bus), true, "realized", &error_abort);

    machine->usb |= defaults_enabled() && !machine->usb_disabled;

    /* Timebase Frequency */

    if (kvm_enabled()) {

        tbfreq = kvmppc_get_tbfreq();

    } else {

        tbfreq = TBFREQ;

    }

    /* init basic PC hardware */

    escc_mem = escc_init(0, pic[0x25], pic[0x24],

                         serial_hds[0], serial_hds[1], ESCC_CLOCK, 4);

    memory_region_init_alias(escc_bar, NULL, "escc-bar",

                             escc_mem, 0, memory_region_size(escc_mem));

    macio = pci_create(pci_bus, -1, TYPE_NEWWORLD_MACIO);

    dev = DEVICE(macio);

    qdev_connect_gpio_out(dev, 0, pic[0x19]); /* CUDA */

    qdev_connect_gpio_out(dev, 1, pic[0x0d]); /* IDE */

    qdev_connect_gpio_out(dev, 2, pic[0x02]); /* IDE DMA */

    qdev_connect_gpio_out(dev, 3, pic[0x0e]); /* IDE */

    qdev_connect_gpio_out(dev, 4, pic[0x03]); /* IDE DMA */

    qdev_prop_set_uint64(dev, "frequency", tbfreq);

    macio_init(macio, pic_mem, escc_bar);

    /* We only emulate 2 out of 3 IDE controllers for now */

    ide_drive_get(hd, ARRAY_SIZE(hd));

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[0]"));

    macio_ide_init_drives(macio_ide, hd);

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[1]"));

    macio_ide_init_drives(macio_ide, &hd[MAX_IDE_DEVS]);

    dev = DEVICE(object_resolve_path_component(OBJECT(macio), "cuda"));

    adb_bus = qdev_get_child_bus(dev, "adb.0");

    dev = qdev_create(adb_bus, TYPE_ADB_KEYBOARD);

    qdev_init_nofail(dev);

    dev = qdev_create(adb_bus, TYPE_ADB_MOUSE);

    qdev_init_nofail(dev);

    if (machine->usb) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

        /* U3 needs to use USB for input because Linux doesn't support via-cuda

        on PPC64 */

        if (machine_arch == ARCH_MAC99_U3) {

            USBBus *usb_bus = usb_bus_find(-1);

            usb_create_simple(usb_bus, "usb-kbd");

            usb_create_simple(usb_bus, "usb-mouse");

        }

    }

    pci_vga_init(pci_bus);

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8) {

        graphic_depth = 15;

    }

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

        pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL);

    }

    /* The NewWorld NVRAM is not located in the MacIO device */

#ifdef CONFIG_KVM

    if (kvm_enabled() && getpagesize() > 4096) {

        /* We can't combine read-write and read-only in a single page, so

           move the NVRAM out of ROM again for KVM */

        nvram_addr = 0xFFE00000;

    }

#endif

    dev = qdev_create(NULL, TYPE_MACIO_NVRAM);

    qdev_prop_set_uint32(dev, "size", 0x2000);

    qdev_prop_set_uint32(dev, "it_shift", 1);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, nvram_addr);

    nvr = MACIO_NVRAM(dev);

    pmac_format_nvram_partition(nvr, 0x2000);

    /* No PCI init: the BIOS will do it */

    fw_cfg = fw_cfg_init_mem(CFG_ADDR, CFG_ADDR + 2);

    fw_cfg_add_i16(fw_cfg, FW_CFG_NB_CPUS, (uint16_t)smp_cpus);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, machine_arch);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, cmdline_base);

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE, kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0);

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, ppc_boot_device);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_IS_KVM, kvm_enabled());

    if (kvm_enabled()) {

#ifdef CONFIG_KVM

        uint8_t *hypercall;

        hypercall = g_malloc(16);

        kvmppc_get_hypercall(env, hypercall, 16);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16);

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid());

#endif

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, tbfreq);

    /* Mac OS X requires a "known good" clock-frequency value; pass it one. */

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, CLOCKFREQ);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_BUSFREQ, BUSFREQ);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_NVRAM_ADDR, nvram_addr);

    /* MacOS NDRV VGA driver */

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, NDRV_VGA_FILENAME);

    if (filename) {

        ndrv_size = get_image_size(filename);

        if (ndrv_size != -1) {

            ndrv_file = g_malloc(ndrv_size);

            ndrv_size = load_image(filename, ndrv_file);

            fw_cfg_add_file(fw_cfg, "ndrv/qemu_vga.ndrv", ndrv_file, ndrv_size);

        }

        g_free(filename);

    }

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static void test_qemu_strtoull_empty(void)

{

    const char *str = "";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0);

    g_assert(endptr == str);

}


void pcmcia_socket_unregister(PCMCIASocket *socket)

{

    struct pcmcia_socket_entry_s *entry, **ptr;

    ptr = &pcmcia_sockets;

    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)

        if (entry->socket == socket) {

            *ptr = entry->next;

            g_free(entry);

        }

}


static ssize_t qsb_get_iovec(const QEMUSizedBuffer *qsb,

                             off_t pos, off_t *d_off)

{

    ssize_t i;

    off_t curr = 0;

    if (pos > qsb->used) {

        return -1;

    }

    for (i = 0; i < qsb->n_iov; i++) {

        if (curr + qsb->iov[i].iov_len > pos) {

            *d_off = pos - curr;

            return i;

        }

        curr += qsb->iov[i].iov_len;

    }

    return -1;

}


static gboolean fd_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)

{

    CharDriverState *chr = opaque;

    FDCharDriver *s = chr->opaque;

    int len;

    uint8_t buf[READ_BUF_LEN];

    GIOStatus status;

    gsize bytes_read;

    len = sizeof(buf);

    if (len > s->max_size) {

        len = s->max_size;

    }

    if (len == 0) {

        return TRUE;

    }

    status = g_io_channel_read_chars(chan, (gchar *)buf,

                                     len, &bytes_read, NULL);

    if (status == G_IO_STATUS_EOF) {

        if (s->fd_in_tag) {

            g_source_remove(s->fd_in_tag);

            s->fd_in_tag = 0;

        }

        qemu_chr_be_event(chr, CHR_EVENT_CLOSED);

        return FALSE;

    }

    if (status == G_IO_STATUS_NORMAL) {

        qemu_chr_be_write(chr, buf, bytes_read);

    }

    return TRUE;

}


void hmp_drive_add_node(Monitor *mon, const char *optstr)

{

    QemuOpts *opts;

    QDict *qdict;

    Error *local_err = NULL;

    opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);

    if (!opts) {

        return;

    }

    qdict = qemu_opts_to_qdict(opts, NULL);

    if (!qdict_get_try_str(qdict, "node-name")) {

        error_report("'node-name' needs to be specified");

        goto out;

    }

    BlockDriverState *bs = bds_tree_init(qdict, &local_err);

    if (!bs) {

        error_report_err(local_err);

        goto out;

    }

    QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);

out:

    qemu_opts_del(opts);

}


void cpu_breakpoint_remove_all(CPUState *cpu, int mask)

{

#if defined(TARGET_HAS_ICE)

    CPUBreakpoint *bp, *next;

    QTAILQ_FOREACH_SAFE(bp, &cpu->breakpoints, entry, next) {

        if (bp->flags & mask) {

            cpu_breakpoint_remove_by_ref(cpu, bp);

        }

    }

#endif

}


solisten(port, laddr, lport, flags)

	u_int port;

	u_int32_t laddr;

	u_int lport;

	int flags;

{

	struct sockaddr_in addr;

	struct socket *so;

	int s, addrlen = sizeof(addr), opt = 1;

	DEBUG_CALL("solisten");

	DEBUG_ARG("port = %d", port);

	DEBUG_ARG("laddr = %x", laddr);

	DEBUG_ARG("lport = %d", lport);

	DEBUG_ARG("flags = %x", flags);

	if ((so = socreate()) == NULL) {

	  /* free(so);      Not sofree() ??? free(NULL) == NOP */

	  return NULL;

	}

	/* Don't tcp_attach... we don't need so_snd nor so_rcv */

	if ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {

		free(so);

		return NULL;

	}

	insque(so,&tcb);

	/*

	 * SS_FACCEPTONCE sockets must time out.

	 */

	if (flags & SS_FACCEPTONCE)

	   so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT*2;

	so->so_state = (SS_FACCEPTCONN|flags);

	so->so_lport = lport; /* Kept in network format */

	so->so_laddr.s_addr = laddr; /* Ditto */

	addr.sin_family = AF_INET;

	addr.sin_addr.s_addr = INADDR_ANY;

	addr.sin_port = port;

	if (((s = socket(AF_INET,SOCK_STREAM,0)) < 0) ||

	    (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int)) < 0) ||

	    (bind(s,(struct sockaddr *)&addr, sizeof(addr)) < 0) ||

	    (listen(s,1) < 0)) {

		int tmperrno = errno; /* Don't clobber the real reason we failed */

		close(s);

		sofree(so);

		/* Restore the real errno */

#ifdef _WIN32

		WSASetLastError(tmperrno);

#else

		errno = tmperrno;

#endif

		return NULL;

	}

	setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));

	getsockname(s,(struct sockaddr *)&addr,&addrlen);

	so->so_fport = addr.sin_port;

	if (addr.sin_addr.s_addr == 0 || addr.sin_addr.s_addr == loopback_addr.s_addr)

	   so->so_faddr = alias_addr;

	else

	   so->so_faddr = addr.sin_addr;

	so->s = s;

	return so;

}


static void *qemu_tcg_cpu_thread_fn(void *arg)

{

    CPUState *cpu = arg;

    qemu_tcg_init_cpu_signals();

    qemu_thread_get_self(cpu->thread);

    qemu_mutex_lock(&qemu_global_mutex);

    CPU_FOREACH(cpu) {

        cpu->thread_id = qemu_get_thread_id();

        cpu->created = true;

        cpu->exception_index = -1;

        cpu->can_do_io = 1;

    }

    qemu_cond_signal(&qemu_cpu_cond);

    /* wait for initial kick-off after machine start */

    while (QTAILQ_FIRST(&cpus)->stopped) {

        qemu_cond_wait(tcg_halt_cond, &qemu_global_mutex);

        /* process any pending work */

        CPU_FOREACH(cpu) {

            qemu_wait_io_event_common(cpu);

        }

    }

    while (1) {

        tcg_exec_all();

        if (use_icount) {

            int64_t deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

            if (deadline == 0) {

                qemu_clock_notify(QEMU_CLOCK_VIRTUAL);

            }

        }

        qemu_tcg_wait_io_event();

    }

    return NULL;

}


int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,

                                              AVPacket *avpkt,

                                              const AVFrame *frame,

                                              int *got_packet_ptr)

{

    int ret;

    AVPacket user_pkt = *avpkt;

    *got_packet_ptr = 0;

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

        av_free_packet(avpkt);

        av_init_packet(avpkt);

        avpkt->size     = 0;

        return 0;

    }

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

        return AVERROR(EINVAL);

    av_assert0(avctx->codec->encode2);

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

    av_assert0(ret <= 0);

    if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {

        if (user_pkt.data) {

            if (user_pkt.size >= avpkt->size) {

                memcpy(user_pkt.data, avpkt->data, avpkt->size);

            } else {

                av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);

                avpkt->size = user_pkt.size;

                ret = -1;

            }

            avpkt->data     = user_pkt.data;

            avpkt->destruct = user_pkt.destruct;

        } else {

            if (av_dup_packet(avpkt) < 0) {

                ret = AVERROR(ENOMEM);

            }

        }

    }

    if (!ret) {

        if (!*got_packet_ptr)

            avpkt->size = 0;

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

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

        if (!user_pkt.data && avpkt->data &&

            avpkt->destruct == av_destruct_packet) {

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

            if (new_data)

                avpkt->data = new_data;

        }

        avctx->frame_number++;

    }

    if (ret < 0 || !*got_packet_ptr)

        av_free_packet(avpkt);

    emms_c();

    return ret;

}


static int net_rx_ok(void *opaque)

{

    struct XenNetDev *netdev = opaque;

    RING_IDX rc, rp;

    if (netdev->xendev.be_state != XenbusStateConnected)

	return 0;

    rc = netdev->rx_ring.req_cons;

    rp = netdev->rx_ring.sring->req_prod;

    xen_rmb();

    if (rc == rp || RING_REQUEST_CONS_OVERFLOW(&netdev->rx_ring, rc)) {

	xen_be_printf(&netdev->xendev, 2, "%s: no rx buffers (%d/%d)\n",

		      __FUNCTION__, rc, rp);

	return 0;

    }

    return 1;

}


uint64_t migrate_max_downtime(void)

{

    return max_downtime;

}


static void tc6393xb_gpio_set(void *opaque, int line, int level)

{

//    TC6393xbState *s = opaque;

    if (line > TC6393XB_GPIOS) {

        printf("%s: No GPIO pin %i\n", __FUNCTION__, line);

        return;

    }

    // FIXME: how does the chip reflect the GPIO input level change?

}


static void ne2000_receive(void *opaque, const uint8_t *buf, int size)

{

    NE2000State *s = opaque;

    uint8_t *p;

    int total_len, next, avail, len, index, mcast_idx;

    uint8_t buf1[60];

    static const uint8_t broadcast_macaddr[6] =

        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

#if defined(DEBUG_NE2000)

    printf("NE2000: received len=%d\n", size);

#endif

    if (s->cmd & E8390_STOP || ne2000_buffer_full(s))

        return;

    /* XXX: check this */

    if (s->rxcr & 0x10) {

        /* promiscuous: receive all */

    } else {

        if (!memcmp(buf,  broadcast_macaddr, 6)) {

            /* broadcast address */

            if (!(s->rxcr & 0x04))

                return;

        } else if (buf[0] & 0x01) {

            /* multicast */

            if (!(s->rxcr & 0x08))

                return;

            mcast_idx = compute_mcast_idx(buf);

            if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))))

                return;

        } else if (s->mem[0] == buf[0] &&

                   s->mem[2] == buf[1] &&

                   s->mem[4] == buf[2] &&

                   s->mem[6] == buf[3] &&

                   s->mem[8] == buf[4] &&

                   s->mem[10] == buf[5]) {

            /* match */

        } else {

            return;

        }

    }

    /* if too small buffer, then expand it */

    if (size < MIN_BUF_SIZE) {

        memcpy(buf1, buf, size);

        memset(buf1 + size, 0, MIN_BUF_SIZE - size);

        buf = buf1;

        size = MIN_BUF_SIZE;

    }

    index = s->curpag << 8;

    /* 4 bytes for header */

    total_len = size + 4;

    /* address for next packet (4 bytes for CRC) */

    next = index + ((total_len + 4 + 255) & ~0xff);

    if (next >= s->stop)

        next -= (s->stop - s->start);

    /* prepare packet header */

    p = s->mem + index;

    s->rsr = ENRSR_RXOK; /* receive status */

    /* XXX: check this */

    if (buf[0] & 0x01)

        s->rsr |= ENRSR_PHY;

    p[0] = s->rsr;

    p[1] = next >> 8;

    p[2] = total_len;

    p[3] = total_len >> 8;

    index += 4;

    /* write packet data */

    while (size > 0) {

        avail = s->stop - index;

        len = size;

        if (len > avail)

            len = avail;

        memcpy(s->mem + index, buf, len);

        buf += len;

        index += len;

        if (index == s->stop)

            index = s->start;

        size -= len;

    }

    s->curpag = next >> 8;

    /* now we can signal we have received something */

    s->isr |= ENISR_RX;

    ne2000_update_irq(s);

}


static TCGv gen_muls_i64_i32(TCGv a, TCGv b)

{

    TCGv tmp1 = tcg_temp_new(TCG_TYPE_I64);

    TCGv tmp2 = tcg_temp_new(TCG_TYPE_I64);

    tcg_gen_ext_i32_i64(tmp1, a);

    dead_tmp(a);

    tcg_gen_ext_i32_i64(tmp2, b);

    dead_tmp(b);

    tcg_gen_mul_i64(tmp1, tmp1, tmp2);

    return tmp1;

}


void runstate_set(RunState new_state)

{

    if (new_state >= RUN_STATE_MAX ||

        !runstate_valid_transitions[current_run_state][new_state]) {

        fprintf(stderr, "invalid runstate transition\n");

        abort();

    }

    current_run_state = new_state;

}


static int kvmppc_put_books_sregs(PowerPCCPU *cpu)

{

    CPUPPCState *env = &cpu->env;

    struct kvm_sregs sregs;

    int i;

    sregs.pvr = env->spr[SPR_PVR];

    sregs.u.s.sdr1 = env->spr[SPR_SDR1];

    /* Sync SLB */

#ifdef TARGET_PPC64

    for (i = 0; i < ARRAY_SIZE(env->slb); i++) {

        sregs.u.s.ppc64.slb[i].slbe = env->slb[i].esid;

        if (env->slb[i].esid & SLB_ESID_V) {

            sregs.u.s.ppc64.slb[i].slbe |= i;

        }

        sregs.u.s.ppc64.slb[i].slbv = env->slb[i].vsid;

    }

#endif

    /* Sync SRs */

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

        sregs.u.s.ppc32.sr[i] = env->sr[i];

    }

    /* Sync BATs */

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

        /* Beware. We have to swap upper and lower bits here */

        sregs.u.s.ppc32.dbat[i] = ((uint64_t)env->DBAT[0][i] << 32)

            | env->DBAT[1][i];

        sregs.u.s.ppc32.ibat[i] = ((uint64_t)env->IBAT[0][i] << 32)

            | env->IBAT[1][i];

    }

    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_SREGS, &sregs);

}


int kvmppc_remove_spapr_tce(void *table, int fd, uint32_t window_size)

{

    long len;

    if (fd < 0) {

        return -1;

    }

    len = (window_size / SPAPR_TCE_PAGE_SIZE)*sizeof(sPAPRTCE);

    if ((munmap(table, len) < 0) ||

        (close(fd) < 0)) {

        fprintf(stderr, "KVM: Unexpected error removing TCE table: %s",

                strerror(errno));

        /* Leak the table */

    }

    return 0;

}


static unsigned int crisv32_decoder(CPUCRISState *env, DisasContext *dc)

{

    int insn_len = 2;

    int i;

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

        tcg_gen_debug_insn_start(dc->pc);

        }

    /* Load a halfword onto the instruction register.  */

        dc->ir = cris_fetch(env, dc, dc->pc, 2, 0);

    /* Now decode it.  */

    dc->opcode   = EXTRACT_FIELD(dc->ir, 4, 11);

    dc->op1      = EXTRACT_FIELD(dc->ir, 0, 3);

    dc->op2      = EXTRACT_FIELD(dc->ir, 12, 15);

    dc->zsize    = EXTRACT_FIELD(dc->ir, 4, 4);

    dc->zzsize   = EXTRACT_FIELD(dc->ir, 4, 5);

    dc->postinc  = EXTRACT_FIELD(dc->ir, 10, 10);

    /* Large switch for all insns.  */

    for (i = 0; i < ARRAY_SIZE(decinfo); i++) {

        if ((dc->opcode & decinfo[i].mask) == decinfo[i].bits) {

            insn_len = decinfo[i].dec(env, dc);

            break;

        }

    }

#if !defined(CONFIG_USER_ONLY)

    /* Single-stepping ?  */

    if (dc->tb_flags & S_FLAG) {

        int l1;

        l1 = gen_new_label();

        tcg_gen_brcondi_tl(TCG_COND_NE, cpu_PR[PR_SPC], dc->pc, l1);

        /* We treat SPC as a break with an odd trap vector.  */

        cris_evaluate_flags(dc);

        t_gen_mov_env_TN(trap_vector, tcg_const_tl(3));

        tcg_gen_movi_tl(env_pc, dc->pc + insn_len);

        tcg_gen_movi_tl(cpu_PR[PR_SPC], dc->pc + insn_len);

        t_gen_raise_exception(EXCP_BREAK);

        gen_set_label(l1);

    }

#endif

    return insn_len;

}


static int64_t coroutine_fn cow_co_get_block_status(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *num_same)

{

    BDRVCowState *s = bs->opaque;

    int ret = cow_co_is_allocated(bs, sector_num, nb_sectors, num_same);

    int64_t offset = s->cow_sectors_offset + (sector_num << BDRV_SECTOR_BITS);

    if (ret < 0) {

        return ret;

    }

    return (ret ? BDRV_BLOCK_DATA : 0) | offset | BDRV_BLOCK_OFFSET_VALID;

}


static int rle_unpack(unsigned char *src, unsigned char *dest, int len)

{

    unsigned char *ps;

    unsigned char *pd;

    int i, l;

    ps = src;

    pd = dest;

    if (len & 1)

        *pd++ = *ps++;

    len >>= 1;

    i = 0;

    do {

        l = *ps++;

        if (l & 0x80) {

            l = (l & 0x7F) * 2;

            memcpy(pd, ps, l);

            ps += l;

            pd += l;

        } else {

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

                *pd++ = ps[0];

                *pd++ = ps[1];

            }

            ps += 2;

        }

        i += l;

    } while (i < len);

    return (ps - src);

}


void scsi_bus_legacy_handle_cmdline(SCSIBus *bus, Error **errp)

{

    Location loc;

    DriveInfo *dinfo;

    int unit;

    Error *err = NULL;

    loc_push_none(&loc);

    for (unit = 0; unit <= bus->info->max_target; unit++) {

        dinfo = drive_get(IF_SCSI, bus->busnr, unit);

        if (dinfo == NULL) {

            continue;

        }

        qemu_opts_loc_restore(dinfo->opts);

        scsi_bus_legacy_add_drive(bus, blk_bs(blk_by_legacy_dinfo(dinfo)),

                                  unit, false, -1, NULL, &err);

        if (err != NULL) {

            error_report("%s", error_get_pretty(err));

            error_propagate(errp, err);

            break;

        }

    }

    loc_pop(&loc);

}


static void netfilter_print_info(Monitor *mon, NetFilterState *nf)

{

    char *str;

    ObjectProperty *prop;

    ObjectPropertyIterator iter;

    StringOutputVisitor *ov;

    /* generate info str */

    object_property_iter_init(&iter, OBJECT(nf));

    while ((prop = object_property_iter_next(&iter))) {

        if (!strcmp(prop->name, "type")) {

            continue;

        }

        ov = string_output_visitor_new(false);

        object_property_get(OBJECT(nf), string_output_get_visitor(ov),

                            prop->name, NULL);

        str = string_output_get_string(ov);

        visit_free(string_output_get_visitor(ov));

        monitor_printf(mon, ",%s=%s", prop->name, str);

        g_free(str);

    }

    monitor_printf(mon, "\n");

}


static int restore_user_regs(CPUPPCState *env,

                             struct target_mcontext *frame, int sig)

{

    target_ulong save_r2 = 0;

    target_ulong msr;

    target_ulong ccr;

    int i;

    if (!sig) {

        save_r2 = env->gpr[2];

    }

    /* Restore general registers.  */

    for (i = 0; i < ARRAY_SIZE(env->gpr); i++) {

        if (__get_user(env->gpr[i], &frame->mc_gregs[i])) {

            return 1;

        }

    }

    if (__get_user(env->nip, &frame->mc_gregs[TARGET_PT_NIP])

        || __get_user(env->ctr, &frame->mc_gregs[TARGET_PT_CTR])

        || __get_user(env->lr, &frame->mc_gregs[TARGET_PT_LNK])

        || __get_user(env->xer, &frame->mc_gregs[TARGET_PT_XER]))

        return 1;

    if (__get_user(ccr, &frame->mc_gregs[TARGET_PT_CCR]))

        return 1;

    for (i = 0; i < ARRAY_SIZE(env->crf); i++) {

        env->crf[i] = (ccr >> (32 - ((i + 1) * 4))) & 0xf;

    }

    if (!sig) {

        env->gpr[2] = save_r2;

    }

    /* Restore MSR.  */

    if (__get_user(msr, &frame->mc_gregs[TARGET_PT_MSR]))

        return 1;

    /* If doing signal return, restore the previous little-endian mode.  */

    if (sig)

        env->msr = (env->msr & ~MSR_LE) | (msr & MSR_LE);

    /* Restore Altivec registers if necessary.  */

    if (env->insns_flags & PPC_ALTIVEC) {

        for (i = 0; i < ARRAY_SIZE(env->avr); i++) {

            ppc_avr_t *avr = &env->avr[i];

            ppc_avr_t *vreg = &frame->mc_vregs.altivec[i];

            if (__get_user(avr->u64[0], &vreg->u64[0]) ||

                __get_user(avr->u64[1], &vreg->u64[1])) {

                return 1;

            }

        }

        /* Set MSR_VEC in the saved MSR value to indicate that

           frame->mc_vregs contains valid data.  */

        if (__get_user(env->spr[SPR_VRSAVE],

                       (target_ulong *)(&frame->mc_vregs.altivec[32].u32[3])))

            return 1;

    }

    /* Restore floating point registers.  */

    if (env->insns_flags & PPC_FLOAT) {

        uint64_t fpscr;

        for (i = 0; i < ARRAY_SIZE(env->fpr); i++) {

            if (__get_user(env->fpr[i], &frame->mc_fregs[i])) {

                return 1;

            }

        }

        if (__get_user(fpscr, &frame->mc_fregs[32]))

            return 1;

        env->fpscr = (uint32_t) fpscr;

    }

    /* Save SPE registers.  The kernel only saves the high half.  */

    if (env->insns_flags & PPC_SPE) {

#if defined(TARGET_PPC64)

        for (i = 0; i < ARRAY_SIZE(env->gpr); i++) {

            uint32_t hi;

            if (__get_user(hi, &frame->mc_vregs.spe[i])) {

                return 1;

            }

            env->gpr[i] = ((uint64_t)hi << 32) | ((uint32_t) env->gpr[i]);

        }

#else

        for (i = 0; i < ARRAY_SIZE(env->gprh); i++) {

            if (__get_user(env->gprh[i], &frame->mc_vregs.spe[i])) {

                return 1;

            }

        }

#endif

        if (__get_user(env->spe_fscr, &frame->mc_vregs.spe[32]))

            return 1;

    }

    return 0;

}


static void virtio_pci_config_write(void *opaque, hwaddr addr,

                                    uint64_t val, unsigned size)

{

    VirtIOPCIProxy *proxy = opaque;

    uint32_t config = VIRTIO_PCI_CONFIG(&proxy->pci_dev);

    if (addr < config) {

        virtio_ioport_write(proxy, addr, val);

        return;

    }

    addr -= config;

    /*

     * Virtio-PCI is odd. Ioports are LE but config space is target native

     * endian.

     */

    switch (size) {

    case 1:

        virtio_config_writeb(proxy->vdev, addr, val);

        break;

    case 2:

        if (virtio_is_big_endian()) {

            val = bswap16(val);

        }

        virtio_config_writew(proxy->vdev, addr, val);

        break;

    case 4:

        if (virtio_is_big_endian()) {

            val = bswap32(val);

        }

        virtio_config_writel(proxy->vdev, addr, val);

        break;

    }

}


int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)

{

    BDRVQcowState *s = bs->opaque;

    int i, j = 0, l2_index, ret;

    uint64_t *old_cluster, start_sect, l2_offset, *l2_table;

    uint64_t cluster_offset = m->cluster_offset;

    bool cow = false;

    trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);

    if (m->nb_clusters == 0)

        return 0;

    old_cluster = g_malloc(m->nb_clusters * sizeof(uint64_t));

    /* copy content of unmodified sectors */

    start_sect = (m->offset & ~(s->cluster_size - 1)) >> 9;

    if (m->n_start) {

        cow = true;

        qemu_co_mutex_unlock(&s->lock);

        ret = copy_sectors(bs, start_sect, cluster_offset, 0, m->n_start);

        qemu_co_mutex_lock(&s->lock);

        if (ret < 0)

            goto err;

    }

    if (m->nb_available & (s->cluster_sectors - 1)) {

        uint64_t end = m->nb_available & ~(uint64_t)(s->cluster_sectors - 1);

        cow = true;

        qemu_co_mutex_unlock(&s->lock);

        ret = copy_sectors(bs, start_sect + end, cluster_offset + (end << 9),

                m->nb_available - end, s->cluster_sectors);

        qemu_co_mutex_lock(&s->lock);

        if (ret < 0)

            goto err;

    }

    /*

     * Update L2 table.

     *

     * Before we update the L2 table to actually point to the new cluster, we

     * need to be sure that the refcounts have been increased and COW was

     * handled.

     */

    if (cow) {

        qcow2_cache_depends_on_flush(s->l2_table_cache);

    }

    qcow2_cache_set_dependency(bs, s->l2_table_cache, s->refcount_block_cache);

    ret = get_cluster_table(bs, m->offset, &l2_table, &l2_offset, &l2_index);

    if (ret < 0) {

        goto err;

    }

    qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);

    for (i = 0; i < m->nb_clusters; i++) {

        /* if two concurrent writes happen to the same unallocated cluster

	 * each write allocates separate cluster and writes data concurrently.

	 * The first one to complete updates l2 table with pointer to its

	 * cluster the second one has to do RMW (which is done above by

	 * copy_sectors()), update l2 table with its cluster pointer and free

	 * old cluster. This is what this loop does */

        if(l2_table[l2_index + i] != 0)

            old_cluster[j++] = l2_table[l2_index + i];

        l2_table[l2_index + i] = cpu_to_be64((cluster_offset +

                    (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);

     }

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

    if (ret < 0) {

        goto err;

    }

    /*

     * If this was a COW, we need to decrease the refcount of the old cluster.

     * Also flush bs->file to get the right order for L2 and refcount update.

     */

    if (j != 0) {

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

            qcow2_free_any_clusters(bs,

                be64_to_cpu(old_cluster[i]) & ~QCOW_OFLAG_COPIED, 1);

        }

    }

    ret = 0;

err:

    g_free(old_cluster);

    return ret;

 }


MemTxResult address_space_read_continue(AddressSpace *as, hwaddr addr,

                                        MemTxAttrs attrs, uint8_t *buf,

                                        int len, hwaddr addr1, hwaddr l,

                                        MemoryRegion *mr)

{

    uint8_t *ptr;

    uint64_t val;

    MemTxResult result = MEMTX_OK;

    bool release_lock = false;

    for (;;) {

        if (!memory_access_is_direct(mr, false)) {

            /* I/O case */

            release_lock |= prepare_mmio_access(mr);

            l = memory_access_size(mr, l, addr1);

            switch (l) {

            case 8:

                /* 64 bit read access */

                result |= memory_region_dispatch_read(mr, addr1, &val, 8,

                                                      attrs);

                stq_p(buf, val);

                break;

            case 4:

                /* 32 bit read access */

                result |= memory_region_dispatch_read(mr, addr1, &val, 4,

                                                      attrs);

                stl_p(buf, val);

                break;

            case 2:

                /* 16 bit read access */

                result |= memory_region_dispatch_read(mr, addr1, &val, 2,

                                                      attrs);

                stw_p(buf, val);

                break;

            case 1:

                /* 8 bit read access */

                result |= memory_region_dispatch_read(mr, addr1, &val, 1,

                                                      attrs);

                stb_p(buf, val);

                break;

            default:

                abort();

            }

        } else {

            /* RAM case */

            ptr = qemu_map_ram_ptr(mr->ram_block, addr1);

            memcpy(buf, ptr, l);

        }

        if (release_lock) {

            qemu_mutex_unlock_iothread();

            release_lock = false;

        }

        len -= l;

        buf += l;

        addr += l;

        if (!len) {

            break;

        }

        l = len;

        mr = address_space_translate(as, addr, &addr1, &l, false);

    }

    return result;

}


FsTypeEntry *get_fsdev_fsentry(char *id)

{

    struct FsTypeListEntry *fsle;

    QTAILQ_FOREACH(fsle, &fstype_entries, next) {

        if (strcmp(fsle->fse.fsdev_id, id) == 0) {

            return &fsle->fse;

        }

    }

    return NULL;

}


bool eth_parse_ipv6_hdr(struct iovec *pkt, int pkt_frags,

                        size_t ip6hdr_off, uint8_t *l4proto,

                        size_t *full_hdr_len)

{

    struct ip6_header ip6_hdr;

    struct ip6_ext_hdr ext_hdr;

    size_t bytes_read;

    bytes_read = iov_to_buf(pkt, pkt_frags, ip6hdr_off,

                            &ip6_hdr, sizeof(ip6_hdr));

    if (bytes_read < sizeof(ip6_hdr)) {

        return false;

    }

    *full_hdr_len = sizeof(struct ip6_header);

    if (!eth_is_ip6_extension_header_type(ip6_hdr.ip6_nxt)) {

        *l4proto = ip6_hdr.ip6_nxt;

        return true;

    }

    do {

        bytes_read = iov_to_buf(pkt, pkt_frags, ip6hdr_off + *full_hdr_len,

                                &ext_hdr, sizeof(ext_hdr));

        *full_hdr_len += (ext_hdr.ip6r_len + 1) * IP6_EXT_GRANULARITY;

    } while (eth_is_ip6_extension_header_type(ext_hdr.ip6r_nxt));

    *l4proto = ext_hdr.ip6r_nxt;

    return true;

}


static void kvmppc_timer_hack(void *opaque)

{

    qemu_service_io();

    qemu_mod_timer(kvmppc_timer, qemu_get_clock_ns(vm_clock) + kvmppc_timer_rate);

}


static void setup_rt_frame(int sig, struct target_sigaction *ka,

                           target_siginfo_t *info,

                           target_sigset_t *set, CPUPPCState *env)

{

    struct target_rt_sigframe *rt_sf;

    struct target_mcontext *frame;

    target_ulong rt_sf_addr, newsp = 0;

    int i, err = 0;

    int signal;

    rt_sf_addr = get_sigframe(ka, env, sizeof(*rt_sf));

    if (!lock_user_struct(VERIFY_WRITE, rt_sf, rt_sf_addr, 1))

        goto sigsegv;

    signal = current_exec_domain_sig(sig);

    copy_siginfo_to_user(&rt_sf->info, info);

    __put_user(0, &rt_sf->uc.tuc_flags);

    __put_user(0, &rt_sf->uc.tuc_link);

    __put_user((target_ulong)target_sigaltstack_used.ss_sp,

               &rt_sf->uc.tuc_stack.ss_sp);

    __put_user(sas_ss_flags(env->gpr[1]),

               &rt_sf->uc.tuc_stack.ss_flags);

    __put_user(target_sigaltstack_used.ss_size,

               &rt_sf->uc.tuc_stack.ss_size);

    __put_user(h2g (&rt_sf->uc.tuc_mcontext),

               &rt_sf->uc.tuc_regs);

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

        __put_user(set->sig[i], &rt_sf->uc.tuc_sigmask.sig[i]);

    }

    frame = &rt_sf->uc.tuc_mcontext;

    err |= save_user_regs(env, frame, TARGET_NR_rt_sigreturn);

    /* The kernel checks for the presence of a VDSO here.  We don't

       emulate a vdso, so use a sigreturn system call.  */

    env->lr = (target_ulong) h2g(frame->tramp);

    /* Turn off all fp exceptions.  */

    env->fpscr = 0;

    /* Create a stack frame for the caller of the handler.  */

    newsp = rt_sf_addr - (SIGNAL_FRAMESIZE + 16);

    __put_user(env->gpr[1], (target_ulong *)(uintptr_t) newsp);

    if (err)

        goto sigsegv;

    /* Set up registers for signal handler.  */

    env->gpr[1] = newsp;

    env->gpr[3] = (target_ulong) signal;

    env->gpr[4] = (target_ulong) h2g(&rt_sf->info);

    env->gpr[5] = (target_ulong) h2g(&rt_sf->uc);

    env->gpr[6] = (target_ulong) h2g(rt_sf);

    env->nip = (target_ulong) ka->_sa_handler;

    /* Signal handlers are entered in big-endian mode.  */

    env->msr &= ~MSR_LE;

    unlock_user_struct(rt_sf, rt_sf_addr, 1);

    return;

sigsegv:

    unlock_user_struct(rt_sf, rt_sf_addr, 1);

    qemu_log("segfaulting from setup_rt_frame\n");

    force_sig(TARGET_SIGSEGV);

}


static void gen_test_cc(int cc, int label)

{

    TCGv tmp;

    TCGv tmp2;

    int inv;

    switch (cc) {

    case 0: /* eq: Z */

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        break;

    case 1: /* ne: !Z */

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_NE, tmp, 0, label);

        break;

    case 2: /* cs: C */

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_NE, tmp, 0, label);

        break;

    case 3: /* cc: !C */

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        break;

    case 4: /* mi: N */

        tmp = load_cpu_field(NF);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    case 5: /* pl: !N */

        tmp = load_cpu_field(NF);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        break;

    case 6: /* vs: V */

        tmp = load_cpu_field(VF);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    case 7: /* vc: !V */

        tmp = load_cpu_field(VF);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        break;

    case 8: /* hi: C && !Z */

        inv = gen_new_label();

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, inv);

        dead_tmp(tmp);

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_NE, tmp, 0, label);

        gen_set_label(inv);

        break;

    case 9: /* ls: !C || Z */

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        dead_tmp(tmp);

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        break;

    case 10: /* ge: N == V -> N ^ V == 0 */

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        break;

    case 11: /* lt: N != V -> N ^ V != 0 */

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    case 12: /* gt: !Z && N == V */

        inv = gen_new_label();

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, inv);

        dead_tmp(tmp);

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        gen_set_label(inv);

        break;

    case 13: /* le: Z || N != V */

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        dead_tmp(tmp);

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    default:

        fprintf(stderr, "Bad condition code 0x%x\n", cc);

        abort();

    }

    dead_tmp(tmp);

}


static int kvm_put_xcrs(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    struct kvm_xcrs xcrs = {};

    if (!kvm_has_xcrs()) {

        return 0;

    }

    xcrs.nr_xcrs = 1;

    xcrs.flags = 0;

    xcrs.xcrs[0].xcr = 0;

    xcrs.xcrs[0].value = env->xcr0;

    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_XCRS, &xcrs);

}


START_TEST(qint_destroy_test)

{

    QInt *qi = qint_from_int(0);

    QDECREF(qi);

}