static void gen_compute_branch1 (CPUState *env, DisasContext *ctx, uint32_t op,

                                 int32_t cc, int32_t offset)

{

    target_ulong btarget;

    const char *opn = "cp1 cond branch";

    TCGv t0 = tcg_temp_local_new(TCG_TYPE_TL);

    TCGv t1 = tcg_temp_local_new(TCG_TYPE_TL);

    if (cc != 0)

        check_insn(env, ctx, ISA_MIPS4 | ISA_MIPS32);

    btarget = ctx->pc + 4 + offset;

    switch (op) {

    case OPC_BC1F:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_not_tl(t0, t0);

            tcg_gen_movi_tl(t1, 0x1 << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1f";

        goto not_likely;

    case OPC_BC1FL:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_not_tl(t0, t0);

            tcg_gen_movi_tl(t1, 0x1 << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1fl";

        goto likely;

    case OPC_BC1T:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_movi_tl(t1, 0x1 << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1t";

        goto not_likely;

    case OPC_BC1TL:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_movi_tl(t1, 0x1 << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1tl";

    likely:

        ctx->hflags |= MIPS_HFLAG_BL;

        tcg_gen_trunc_tl_i32(bcond, t0);

        break;

    case OPC_BC1FANY2:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_not_tl(t0, t0);

            tcg_gen_movi_tl(t1, 0x3 << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1any2f";

        goto not_likely;

    case OPC_BC1TANY2:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_movi_tl(t1, 0x3 << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1any2t";

        goto not_likely;

    case OPC_BC1FANY4:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_not_tl(t0, t0);

            tcg_gen_movi_tl(t1, 0xf << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1any4f";

        goto not_likely;

    case OPC_BC1TANY4:

        {

            int l1 = gen_new_label();

            int l2 = gen_new_label();

            TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

            get_fp_cond(r_tmp1);

            tcg_gen_ext_i32_tl(t0, r_tmp1);

            tcg_temp_free(r_tmp1);

            tcg_gen_movi_tl(t1, 0xf << cc);

            tcg_gen_and_tl(t0, t0, t1);

            tcg_gen_brcondi_tl(TCG_COND_NE, t0, 0, l1);

            tcg_gen_movi_tl(t0, 0);

            tcg_gen_br(l2);

            gen_set_label(l1);

            tcg_gen_movi_tl(t0, 1);

            gen_set_label(l2);

        }

        opn = "bc1any4t";

    not_likely:

        ctx->hflags |= MIPS_HFLAG_BC;

        tcg_gen_trunc_tl_i32(bcond, t0);

        break;

    default:

        MIPS_INVAL(opn);

        generate_exception (ctx, EXCP_RI);

        goto out;

    }

    MIPS_DEBUG("%s: cond %02x target " TARGET_FMT_lx, opn,

               ctx->hflags, btarget);

    ctx->btarget = btarget;

 out:

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


void kvm_s390_crw_mchk(void)

{

    struct kvm_s390_irq irq = {

        .type = KVM_S390_MCHK,

        .u.mchk.cr14 = 1 << 28,

        .u.mchk.mcic = build_channel_report_mcic(),

    };

    kvm_s390_floating_interrupt(&irq);

}


void timerlistgroup_init(QEMUTimerListGroup *tlg,

                         QEMUTimerListNotifyCB *cb, void *opaque)

{

    QEMUClockType type;

    for (type = 0; type < QEMU_CLOCK_MAX; type++) {

        tlg->tl[type] = timerlist_new(type, cb, opaque);

    }

}


static ssize_t block_crypto_init_func(QCryptoBlock *block,

                                      size_t headerlen,

                                      Error **errp,

                                      void *opaque)

{

    struct BlockCryptoCreateData *data = opaque;

    int ret;

    /* User provided size should reflect amount of space made

     * available to the guest, so we must take account of that

     * which will be used by the crypto header

     */

    data->size += headerlen;

    qemu_opt_set_number(data->opts, BLOCK_OPT_SIZE, data->size, &error_abort);

    ret = bdrv_create_file(data->filename, data->opts, errp);

    if (ret < 0) {

        return -1;

    }

    data->blk = blk_new_open(data->filename, NULL, NULL,

                             BDRV_O_RDWR | BDRV_O_PROTOCOL, errp);

    if (!data->blk) {

        return -1;

    }

    return 0;

}


static void gen_spr_620 (CPUPPCState *env)

{

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR0, "PMR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR1, "PMR1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR2, "PMR2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR3, "PMR3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR4, "PMR4",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR5, "PMR5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR6, "PMR6",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR7, "PMR7",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR8, "PMR8",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMR9, "PMR9",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMRA, "PMR10",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMRB, "PMR11",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMRC, "PMR12",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMRD, "PMR13",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMRE, "PMR14",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_PMRF, "PMR15",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_HID8, "HID8",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_620_HID9, "HID9",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

}


static struct dpll_ctl_s  *omap_dpll_init(MemoryRegion *memory,

                           target_phys_addr_t base, omap_clk clk)

{

    struct dpll_ctl_s *s = g_malloc0(sizeof(*s));

    memory_region_init_io(&s->iomem, &omap_dpll_ops, s, "omap-dpll", 0x100);

    s->dpll = clk;

    omap_dpll_reset(s);

    memory_region_add_subregion(memory, base, &s->iomem);

    return s;

}


static void qcow2_close(BlockDriverState *bs)

{

    BDRVQcow2State *s = bs->opaque;

    qemu_vfree(s->l1_table);

    /* else pre-write overlap checks in cache_destroy may crash */

    s->l1_table = NULL;

    if (!(s->flags & BDRV_O_INACTIVE)) {

        qcow2_inactivate(bs);

    }

    cache_clean_timer_del(bs);

    qcow2_cache_destroy(bs, s->l2_table_cache);

    qcow2_cache_destroy(bs, s->refcount_block_cache);

    qcrypto_cipher_free(s->cipher);

    s->cipher = NULL;

    g_free(s->unknown_header_fields);

    cleanup_unknown_header_ext(bs);

    g_free(s->image_backing_file);

    g_free(s->image_backing_format);

    g_free(s->cluster_cache);

    qemu_vfree(s->cluster_data);

    qcow2_refcount_close(bs);

    qcow2_free_snapshots(bs);

}


static int opt_output_file(const char *opt, const char *filename)

{

    AVFormatContext *oc;

    int i, err;

    AVOutputFormat *file_oformat;

    OutputStream *ost;

    InputStream  *ist;

    if (!strcmp(filename, "-"))

        filename = "pipe:";

    err = avformat_alloc_output_context2(&oc, NULL, last_asked_format, filename);

    last_asked_format = NULL;

    if (!oc) {

        print_error(filename, err);

        exit_program(1);

    }

    file_oformat= oc->oformat;

    if (!strcmp(file_oformat->name, "ffm") &&

        av_strstart(filename, "http:", NULL)) {

        /* special case for files sent to ffserver: we get the stream

           parameters from ffserver */

        int err = read_ffserver_streams(oc, filename);

        if (err < 0) {

            print_error(filename, err);

            exit_program(1);

        }

    } else if (!nb_stream_maps) {

        /* pick the "best" stream of each type */

#define NEW_STREAM(type, index)\

        if (index >= 0) {\

            ost = new_ ## type ## _stream(oc);\

            ost->source_index = index;\

            ost->sync_ist     = &input_streams[index];\

            input_streams[index].discard = 0;\

        }

        /* video: highest resolution */

        if (!video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {

            int area = 0, idx = -1;

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

                ist = &input_streams[i];

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

                    ist->st->codec->width * ist->st->codec->height > area) {

                    area = ist->st->codec->width * ist->st->codec->height;

                    idx = i;

                }

            }

            NEW_STREAM(video, idx);

        }

        /* audio: most channels */

        if (!audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {

            int channels = 0, idx = -1;

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

                ist = &input_streams[i];

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&

                    ist->st->codec->channels > channels) {

                    channels = ist->st->codec->channels;

                    idx = i;

                }

            }

            NEW_STREAM(audio, idx);

        }

        /* subtitles: pick first */

        if (!subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {

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

                if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {

                    NEW_STREAM(subtitle, i);

                    break;

                }

        }

        /* do something with data? */

    } else {

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

            StreamMap *map = &stream_maps[i];

            if (map->disabled)

                continue;

            ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];

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

            case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(oc);    break;

            case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(oc);    break;

            case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(oc); break;

            case AVMEDIA_TYPE_DATA:     ost = new_data_stream(oc);     break;

            default:

                av_log(NULL, AV_LOG_ERROR, "Cannot map stream #%d.%d - unsupported type.\n",

                       map->file_index, map->stream_index);

                exit_program(1);

            }

            ost->source_index = input_files[map->file_index].ist_index + map->stream_index;

            ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +

                                           map->sync_stream_index];

            ist->discard = 0;

        }

    }

    av_dict_copy(&oc->metadata, metadata, 0);

    av_dict_free(&metadata);

    if (nb_output_files == MAX_FILES)

        exit_program(1);                /* a temporary hack until all the other MAX_FILES-sized arrays are removed */

    output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);

    output_files[nb_output_files - 1].ctx       = oc;

    output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;

    av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);

    /* check filename in case of an image number is expected */

    if (oc->oformat->flags & AVFMT_NEEDNUMBER) {

        if (!av_filename_number_test(oc->filename)) {

            print_error(oc->filename, AVERROR(EINVAL));

            exit_program(1);

        }

    }

    if (!(oc->oformat->flags & AVFMT_NOFILE)) {

        /* test if it already exists to avoid loosing precious files */

        if (!file_overwrite &&

            (strchr(filename, ':') == NULL ||

             filename[1] == ':' ||

             av_strstart(filename, "file:", NULL))) {

            if (avio_check(filename, 0) == 0) {

                if (!using_stdin) {

                    fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);

                    fflush(stderr);

                    if (!read_yesno()) {

                        fprintf(stderr, "Not overwriting - exiting\n");

                        exit_program(1);

                    }

                }

                else {

                    fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);

                    exit_program(1);

                }

            }

        }

        /* open the file */

        if ((err = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE)) < 0) {

            print_error(filename, err);

            exit_program(1);

        }

    }

    oc->preload= (int)(mux_preload*AV_TIME_BASE);

    oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);

    if (loop_output >= 0) {

        av_log(NULL, AV_LOG_WARNING, "-loop_output is deprecated, use -loop\n");

        oc->loop_output = loop_output;

    }

    /* copy chapters */

    if (chapters_input_file >= nb_input_files) {

        if (chapters_input_file == INT_MAX) {

            /* copy chapters from the first input file that has them*/

            chapters_input_file = -1;

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

                if (input_files[i].ctx->nb_chapters) {

                    chapters_input_file = i;

                    break;

                }

        } else {

            av_log(NULL, AV_LOG_ERROR, "Invalid input file index %d in chapter mapping.\n",

                   chapters_input_file);

            exit_program(1);

        }

    }

    if (chapters_input_file >= 0)

        copy_chapters(chapters_input_file, nb_output_files - 1);

    /* copy metadata */

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

        AVFormatContext *files[2];

        AVDictionary    **meta[2];

        int j;

#define METADATA_CHECK_INDEX(index, nb_elems, desc)\

        if ((index) < 0 || (index) >= (nb_elems)) {\

            av_log(NULL, AV_LOG_ERROR, "Invalid %s index %d while processing metadata maps\n",\

                     (desc), (index));\

            exit_program(1);\

        }

        int in_file_index = meta_data_maps[i][1].file;

        if (in_file_index < 0)

            continue;

        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")

        files[0] = oc;

        files[1] = input_files[in_file_index].ctx;

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

            MetadataMap *map = &meta_data_maps[i][j];

            switch (map->type) {

            case 'g':

                meta[j] = &files[j]->metadata;

                break;

            case 's':

                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")

                meta[j] = &files[j]->streams[map->index]->metadata;

                break;

            case 'c':

                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")

                meta[j] = &files[j]->chapters[map->index]->metadata;

                break;

            case 'p':

                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")

                meta[j] = &files[j]->programs[map->index]->metadata;

                break;

            }

        }

        av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);

    }

    /* copy global metadata by default */

    if (metadata_global_autocopy && nb_input_files)

        av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,

                     AV_DICT_DONT_OVERWRITE);

    if (metadata_streams_autocopy)

        for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {

            InputStream *ist = &input_streams[output_streams[i].source_index];

            av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);

        }

    frame_rate    = (AVRational){0, 0};

    frame_width   = 0;

    frame_height  = 0;

    audio_sample_rate = 0;

    audio_channels    = 0;

    audio_sample_fmt  = AV_SAMPLE_FMT_NONE;

    chapters_input_file = INT_MAX;

    av_freep(&meta_data_maps);

    nb_meta_data_maps = 0;

    metadata_global_autocopy   = 1;

    metadata_streams_autocopy  = 1;

    metadata_chapters_autocopy = 1;

    av_freep(&stream_maps);

    nb_stream_maps = 0;

    av_dict_free(&codec_names);

    av_freep(&forced_key_frames);

    uninit_opts();

    init_opts();

    return 0;

}


static int pte64_check(mmu_ctx_t *ctx, target_ulong pte0,

                       target_ulong pte1, int h, int rw, int type)

{

    target_ulong ptem, mmask;

    int access, ret, pteh, ptev, pp;

    ret = -1;

    /* Check validity and table match */

    ptev = pte64_is_valid(pte0);

    pteh = (pte0 >> 1) & 1;

    if (ptev && h == pteh) {

        /* Check vsid & api */

        ptem = pte0 & PTE64_PTEM_MASK;

        mmask = PTE64_CHECK_MASK;

        pp = (pte1 & 0x00000003) | ((pte1 >> 61) & 0x00000004);

        ctx->nx  = (pte1 >> 2) & 1; /* No execute bit */

        ctx->nx |= (pte1 >> 3) & 1; /* Guarded bit    */

        if (ptem == ctx->ptem) {

            if (ctx->raddr != (hwaddr)-1ULL) {

                /* all matches should have equal RPN, WIMG & PP */

                if ((ctx->raddr & mmask) != (pte1 & mmask)) {

                    qemu_log("Bad RPN/WIMG/PP\n");

                    return -3;

                }

            }

            /* Compute access rights */

            access = pp_check(ctx->key, pp, ctx->nx);

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            ret = check_prot(ctx->prot, rw, type);

            if (ret == 0) {

                /* Access granted */

                LOG_MMU("PTE access granted !\n");

            } else {

                /* Access right violation */

                LOG_MMU("PTE access rejected\n");

            }

        }

    }

    return ret;

}


static void usb_xhci_realize(struct PCIDevice *dev, Error **errp)

{

    int i, ret;

    Error *err = NULL;

    XHCIState *xhci = XHCI(dev);

    dev->config[PCI_CLASS_PROG] = 0x30;    /* xHCI */

    dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */

    dev->config[PCI_CACHE_LINE_SIZE] = 0x10;

    dev->config[0x60] = 0x30; /* release number */

    if (strcmp(object_get_typename(OBJECT(dev)), TYPE_NEC_XHCI) == 0) {

        xhci->nec_quirks = true;

    }

    if (xhci->numintrs > MAXINTRS) {

        xhci->numintrs = MAXINTRS;

    }

    while (xhci->numintrs & (xhci->numintrs - 1)) {   /* ! power of 2 */

        xhci->numintrs++;

    }

    if (xhci->numintrs < 1) {

        xhci->numintrs = 1;

    }

    if (xhci->numslots > MAXSLOTS) {

        xhci->numslots = MAXSLOTS;

    }

    if (xhci->numslots < 1) {

        xhci->numslots = 1;

    }

    if (xhci_get_flag(xhci, XHCI_FLAG_ENABLE_STREAMS)) {

        xhci->max_pstreams_mask = 7; /* == 256 primary streams */

    } else {

        xhci->max_pstreams_mask = 0;

    }

    if (xhci->msi != ON_OFF_AUTO_OFF) {

        ret = msi_init(dev, 0x70, xhci->numintrs, true, false, &err);

        /* Any error other than -ENOTSUP(board's MSI support is broken)

         * is a programming error */

        assert(!ret || ret == -ENOTSUP);

        if (ret && xhci->msi == ON_OFF_AUTO_ON) {

            /* Can't satisfy user's explicit msi=on request, fail */

            error_append_hint(&err, "You have to use msi=auto (default) or "

                    "msi=off with this machine type.\n");

            error_propagate(errp, err);

            return;

        }

        assert(!err || xhci->msi == ON_OFF_AUTO_AUTO);

        /* With msi=auto, we fall back to MSI off silently */

        error_free(err);

    }

    usb_xhci_init(xhci);

    xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci);

    memory_region_init(&xhci->mem, OBJECT(xhci), "xhci", LEN_REGS);

    memory_region_init_io(&xhci->mem_cap, OBJECT(xhci), &xhci_cap_ops, xhci,

                          "capabilities", LEN_CAP);

    memory_region_init_io(&xhci->mem_oper, OBJECT(xhci), &xhci_oper_ops, xhci,

                          "operational", 0x400);

    memory_region_init_io(&xhci->mem_runtime, OBJECT(xhci), &xhci_runtime_ops, xhci,

                          "runtime", LEN_RUNTIME);

    memory_region_init_io(&xhci->mem_doorbell, OBJECT(xhci), &xhci_doorbell_ops, xhci,

                          "doorbell", LEN_DOORBELL);

    memory_region_add_subregion(&xhci->mem, 0,            &xhci->mem_cap);

    memory_region_add_subregion(&xhci->mem, OFF_OPER,     &xhci->mem_oper);

    memory_region_add_subregion(&xhci->mem, OFF_RUNTIME,  &xhci->mem_runtime);

    memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell);

    for (i = 0; i < xhci->numports; i++) {

        XHCIPort *port = &xhci->ports[i];

        uint32_t offset = OFF_OPER + 0x400 + 0x10 * i;

        port->xhci = xhci;

        memory_region_init_io(&port->mem, OBJECT(xhci), &xhci_port_ops, port,

                              port->name, 0x10);

        memory_region_add_subregion(&xhci->mem, offset, &port->mem);

    }

    pci_register_bar(dev, 0,

                     PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,

                     &xhci->mem);

    if (pci_bus_is_express(dev->bus) ||

        xhci_get_flag(xhci, XHCI_FLAG_FORCE_PCIE_ENDCAP)) {

        ret = pcie_endpoint_cap_init(dev, 0xa0);

        assert(ret > 0);

    }

    if (xhci->msix != ON_OFF_AUTO_OFF) {

        /* TODO check for errors, and should fail when msix=on */

        msix_init(dev, xhci->numintrs,

                  &xhci->mem, 0, OFF_MSIX_TABLE,

                  &xhci->mem, 0, OFF_MSIX_PBA,

                  0x90, NULL);

    }

}


void acpi_pcihp_init(AcpiPciHpState *s, PCIBus *root_bus,

                     MemoryRegion *address_space_io)

{

    s->root= root_bus;

    memory_region_init_io(&s->io, NULL, &acpi_pcihp_io_ops, s,

                          "acpi-pci-hotplug",

                          PCI_HOTPLUG_SIZE);

    memory_region_add_subregion(address_space_io, PCI_HOTPLUG_ADDR, &s->io);

}


static void qmp_output_complete(Visitor *v, void *opaque)

{

    QmpOutputVisitor *qov = to_qov(v);

    /* A visit must have occurred, with each start paired with end.  */

    assert(qov->root && QSLIST_EMPTY(&qov->stack));

    assert(opaque == qov->result);

    qobject_incref(qov->root);

    *qov->result = qov->root;

    qov->result = NULL;

}


static SocketAddress *sd_server_config(QDict *options, Error **errp)

{

    QDict *server = NULL;

    QObject *crumpled_server = NULL;

    Visitor *iv = NULL;

    SocketAddressFlat *saddr_flat = NULL;

    SocketAddress *saddr = NULL;

    Error *local_err = NULL;

    qdict_extract_subqdict(options, &server, "server.");

    crumpled_server = qdict_crumple(server, errp);

    if (!crumpled_server) {

        goto done;

    }

    /*

     * FIXME .numeric, .to, .ipv4 or .ipv6 don't work with -drive

     * server.type=inet.  .to doesn't matter, it's ignored anyway.

     * That's because when @options come from -blockdev or

     * blockdev_add, members are typed according to the QAPI schema,

     * but when they come from -drive, they're all QString.  The

     * visitor expects the former.

     */

    iv = qobject_input_visitor_new(crumpled_server);

    visit_type_SocketAddressFlat(iv, NULL, &saddr_flat, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto done;

    }

    saddr = socket_address_crumple(saddr_flat);

done:

    qapi_free_SocketAddressFlat(saddr_flat);

    visit_free(iv);

    qobject_decref(crumpled_server);

    QDECREF(server);

    return saddr;

}


filter_mirror_set_outdev(Object *obj, const char *value, Error **errp)

{

    MirrorState *s = FILTER_MIRROR(obj);

    g_free(s->outdev);

    s->outdev = g_strdup(value);

    if (!s->outdev) {

        error_setg(errp, "filter filter mirror needs 'outdev' "

                   "property set");

        return;

    }

}


int bdrv_is_inserted(BlockDriverState *bs)

{

    BlockDriver *drv = bs->drv;

    int ret;

    if (!drv)

        return 0;

    if (!drv->bdrv_is_inserted)

        return !bs->tray_open;

    ret = drv->bdrv_is_inserted(bs);

    return ret;

}


static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)

{

    VirtIOBlock *s = to_virtio_blk(vdev);

    struct virtio_blk_config blkcfg;

    uint64_t capacity;

    int cylinders, heads, secs;

    bdrv_get_geometry(s->bs, &capacity);

    bdrv_get_geometry_hint(s->bs, &cylinders, &heads, &secs);

    stq_raw(&blkcfg.capacity, capacity);

    stl_raw(&blkcfg.seg_max, 128 - 2);

    stw_raw(&blkcfg.cylinders, cylinders);

    blkcfg.heads = heads;

    blkcfg.sectors = secs;

    memcpy(config, &blkcfg, sizeof(blkcfg));

}


static int vpc_create(const char *filename, QEMUOptionParameter *options)

{

    uint8_t buf[1024];

    struct vhd_footer* footer = (struct vhd_footer*) buf;

    struct vhd_dyndisk_header* dyndisk_header =

        (struct vhd_dyndisk_header*) buf;

    int fd, i;

    uint16_t cyls;

    uint8_t heads;

    uint8_t secs_per_cyl;

    size_t block_size, num_bat_entries;

    int64_t total_sectors = 0;

    // Read out options

    while (options && options->name) {

        if (!strcmp(options->name, "size")) {

            total_sectors = options->value.n / 512;

        }

        options++;

    }

    // Create the file

    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);

    if (fd < 0)

        return -EIO;

    // Calculate matching total_size and geometry

    if (calculate_geometry(total_sectors, &cyls, &heads, &secs_per_cyl))

        return -EFBIG;

    total_sectors = (int64_t) cyls * heads * secs_per_cyl;

    // Prepare the Hard Disk Footer

    memset(buf, 0, 1024);

    memcpy(footer->creator, "conectix", 8);

    // TODO Check if "qemu" creator_app is ok for VPC

    memcpy(footer->creator_app, "qemu", 4);

    memcpy(footer->creator_os, "Wi2k", 4);

    footer->features = be32_to_cpu(0x02);

    footer->version = be32_to_cpu(0x00010000);

    footer->data_offset = be64_to_cpu(HEADER_SIZE);

    footer->timestamp = be32_to_cpu(time(NULL) - VHD_TIMESTAMP_BASE);

    // Version of Virtual PC 2007

    footer->major = be16_to_cpu(0x0005);

    footer->minor =be16_to_cpu(0x0003);

    footer->orig_size = be64_to_cpu(total_sectors * 512);

    footer->size = be64_to_cpu(total_sectors * 512);

    footer->cyls = be16_to_cpu(cyls);

    footer->heads = heads;

    footer->secs_per_cyl = secs_per_cyl;

    footer->type = be32_to_cpu(VHD_DYNAMIC);

    // TODO uuid is missing

    footer->checksum = be32_to_cpu(vpc_checksum(buf, HEADER_SIZE));

    // Write the footer (twice: at the beginning and at the end)

    block_size = 0x200000;

    num_bat_entries = (total_sectors + block_size / 512) / (block_size / 512);

    if (write(fd, buf, HEADER_SIZE) != HEADER_SIZE)

        return -EIO;

    if (lseek(fd, 1536 + ((num_bat_entries * 4 + 511) & ~511), SEEK_SET) < 0)

        return -EIO;

    if (write(fd, buf, HEADER_SIZE) != HEADER_SIZE)

        return -EIO;

    // Write the initial BAT

    if (lseek(fd, 3 * 512, SEEK_SET) < 0)

        return -EIO;

    memset(buf, 0xFF, 512);

    for (i = 0; i < (num_bat_entries * 4 + 511) / 512; i++)

        if (write(fd, buf, 512) != 512)

            return -EIO;

    // Prepare the Dynamic Disk Header

    memset(buf, 0, 1024);

    memcpy(dyndisk_header->magic, "cxsparse", 8);

    dyndisk_header->data_offset = be64_to_cpu(0xFFFFFFFF);

    dyndisk_header->table_offset = be64_to_cpu(3 * 512);

    dyndisk_header->version = be32_to_cpu(0x00010000);

    dyndisk_header->block_size = be32_to_cpu(block_size);

    dyndisk_header->max_table_entries = be32_to_cpu(num_bat_entries);

    dyndisk_header->checksum = be32_to_cpu(vpc_checksum(buf, 1024));

    // Write the header

    if (lseek(fd, 512, SEEK_SET) < 0)

        return -EIO;

    if (write(fd, buf, 1024) != 1024)

        return -EIO;

    close(fd);

    return 0;

}


ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb,

                      AVStream *st, RMStream *ast, AVPacket *pkt)

{

    RMDemuxContext *rm = s->priv_data;

    assert (rm->audio_pkt_cnt > 0);

    if (st->codec->codec_id == CODEC_ID_AAC)

        av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);

    else {

        av_new_packet(pkt, st->codec->block_align);

        memcpy(pkt->data, ast->pkt.data + st->codec->block_align * //FIXME avoid this

               (ast->sub_packet_h * ast->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),

               st->codec->block_align);

    }

    rm->audio_pkt_cnt--;

    if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {

        ast->audiotimestamp = AV_NOPTS_VALUE;

        pkt->flags = AV_PKT_FLAG_KEY;

    } else

        pkt->flags = 0;

    pkt->stream_index = st->index;

    return rm->audio_pkt_cnt;

}


static void virtio_pci_reset(void *opaque)

{

    VirtIOPCIProxy *proxy = opaque;

    virtio_reset(proxy->vdev);

    msix_reset(&proxy->pci_dev);

}


static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,

                         const uint8_t *buf, int nb_sectors)

{

    int async_ret;

    BlockDriverAIOCB *acb;

    async_ret = NOT_DONE;

    qemu_aio_wait_start();

    acb = bdrv_aio_write(bs, sector_num, buf, nb_sectors,

                         bdrv_rw_em_cb, &async_ret);

    if (acb == NULL) {

        qemu_aio_wait_end();

        return -1;

    }

    while (async_ret == NOT_DONE) {

        qemu_aio_wait();

    }

    qemu_aio_wait_end();

    return async_ret;

}


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

{

    IOAPICCommonClass *k = IOAPIC_COMMON_CLASS(klass);

    DeviceClass *dc = DEVICE_CLASS(klass);

    k->realize = ioapic_realize;

     * If APIC is in kernel, we need to update the kernel cache after

     * migration, otherwise first 24 gsi routes will be invalid.

    k->post_load = ioapic_update_kvm_routes;

    dc->reset = ioapic_reset_common;

    dc->props = ioapic_properties;

}


static inline void iwmmxt_store_creg(int reg, TCGv var)

{

    tcg_gen_st_i32(var, cpu_env, offsetof(CPUState, iwmmxt.cregs[reg]));

}


static int decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             const uint8_t *buf, int buf_size)

{

    H264Context *h = avctx->priv_data;

    MpegEncContext *s = &h->s;

    AVFrame *pict = data;

    int buf_index;

    s->flags= avctx->flags;

    s->flags2= avctx->flags2;

    if(s->flags&CODEC_FLAG_TRUNCATED){

        const int next= ff_h264_find_frame_end(h, buf, buf_size);

        assert((buf_size > 0) || (next == END_NOT_FOUND));

        if( ff_combine_frame(&s->parse_context, next, &buf, &buf_size) < 0 )

          return buf_size;

//printf("next:%d buf_size:%d last_index:%d\n", next, buf_size, s->parse_context.last_index);

    }

   /* no supplementary picture */

    if (buf_size == 0) {

        Picture *out;

        int i, out_idx;

//FIXME factorize this with the output code below

        out = h->delayed_pic[0];

        out_idx = 0;

        for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && h->delayed_pic[i]->poc; i++)

            if(h->delayed_pic[i]->poc < out->poc){

                out = h->delayed_pic[i];

                out_idx = i;

            }

        for(i=out_idx; h->delayed_pic[i]; i++)

            h->delayed_pic[i] = h->delayed_pic[i+1];

        if(out){

            *data_size = sizeof(AVFrame);

            *pict= *(AVFrame*)out;

        }

        return 0;

    }

    if(h->is_avc && !h->got_avcC) {

        int i, cnt, nalsize;

        unsigned char *p = avctx->extradata;

        if(avctx->extradata_size < 7) {

            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");

            return -1;

        }

        if(*p != 1) {

            av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);

            return -1;

        }

        /* sps and pps in the avcC always have length coded with 2 bytes,

           so put a fake nal_length_size = 2 while parsing them */

        h->nal_length_size = 2;

        // Decode sps from avcC

        cnt = *(p+5) & 0x1f; // Number of sps

        p += 6;

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

            nalsize = AV_RB16(p) + 2;

            if(decode_nal_units(h, p, nalsize) < 0) {

                av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Decode pps from avcC

        cnt = *(p++); // Number of pps

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

            nalsize = AV_RB16(p) + 2;

            if(decode_nal_units(h, p, nalsize)  != nalsize) {

                av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Now store right nal length size, that will be use to parse all other nals

        h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;

        // Do not reparse avcC

        h->got_avcC = 1;

    }

    if(avctx->frame_number==0 && !h->is_avc && s->avctx->extradata_size){

        if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)

            return -1;

    }

    buf_index=decode_nal_units(h, buf, buf_size);

    if(buf_index < 0)

        return -1;

    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){

        if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;

        av_log(avctx, AV_LOG_ERROR, "no frame!\n");

        return -1;

    }

    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){

        Picture *out = s->current_picture_ptr;

        Picture *cur = s->current_picture_ptr;

        int i, pics, cross_idr, out_of_order, out_idx;

        s->mb_y= 0;

        s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;

        s->current_picture_ptr->pict_type= s->pict_type;

        if(!s->dropable) {

            execute_ref_pic_marking(h, h->mmco, h->mmco_index);

            h->prev_poc_msb= h->poc_msb;

            h->prev_poc_lsb= h->poc_lsb;

        }

        h->prev_frame_num_offset= h->frame_num_offset;

        h->prev_frame_num= h->frame_num;

        /*

         * FIXME: Error handling code does not seem to support interlaced

         * when slices span multiple rows

         * The ff_er_add_slice calls don't work right for bottom

         * fields; they cause massive erroneous error concealing

         * Error marking covers both fields (top and bottom).

         * This causes a mismatched s->error_count

         * and a bad error table. Further, the error count goes to

         * INT_MAX when called for bottom field, because mb_y is

         * past end by one (callers fault) and resync_mb_y != 0

         * causes problems for the first MB line, too.

         */

        if (!FIELD_PICTURE)

            ff_er_frame_end(s);

        MPV_frame_end(s);

        if (s->first_field) {

            /* Wait for second field. */

            *data_size = 0;

        } else {

            cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;

            /* Derive top_field_first from field pocs. */

            cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];

        //FIXME do something with unavailable reference frames

            /* Sort B-frames into display order */

            if(h->sps.bitstream_restriction_flag

               && s->avctx->has_b_frames < h->sps.num_reorder_frames){

                s->avctx->has_b_frames = h->sps.num_reorder_frames;

                s->low_delay = 0;

            }

            if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT

               && !h->sps.bitstream_restriction_flag){

                s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;

                s->low_delay= 0;

            }

            pics = 0;

            while(h->delayed_pic[pics]) pics++;

            assert(pics <= MAX_DELAYED_PIC_COUNT);

            h->delayed_pic[pics++] = cur;

            if(cur->reference == 0)

                cur->reference = DELAYED_PIC_REF;

            cross_idr = 0;

            for(i=0; h->delayed_pic[i]; i++)

                if(h->delayed_pic[i]->key_frame || h->delayed_pic[i]->poc==0)

                    cross_idr = 1;

            out = h->delayed_pic[0];

            out_idx = 0;

            for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && h->delayed_pic[i]->poc; i++)

                if(h->delayed_pic[i]->poc < out->poc){

                    out = h->delayed_pic[i];

                    out_idx = i;

                }

            out_of_order = !cross_idr && out->poc < h->outputed_poc;

            if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)

                { }

            else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)

               || (s->low_delay &&

                ((!cross_idr && out->poc > h->outputed_poc + 2)

                 || cur->pict_type == FF_B_TYPE)))

            {

                s->low_delay = 0;

                s->avctx->has_b_frames++;

            }

            if(out_of_order || pics > s->avctx->has_b_frames){

                out->reference &= ~DELAYED_PIC_REF;

                for(i=out_idx; h->delayed_pic[i]; i++)

                    h->delayed_pic[i] = h->delayed_pic[i+1];

            }

            if(!out_of_order && pics > s->avctx->has_b_frames){

                *data_size = sizeof(AVFrame);

                h->outputed_poc = out->poc;

                *pict= *(AVFrame*)out;

            }else{

                av_log(avctx, AV_LOG_DEBUG, "no picture\n");

            }

        }

    }

    assert(pict->data[0] || !*data_size);

    ff_print_debug_info(s, pict);

//printf("out %d\n", (int)pict->data[0]);

#if 0 //?

    /* Return the Picture timestamp as the frame number */

    /* we subtract 1 because it is added on utils.c     */

    avctx->frame_number = s->picture_number - 1;

#endif

    return get_consumed_bytes(s, buf_index, buf_size);

}


static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h)

{

    PadContext *s = inlink->dst->priv;

    AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0],

                                         w + (s->w - s->in_w),

                                         h + (s->h - s->in_h));

    int plane;

    if (!frame)

        return NULL;

    frame->width  = w;

    frame->height = h;

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

        int hsub = s->draw.hsub[plane];

        int vsub = s->draw.vsub[plane];

        frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] +

                              (s->y >> vsub) * frame->linesize[plane];

    }

    return frame;

}


int64_t ff_start_tag(AVIOContext *pb, const char *tag)

{

    ffio_wfourcc(pb, tag);

    avio_wl32(pb, 0);

    return avio_tell(pb);

}


static int svq3_decode_mb(H264Context *h, unsigned int mb_type)

{

    int i, j, k, m, dir, mode;

    int cbp = 0;

    uint32_t vlc;

    int8_t *top, *left;

    MpegEncContext *const s = (MpegEncContext *) h;

    const int mb_xy = h->mb_xy;

    const int b_xy  = 4*s->mb_x + 4*s->mb_y*h->b_stride;

    h->top_samples_available      = (s->mb_y == 0) ? 0x33FF : 0xFFFF;

    h->left_samples_available     = (s->mb_x == 0) ? 0x5F5F : 0xFFFF;

    h->topright_samples_available = 0xFFFF;

    if (mb_type == 0) {           /* SKIP */

        if (s->pict_type == FF_P_TYPE || s->next_picture.mb_type[mb_xy] == -1) {

            svq3_mc_dir_part(s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 0, 0);

            if (s->pict_type == FF_B_TYPE) {

                svq3_mc_dir_part(s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 1, 1);

            }

            mb_type = MB_TYPE_SKIP;

        } else {

            mb_type = FFMIN(s->next_picture.mb_type[mb_xy], 6);

            if (svq3_mc_dir(h, mb_type, PREDICT_MODE, 0, 0) < 0)

                return -1;

            if (svq3_mc_dir(h, mb_type, PREDICT_MODE, 1, 1) < 0)

                return -1;

            mb_type = MB_TYPE_16x16;

        }

    } else if (mb_type < 8) {     /* INTER */

        if (h->thirdpel_flag && h->halfpel_flag == !get_bits1 (&s->gb)) {

            mode = THIRDPEL_MODE;

        } else if (h->halfpel_flag && h->thirdpel_flag == !get_bits1 (&s->gb)) {

            mode = HALFPEL_MODE;

        } else {

            mode = FULLPEL_MODE;

        }

        /* fill caches */

        /* note ref_cache should contain here:

            ????????

            ???11111

            N??11111

            N??11111

            N??11111

        */

        for (m = 0; m < 2; m++) {

            if (s->mb_x > 0 && h->intra4x4_pred_mode[mb_xy - 1][0] != -1) {

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

                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = *(uint32_t *) s->current_picture.motion_val[m][b_xy - 1 + i*h->b_stride];

                }

            } else {

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

                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = 0;

                }

            }

            if (s->mb_y > 0) {

                memcpy(h->mv_cache[m][scan8[0] - 1*8], s->current_picture.motion_val[m][b_xy - h->b_stride], 4*2*sizeof(int16_t));

                memset(&h->ref_cache[m][scan8[0] - 1*8], (h->intra4x4_pred_mode[mb_xy - s->mb_stride][4] == -1) ? PART_NOT_AVAILABLE : 1, 4);

                if (s->mb_x < (s->mb_width - 1)) {

                    *(uint32_t *) h->mv_cache[m][scan8[0] + 4 - 1*8] = *(uint32_t *) s->current_picture.motion_val[m][b_xy - h->b_stride + 4];

                    h->ref_cache[m][scan8[0] + 4 - 1*8] =

                        (h->intra4x4_pred_mode[mb_xy - s->mb_stride + 1][0] == -1 ||

                         h->intra4x4_pred_mode[mb_xy - s->mb_stride    ][4] == -1) ? PART_NOT_AVAILABLE : 1;

                }else

                    h->ref_cache[m][scan8[0] + 4 - 1*8] = PART_NOT_AVAILABLE;

                if (s->mb_x > 0) {

                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 - 1*8] = *(uint32_t *) s->current_picture.motion_val[m][b_xy - h->b_stride - 1];

                    h->ref_cache[m][scan8[0] - 1 - 1*8] = (h->intra4x4_pred_mode[mb_xy - s->mb_stride - 1][3] == -1) ? PART_NOT_AVAILABLE : 1;

                }else

                    h->ref_cache[m][scan8[0] - 1 - 1*8] = PART_NOT_AVAILABLE;

            }else

                memset(&h->ref_cache[m][scan8[0] - 1*8 - 1], PART_NOT_AVAILABLE, 8);

            if (s->pict_type != FF_B_TYPE)

                break;

        }

        /* decode motion vector(s) and form prediction(s) */

        if (s->pict_type == FF_P_TYPE) {

            if (svq3_mc_dir(h, (mb_type - 1), mode, 0, 0) < 0)

                return -1;

        } else {        /* FF_B_TYPE */

            if (mb_type != 2) {

                if (svq3_mc_dir(h, 0, mode, 0, 0) < 0)

                    return -1;

            } else {

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

                    memset(s->current_picture.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

                }

            }

            if (mb_type != 1) {

                if (svq3_mc_dir(h, 0, mode, 1, (mb_type == 3)) < 0)

                    return -1;

            } else {

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

                    memset(s->current_picture.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

                }

            }

        }

        mb_type = MB_TYPE_16x16;

    } else if (mb_type == 8 || mb_type == 33) {   /* INTRA4x4 */

        memset(h->intra4x4_pred_mode_cache, -1, 8*5*sizeof(int8_t));

        if (mb_type == 8) {

            if (s->mb_x > 0) {

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

                    h->intra4x4_pred_mode_cache[scan8[0] - 1 + i*8] = h->intra4x4_pred_mode[mb_xy - 1][i];

                }

                if (h->intra4x4_pred_mode_cache[scan8[0] - 1] == -1) {

                    h->left_samples_available = 0x5F5F;

                }

            }

            if (s->mb_y > 0) {

                h->intra4x4_pred_mode_cache[4+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][4];

                h->intra4x4_pred_mode_cache[5+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][5];

                h->intra4x4_pred_mode_cache[6+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][6];

                h->intra4x4_pred_mode_cache[7+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][3];

                if (h->intra4x4_pred_mode_cache[4+8*0] == -1) {

                    h->top_samples_available = 0x33FF;

                }

            }

            /* decode prediction codes for luma blocks */

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

                vlc = svq3_get_ue_golomb(&s->gb);

                if (vlc >= 25){

                    av_log(h->s.avctx, AV_LOG_ERROR, "luma prediction:%d\n", vlc);

                    return -1;

                }

                left    = &h->intra4x4_pred_mode_cache[scan8[i] - 1];

                top     = &h->intra4x4_pred_mode_cache[scan8[i] - 8];

                left[1] = svq3_pred_1[top[0] + 1][left[0] + 1][svq3_pred_0[vlc][0]];

                left[2] = svq3_pred_1[top[1] + 1][left[1] + 1][svq3_pred_0[vlc][1]];

                if (left[1] == -1 || left[2] == -1){

                    av_log(h->s.avctx, AV_LOG_ERROR, "weird prediction\n");

                    return -1;

                }

            }

        } else {    /* mb_type == 33, DC_128_PRED block type */

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

                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_PRED, 4);

            }

        }

        ff_h264_write_back_intra_pred_mode(h);

        if (mb_type == 8) {

            ff_h264_check_intra4x4_pred_mode(h);

            h->top_samples_available  = (s->mb_y == 0) ? 0x33FF : 0xFFFF;

            h->left_samples_available = (s->mb_x == 0) ? 0x5F5F : 0xFFFF;

        } else {

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

                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_128_PRED, 4);

            }

            h->top_samples_available  = 0x33FF;

            h->left_samples_available = 0x5F5F;

        }

        mb_type = MB_TYPE_INTRA4x4;

    } else {                      /* INTRA16x16 */

        dir = i_mb_type_info[mb_type - 8].pred_mode;

        dir = (dir >> 1) ^ 3*(dir & 1) ^ 1;

        if ((h->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, dir)) == -1){

            av_log(h->s.avctx, AV_LOG_ERROR, "check_intra_pred_mode = -1\n");

            return -1;

        }

        cbp = i_mb_type_info[mb_type - 8].cbp;

        mb_type = MB_TYPE_INTRA16x16;

    }

    if (!IS_INTER(mb_type) && s->pict_type != FF_I_TYPE) {

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

            memset(s->current_picture.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

        }

        if (s->pict_type == FF_B_TYPE) {

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

                memset(s->current_picture.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

            }

        }

    }

    if (!IS_INTRA4x4(mb_type)) {

        memset(h->intra4x4_pred_mode[mb_xy], DC_PRED, 8);

    }

    if (!IS_SKIP(mb_type) || s->pict_type == FF_B_TYPE) {

        memset(h->non_zero_count_cache + 8, 0, 4*9*sizeof(uint8_t));

        s->dsp.clear_blocks(h->mb);

    }

    if (!IS_INTRA16x16(mb_type) && (!IS_SKIP(mb_type) || s->pict_type == FF_B_TYPE)) {

        if ((vlc = svq3_get_ue_golomb(&s->gb)) >= 48){

            av_log(h->s.avctx, AV_LOG_ERROR, "cbp_vlc=%d\n", vlc);

            return -1;

        }

        cbp = IS_INTRA(mb_type) ? golomb_to_intra4x4_cbp[vlc] : golomb_to_inter_cbp[vlc];

    }

    if (IS_INTRA16x16(mb_type) || (s->pict_type != FF_I_TYPE && s->adaptive_quant && cbp)) {

        s->qscale += svq3_get_se_golomb(&s->gb);

        if (s->qscale > 31){

            av_log(h->s.avctx, AV_LOG_ERROR, "qscale:%d\n", s->qscale);

            return -1;

        }

    }

    if (IS_INTRA16x16(mb_type)) {

        if (svq3_decode_block(&s->gb, h->mb, 0, 0)){

            av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding intra luma dc\n");

            return -1;

        }

    }

    if (cbp) {

        const int index = IS_INTRA16x16(mb_type) ? 1 : 0;

        const int type = ((s->qscale < 24 && IS_INTRA4x4(mb_type)) ? 2 : 1);

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

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

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

                    k = index ? ((j&1) + 2*(i&1) + 2*(j&2) + 4*(i&2)) : (4*i + j);

                    h->non_zero_count_cache[ scan8[k] ] = 1;

                    if (svq3_decode_block(&s->gb, &h->mb[16*k], index, type)){

                        av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding block\n");

                        return -1;

                    }

                }

            }

        }

        if ((cbp & 0x30)) {

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

              if (svq3_decode_block(&s->gb, &h->mb[16*(16 + 4*i)], 0, 3)){

                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding chroma dc block\n");

                return -1;

              }

            }

            if ((cbp & 0x20)) {

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

                    h->non_zero_count_cache[ scan8[16+i] ] = 1;

                    if (svq3_decode_block(&s->gb, &h->mb[16*(16 + i)], 1, 1)){

                        av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding chroma ac block\n");

                        return -1;

                    }

                }

            }

        }

    }

    h->cbp= cbp;

    s->current_picture.mb_type[mb_xy] = mb_type;

    if (IS_INTRA(mb_type)) {

        h->chroma_pred_mode = ff_h264_check_intra_pred_mode(h, DC_PRED8x8);

    }

    return 0;

}


AVCodecContext *avcodec_alloc_context3(const AVCodec *codec)

{

    AVCodecContext *avctx= av_malloc(sizeof(AVCodecContext));

    if(avctx==NULL) return NULL;

    if(avcodec_get_context_defaults3(avctx, codec) < 0){

        av_free(avctx);

        return NULL;

    }

    return avctx;

}


static void exynos4210_fimd_reset(DeviceState *d)

{

    Exynos4210fimdState *s = EXYNOS4210_FIMD(d);

    unsigned w;

    DPRINT_TRACE("Display controller reset\n");

    /* Set all display controller registers to 0 */

    memset(&s->vidcon, 0, (uint8_t *)&s->window - (uint8_t *)&s->vidcon);

    for (w = 0; w < NUM_OF_WINDOWS; w++) {

        memset(&s->window[w], 0, sizeof(Exynos4210fimdWindow));

        s->window[w].blendeq = 0xC2;

        exynos4210_fimd_update_win_bppmode(s, w);

        exynos4210_fimd_trace_bppmode(s, w, 0xFFFFFFFF);

        fimd_update_get_alpha(s, w);

    }

    if (s->ifb != NULL) {

        g_free(s->ifb);

    }

    s->ifb = NULL;

    exynos4210_fimd_invalidate(s);

    exynos4210_fimd_enable(s, false);

    /* Some registers have non-zero initial values */

    s->winchmap = 0x7D517D51;

    s->colorgaincon = 0x10040100;

    s->huecoef_cr[0] = s->huecoef_cr[3] = 0x01000100;

    s->huecoef_cb[0] = s->huecoef_cb[3] = 0x01000100;

    s->hueoffset = 0x01800080;

}


void helper_slbie(CPUPPCState *env, target_ulong addr)

{

    PowerPCCPU *cpu = ppc_env_get_cpu(env);

    ppc_slb_t *slb;

    slb = slb_lookup(cpu, addr);

    if (!slb) {

        return;

    }

    if (slb->esid & SLB_ESID_V) {

        slb->esid &= ~SLB_ESID_V;

        /* XXX: given the fact that segment size is 256 MB or 1TB,

         *      and we still don't have a tlb_flush_mask(env, n, mask)

         *      in QEMU, we just invalidate all TLBs

         */

        env->tlb_need_flush |= TLB_NEED_LOCAL_FLUSH;

    }

}


static int execute_command(BlockDriverState *bdrv,

                           SCSIRequest *r, int direction,

			   BlockDriverCompletionFunc *complete)

{

    r->io_header.interface_id = 'S';

    r->io_header.dxfer_direction = direction;

    r->io_header.dxferp = r->buf;

    r->io_header.dxfer_len = r->buflen;

    r->io_header.cmdp = r->cmd;

    r->io_header.cmd_len = r->cmdlen;

    r->io_header.mx_sb_len = sizeof(r->dev->sensebuf);

    r->io_header.sbp = r->dev->sensebuf;

    r->io_header.timeout = MAX_UINT;

    r->io_header.usr_ptr = r;

    r->io_header.flags |= SG_FLAG_DIRECT_IO;

    if (bdrv_pwrite(bdrv, -1, &r->io_header, sizeof(r->io_header)) == -1) {

        BADF("execute_command: write failed ! (%d)\n", errno);

        return -1;

    }

    if (complete == NULL) {

        int ret;

        r->aiocb = NULL;

        while ((ret = bdrv_pread(bdrv, -1, &r->io_header,

                                           sizeof(r->io_header))) == -1 &&

                      errno == EINTR);

        if (ret == -1) {

            BADF("execute_command: read failed !\n");

            return -1;

        }

        return 0;

    }

    r->aiocb = bdrv_aio_read(bdrv, 0, (uint8_t*)&r->io_header,

                          -(int64_t)sizeof(r->io_header), complete, r);

    if (r->aiocb == NULL) {

        BADF("execute_command: read failed !\n");

        return -1;

    }

    return 0;

}


static void inet_addr_to_opts(QemuOpts *opts, const InetSocketAddress *addr)

{

    bool ipv4 = addr->ipv4 || !addr->has_ipv4;

    bool ipv6 = addr->ipv6 || !addr->has_ipv6;

    if (!ipv4 || !ipv6) {

        qemu_opt_set_bool(opts, "ipv4", ipv4, &error_abort);

        qemu_opt_set_bool(opts, "ipv6", ipv6, &error_abort);

    }

    if (addr->has_to) {

        qemu_opt_set_number(opts, "to", addr->to, &error_abort);

    }

    qemu_opt_set(opts, "host", addr->host, &error_abort);

    qemu_opt_set(opts, "port", addr->port, &error_abort);

}


static int local_lstat(FsContext *ctx, const char *path, struct stat *stbuf)

{

    return lstat(rpath(ctx, path), stbuf);

}


static void help(void)

{

    printf("qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"

           "usage: qemu-img command [command options]\n"

           "QEMU disk image utility\n"

           "\n"

           "Command syntax:\n"

           "  check [-f fmt] filename\n"

           "  create [-F fmt] [-b base_image] [-f fmt] [-o options] filename [size]\n"

           "  commit [-f fmt] filename\n"

           "  convert [-c] [-f fmt] [-O output_fmt] [-o options] [-B output_base_image] filename [filename2 [...]] output_filename\n"

           "  info [-f fmt] filename\n"

           "  snapshot [-l | -a snapshot | -c snapshot | -d snapshot] filename\n"

           "\n"

           "Command parameters:\n"

           "  'filename' is a disk image filename\n"

           "  'base_image' is the read-only disk image which is used as base for a copy on\n"

           "    write image; the copy on write image only stores the modified data\n"

           "  'output_base_image' forces the output image to be created as a copy on write\n"

           "    image of the specified base image; 'output_base_image' should have the same\n"

           "    content as the input's base image, however the path, image format, etc may\n"

           "    differ\n"

           "  'fmt' is the disk image format. It is guessed automatically in most cases\n"

           "  'size' is the disk image size in kilobytes. Optional suffixes\n"

           "    'M' (megabyte, 1024 * 1024) and 'G' (gigabyte, 1024 * 1024 * 1024) are\n"

           "    supported any 'k' or 'K' is ignored\n"

           "  'output_filename' is the destination disk image filename\n"

           "  'output_fmt' is the destination format\n"

           "  'options' is a comma separated list of format specific options in a\n"

           "    name=value format. Use -o ? for an overview of the options supported by the\n"

           "    used format\n"

           "  '-c' indicates that target image must be compressed (qcow format only)\n"

           "  '-h' with or without a command shows this help and lists the supported formats\n"

           "\n"

           "Parameters to snapshot subcommand:\n"

           "  'snapshot' is the name of the snapshot to create, apply or delete\n"

           "  '-a' applies a snapshot (revert disk to saved state)\n"

           "  '-c' creates a snapshot\n"

           "  '-d' deletes a snapshot\n"

           "  '-l' lists all snapshots in the given image\n"

           );

    printf("\nSupported formats:");

    bdrv_iterate_format(format_print, NULL);

    printf("\n");

    exit(1);

}


ReadLineState *readline_init(Monitor *mon,

                             ReadLineCompletionFunc *completion_finder)

{

    ReadLineState *rs = g_malloc0(sizeof(*rs));

    rs->hist_entry = -1;

    rs->mon = mon;

    rs->completion_finder = completion_finder;

    return rs;

}


BlockDriverAIOCB *thread_pool_submit_aio(ThreadPoolFunc *func, void *arg,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    ThreadPool *pool = &global_pool;

    ThreadPoolElement *req;

    req = qemu_aio_get(&thread_pool_aiocb_info, NULL, cb, opaque);

    req->func = func;

    req->arg = arg;

    req->state = THREAD_QUEUED;

    req->pool = pool;

    QLIST_INSERT_HEAD(&pool->head, req, all);

    trace_thread_pool_submit(pool, req, arg);

    qemu_mutex_lock(&pool->lock);

    if (pool->idle_threads == 0 && pool->cur_threads < pool->max_threads) {

        spawn_thread(pool);

    }

    QTAILQ_INSERT_TAIL(&pool->request_list, req, reqs);

    qemu_mutex_unlock(&pool->lock);

    qemu_sem_post(&pool->sem);

    return &req->common;

}


int ff_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    int ret, i, err;

    AVStream *st;

    for (;;) {

        AVPacketList *pktl = s->internal->raw_packet_buffer;

        if (pktl) {

            *pkt = pktl->pkt;

            st   = s->streams[pkt->stream_index];

            if (s->internal->raw_packet_buffer_remaining_size <= 0)

                if ((err = probe_codec(s, st, NULL)) < 0)

                    return err;

            if (st->request_probe <= 0) {

                s->internal->raw_packet_buffer                 = pktl->next;

                s->internal->raw_packet_buffer_remaining_size += pkt->size;

                av_free(pktl);

                return 0;

            }

        }

        pkt->data = NULL;

        pkt->size = 0;

        av_init_packet(pkt);

        ret = s->iformat->read_packet(s, pkt);

        if (ret < 0) {

            /* Some demuxers return FFERROR_REDO when they consume

               data and discard it (ignored streams, junk, extradata).

               We must re-call the demuxer to get the real packet. */

            if (ret == FFERROR_REDO)

                continue;

            if (!pktl || ret == AVERROR(EAGAIN))

                return ret;

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

                st = s->streams[i];

                if (st->probe_packets)

                    if ((err = probe_codec(s, st, NULL)) < 0)

                        return err;

                av_assert0(st->request_probe <= 0);

            }

            continue;

        }

        if (!pkt->buf) {

            AVPacket tmp = { 0 };

            ret = av_packet_ref(&tmp, pkt);

            if (ret < 0)

                return ret;

            *pkt = tmp;

        }

        if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&

            (pkt->flags & AV_PKT_FLAG_CORRUPT)) {

            av_log(s, AV_LOG_WARNING,

                   "Dropped corrupted packet (stream = %d)\n",

                   pkt->stream_index);

            av_packet_unref(pkt);

            continue;

        }

        if (pkt->stream_index >= (unsigned)s->nb_streams) {

            av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);

            continue;

        }

        st = s->streams[pkt->stream_index];

        if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {

            // correct first time stamps to negative values

            if (!is_relative(st->first_dts))

                st->first_dts = wrap_timestamp(st, st->first_dts);

            if (!is_relative(st->start_time))

                st->start_time = wrap_timestamp(st, st->start_time);

            if (!is_relative(st->cur_dts))

                st->cur_dts = wrap_timestamp(st, st->cur_dts);

        }

        pkt->dts = wrap_timestamp(st, pkt->dts);

        pkt->pts = wrap_timestamp(st, pkt->pts);

        force_codec_ids(s, st);

        /* TODO: audio: time filter; video: frame reordering (pts != dts) */

        if (s->use_wallclock_as_timestamps)

            pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);

        if (!pktl && st->request_probe <= 0)

            return ret;

        err = add_to_pktbuf(&s->internal->raw_packet_buffer, pkt,

                            &s->internal->raw_packet_buffer_end, 0);

        if (err)

            return err;

        s->internal->raw_packet_buffer_remaining_size -= pkt->size;

        if ((err = probe_codec(s, st, pkt)) < 0)

            return err;

    }

}


int kvm_arch_post_run(CPUState *env, struct kvm_run *run)

{

    return 0;

}


int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,

                            Error **errp)

{

    int ret;

    ret = bdrv_child_check_perm(c, perm, shared, errp);

    if (ret < 0) {

        bdrv_child_abort_perm_update(c);

        return ret;

    }

    bdrv_child_set_perm(c, perm, shared);

    return 0;

}


static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)

{

    QIOChannelSocket *cioc;

    cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),

                                     NULL);

    if (!cioc) {

        return TRUE;

    }

    if (state >= TERMINATE) {

        object_unref(OBJECT(cioc));

        return TRUE;

    }

    nb_fds++;

    nbd_update_server_watch();

    nbd_client_new(newproto ? NULL : exp, cioc,

                   NULL, NULL, nbd_client_closed);

    object_unref(OBJECT(cioc));

    return TRUE;

}


static int sd_open(BlockDriverState *bs, QDict *options, int flags,

                   Error **errp)

{

    int ret, fd;

    uint32_t vid = 0;

    BDRVSheepdogState *s = bs->opaque;

    char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];

    uint32_t snapid;

    char *buf = NULL;

    QemuOpts *opts;

    Error *local_err = NULL;

    const char *filename;

    s->bs = bs;

    s->aio_context = bdrv_get_aio_context(bs);

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto out;

    }

    filename = qemu_opt_get(opts, "filename");

    QLIST_INIT(&s->inflight_aio_head);

    QLIST_INIT(&s->failed_aio_head);

    QLIST_INIT(&s->inflight_aiocb_head);

    s->fd = -1;

    memset(vdi, 0, sizeof(vdi));

    memset(tag, 0, sizeof(tag));

    if (strstr(filename, "://")) {

        ret = sd_parse_uri(s, filename, vdi, &snapid, tag);

    } else {

        ret = parse_vdiname(s, filename, vdi, &snapid, tag);

    }

    if (ret < 0) {

        error_setg(errp, "Can't parse filename");

        goto out;

    }

    s->fd = get_sheep_fd(s, errp);

    if (s->fd < 0) {

        ret = s->fd;

        goto out;

    }

    ret = find_vdi_name(s, vdi, snapid, tag, &vid, true, errp);

    if (ret) {

        goto out;

    }

    /*

     * QEMU block layer emulates writethrough cache as 'writeback + flush', so

     * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.

     */

    s->cache_flags = SD_FLAG_CMD_CACHE;

    if (flags & BDRV_O_NOCACHE) {

        s->cache_flags = SD_FLAG_CMD_DIRECT;

    }

    s->discard_supported = true;

    if (snapid || tag[0] != '\0') {

        DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);

        s->is_snapshot = true;

    }

    fd = connect_to_sdog(s, errp);

    if (fd < 0) {

        ret = fd;

        goto out;

    }

    buf = g_malloc(SD_INODE_SIZE);

    ret = read_object(fd, s->aio_context, buf, vid_to_vdi_oid(vid),

                      0, SD_INODE_SIZE, 0, s->cache_flags);

    closesocket(fd);

    if (ret) {

        error_setg(errp, "Can't read snapshot inode");

        goto out;

    }

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

    s->min_dirty_data_idx = UINT32_MAX;

    s->max_dirty_data_idx = 0;

    bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;

    pstrcpy(s->name, sizeof(s->name), vdi);

    qemu_co_mutex_init(&s->lock);

    qemu_co_queue_init(&s->overwrapping_queue);

    qemu_opts_del(opts);

    g_free(buf);

    return 0;

out:

    aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd, NULL, NULL, NULL);

    if (s->fd >= 0) {

        closesocket(s->fd);

    }

    qemu_opts_del(opts);

    g_free(buf);

    return ret;

}


static void gen_cp1 (DisasContext *ctx, uint32_t opc, int rt, int fs)

{

    const char *opn = "cp1 move";

    TCGv t0 = tcg_temp_new();

    switch (opc) {

    case OPC_MFC1:

        {

            TCGv_i32 fp0 = tcg_temp_new_i32();

            gen_load_fpr32(fp0, fs);

            tcg_gen_ext_i32_tl(t0, fp0);

            tcg_temp_free_i32(fp0);

        }

        gen_store_gpr(t0, rt);

        opn = "mfc1";

        break;

    case OPC_MTC1:

        gen_load_gpr(t0, rt);

        {

            TCGv_i32 fp0 = tcg_temp_new_i32();

            tcg_gen_trunc_tl_i32(fp0, t0);

            gen_store_fpr32(fp0, fs);

            tcg_temp_free_i32(fp0);

        }

        opn = "mtc1";

        break;

    case OPC_CFC1:

        gen_helper_1e0i(cfc1, t0, fs);

        gen_store_gpr(t0, rt);

        opn = "cfc1";

        break;

    case OPC_CTC1:

        gen_load_gpr(t0, rt);

        {

            TCGv_i32 fs_tmp = tcg_const_i32(fs);

            gen_helper_0e2i(ctc1, t0, fs_tmp, rt);

            tcg_temp_free_i32(fs_tmp);

        }

        opn = "ctc1";

        break;

#if defined(TARGET_MIPS64)

    case OPC_DMFC1:

        gen_load_fpr64(ctx, t0, fs);

        gen_store_gpr(t0, rt);

        opn = "dmfc1";

        break;

    case OPC_DMTC1:

        gen_load_gpr(t0, rt);

        gen_store_fpr64(ctx, t0, fs);

        opn = "dmtc1";

        break;

#endif

    case OPC_MFHC1:

        {

            TCGv_i32 fp0 = tcg_temp_new_i32();

            gen_load_fpr32h(fp0, fs);

            tcg_gen_ext_i32_tl(t0, fp0);

            tcg_temp_free_i32(fp0);

        }

        gen_store_gpr(t0, rt);

        opn = "mfhc1";

        break;

    case OPC_MTHC1:

        gen_load_gpr(t0, rt);

        {

            TCGv_i32 fp0 = tcg_temp_new_i32();

            tcg_gen_trunc_tl_i32(fp0, t0);

            gen_store_fpr32h(fp0, fs);

            tcg_temp_free_i32(fp0);

        }

        opn = "mthc1";

        break;

    default:

        MIPS_INVAL(opn);

        generate_exception (ctx, EXCP_RI);

        goto out;

    }

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

    MIPS_DEBUG("%s %s %s", opn, regnames[rt], fregnames[fs]);

 out:

    tcg_temp_free(t0);

}


static void hpet_ram_write(void *opaque, target_phys_addr_t addr,

                           uint64_t value, unsigned size)

{

    int i;

    HPETState *s = opaque;

    uint64_t old_val, new_val, val, index;

    DPRINTF("qemu: Enter hpet_ram_writel at %" PRIx64 " = %#x\n", addr, value);

    index = addr;

    old_val = hpet_ram_read(opaque, addr, 4);

    new_val = value;

    /*address range of all TN regs*/

    if (index >= 0x100 && index <= 0x3ff) {

        uint8_t timer_id = (addr - 0x100) / 0x20;

        HPETTimer *timer = &s->timer[timer_id];

        DPRINTF("qemu: hpet_ram_writel timer_id = %#x\n", timer_id);

        if (timer_id > s->num_timers) {

            DPRINTF("qemu: timer id out of range\n");

            return;

        }

        switch ((addr - 0x100) % 0x20) {

        case HPET_TN_CFG:

            DPRINTF("qemu: hpet_ram_writel HPET_TN_CFG\n");

            if (activating_bit(old_val, new_val, HPET_TN_FSB_ENABLE)) {

                update_irq(timer, 0);

            }

            val = hpet_fixup_reg(new_val, old_val, HPET_TN_CFG_WRITE_MASK);

            timer->config = (timer->config & 0xffffffff00000000ULL) | val;

            if (new_val & HPET_TN_32BIT) {

                timer->cmp = (uint32_t)timer->cmp;

                timer->period = (uint32_t)timer->period;

            }

            if (activating_bit(old_val, new_val, HPET_TN_ENABLE)) {

                hpet_set_timer(timer);

            } else if (deactivating_bit(old_val, new_val, HPET_TN_ENABLE)) {

                hpet_del_timer(timer);

            }

            break;

        case HPET_TN_CFG + 4: // Interrupt capabilities

            DPRINTF("qemu: invalid HPET_TN_CFG+4 write\n");

            break;

        case HPET_TN_CMP: // comparator register

            DPRINTF("qemu: hpet_ram_writel HPET_TN_CMP\n");

            if (timer->config & HPET_TN_32BIT) {

                new_val = (uint32_t)new_val;

            }

            if (!timer_is_periodic(timer)

                || (timer->config & HPET_TN_SETVAL)) {

                timer->cmp = (timer->cmp & 0xffffffff00000000ULL) | new_val;

            }

            if (timer_is_periodic(timer)) {

                /*

                 * FIXME: Clamp period to reasonable min value?

                 * Clamp period to reasonable max value

                 */

                new_val &= (timer->config & HPET_TN_32BIT ? ~0u : ~0ull) >> 1;

                timer->period =

                    (timer->period & 0xffffffff00000000ULL) | new_val;

            }

            timer->config &= ~HPET_TN_SETVAL;

            if (hpet_enabled(s)) {

                hpet_set_timer(timer);

            }

            break;

        case HPET_TN_CMP + 4: // comparator register high order

            DPRINTF("qemu: hpet_ram_writel HPET_TN_CMP + 4\n");

            if (!timer_is_periodic(timer)

                || (timer->config & HPET_TN_SETVAL)) {

                timer->cmp = (timer->cmp & 0xffffffffULL) | new_val << 32;

            } else {

                /*

                 * FIXME: Clamp period to reasonable min value?

                 * Clamp period to reasonable max value

                 */

                new_val &= (timer->config & HPET_TN_32BIT ? ~0u : ~0ull) >> 1;

                timer->period =

                    (timer->period & 0xffffffffULL) | new_val << 32;

                }

                timer->config &= ~HPET_TN_SETVAL;

                if (hpet_enabled(s)) {

                    hpet_set_timer(timer);

                }

                break;

        case HPET_TN_ROUTE:

            timer->fsb = (timer->fsb & 0xffffffff00000000ULL) | new_val;

            break;

        case HPET_TN_ROUTE + 4:

            timer->fsb = (new_val << 32) | (timer->fsb & 0xffffffff);

            break;

        default:

            DPRINTF("qemu: invalid hpet_ram_writel\n");

            break;

        }

        return;

    } else {

        switch (index) {

        case HPET_ID:

            return;

        case HPET_CFG:

            val = hpet_fixup_reg(new_val, old_val, HPET_CFG_WRITE_MASK);

            s->config = (s->config & 0xffffffff00000000ULL) | val;

            if (activating_bit(old_val, new_val, HPET_CFG_ENABLE)) {

                /* Enable main counter and interrupt generation. */

                s->hpet_offset =

                    ticks_to_ns(s->hpet_counter) - qemu_get_clock_ns(vm_clock);

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

                    if ((&s->timer[i])->cmp != ~0ULL) {

                        hpet_set_timer(&s->timer[i]);

                    }

                }

            } else if (deactivating_bit(old_val, new_val, HPET_CFG_ENABLE)) {

                /* Halt main counter and disable interrupt generation. */

                s->hpet_counter = hpet_get_ticks(s);

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

                    hpet_del_timer(&s->timer[i]);

                }

            }

            /* i8254 and RTC output pins are disabled

             * when HPET is in legacy mode */

            if (activating_bit(old_val, new_val, HPET_CFG_LEGACY)) {

                qemu_set_irq(s->pit_enabled, 0);

                qemu_irq_lower(s->irqs[0]);

                qemu_irq_lower(s->irqs[RTC_ISA_IRQ]);

            } else if (deactivating_bit(old_val, new_val, HPET_CFG_LEGACY)) {

                qemu_irq_lower(s->irqs[0]);

                qemu_set_irq(s->pit_enabled, 1);

                qemu_set_irq(s->irqs[RTC_ISA_IRQ], s->rtc_irq_level);

            }

            break;

        case HPET_CFG + 4:

            DPRINTF("qemu: invalid HPET_CFG+4 write\n");

            break;

        case HPET_STATUS:

            val = new_val & s->isr;

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

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

                    update_irq(&s->timer[i], 0);

                }

            }

            break;

        case HPET_COUNTER:

            if (hpet_enabled(s)) {

                DPRINTF("qemu: Writing counter while HPET enabled!\n");

            }

            s->hpet_counter =

                (s->hpet_counter & 0xffffffff00000000ULL) | value;

            DPRINTF("qemu: HPET counter written. ctr = %#x -> %" PRIx64 "\n",

                    value, s->hpet_counter);

            break;

        case HPET_COUNTER + 4:

            if (hpet_enabled(s)) {

                DPRINTF("qemu: Writing counter while HPET enabled!\n");

            }

            s->hpet_counter =

                (s->hpet_counter & 0xffffffffULL) | (((uint64_t)value) << 32);

            DPRINTF("qemu: HPET counter + 4 written. ctr = %#x -> %" PRIx64 "\n",

                    value, s->hpet_counter);

            break;

        default:

            DPRINTF("qemu: invalid hpet_ram_writel\n");

            break;

        }

    }

}


static void init_proc_601 (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_601(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_hid0_601,

                 0x80010080);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_601_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_601_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_601_HID15, "HID15",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Memory management */

#if !defined(CONFIG_USER_ONLY)

    env->nb_tlb = 64;

    env->nb_ways = 2;

    env->id_tlbs = 0;

#endif

    init_excp_601(env);

    env->dcache_line_size = 64;

    env->icache_line_size = 64;

    /* Allocate hardware IRQ controller */

    ppc6xx_irq_init(env);

}


static inline void gen_stos(DisasContext *s, int ot)

{

    gen_op_mov_TN_reg(OT_LONG, 0, R_EAX);

    gen_string_movl_A0_EDI(s);

    gen_op_st_T0_A0(ot + s->mem_index);

    gen_op_movl_T0_Dshift[ot]();

#ifdef TARGET_X86_64

    if (s->aflag == 2) {

        gen_op_addq_EDI_T0();

    } else

#endif

    if (s->aflag) {

        gen_op_addl_EDI_T0();

    } else {

        gen_op_addw_EDI_T0();

    }

}


static int read_object(int fd, char *buf, uint64_t oid, int copies,

                       unsigned int datalen, uint64_t offset, bool cache)

{

    return read_write_object(fd, buf, oid, copies, datalen, offset, false,

                             false, cache);

}


static int decode_group3_2d_line(AVCodecContext *avctx, GetBitContext *gb,

                                 unsigned int width, int *runs, const int *runend, const int *ref)

{

    int mode = 0, saved_run = 0, t;

    int run_off = *ref++;

    unsigned int offs=0, run= 0;

    runend--; // for the last written 0

    while(offs < width){

        int cmode = get_vlc2(gb, ccitt_group3_2d_vlc.table, 9, 1);

        if(cmode == -1){

            av_log(avctx, AV_LOG_ERROR, "Incorrect mode VLC\n");

            return -1;

        }

        if(!cmode){//pass mode

            run_off += *ref++;

            run = run_off - offs;

            offs= run_off;

            run_off += *ref++;

            if(offs > width){

                av_log(avctx, AV_LOG_ERROR, "Run went out of bounds\n");

                return -1;

            }

            saved_run += run;

        }else if(cmode == 1){//horizontal mode

            int k;

            for(k = 0; k < 2; k++){

                run = 0;

                for(;;){

                    t = get_vlc2(gb, ccitt_vlc[mode].table, 9, 2);

                    if(t == -1){

                        av_log(avctx, AV_LOG_ERROR, "Incorrect code\n");

                        return -1;

                    }

                    run += t;

                    if(t < 64)

                        break;

                }

                *runs++ = run + saved_run;

                if(runs >= runend){

                    av_log(avctx, AV_LOG_ERROR, "Run overrun\n");

                    return -1;

                }

                saved_run = 0;

                offs += run;

                if(offs > width || run > width){

                    av_log(avctx, AV_LOG_ERROR, "Run went out of bounds\n");

                    return -1;

                }

                mode = !mode;

            }

        }else if(cmode == 9 || cmode == 10){

            av_log(avctx, AV_LOG_ERROR, "Special modes are not supported (yet)\n");

            return -1;

        }else{//vertical mode

            run = run_off - offs + (cmode - 5);

            run_off -= *--ref;

            offs += run;

            if(offs > width || run > width){

                av_log(avctx, AV_LOG_ERROR, "Run went out of bounds\n");

                return -1;

            }

            *runs++ = run + saved_run;

            if(runs >= runend){

                av_log(avctx, AV_LOG_ERROR, "Run overrun\n");

                return -1;

            }

            saved_run = 0;

            mode = !mode;

        }

        //sync line pointers

        while(run_off <= offs){

            run_off += *ref++;

            run_off += *ref++;

        }

    }

    *runs++ = saved_run;

    *runs++ = 0;

    return 0;

}


static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,

    int64_t offset, unsigned int bytes, QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    BdrvTrackedRequest req;

    int ret;

    int64_t sector_num = offset >> BDRV_SECTOR_BITS;

    unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    /* Handle Copy on Read and associated serialisation */

    if (flags & BDRV_REQ_COPY_ON_READ) {

        bs->copy_on_read_in_flight++;

    }

    if (bs->copy_on_read_in_flight) {

        wait_for_overlapping_requests(bs, offset, bytes);

    }

    tracked_request_begin(&req, bs, offset, bytes, false);

    if (flags & BDRV_REQ_COPY_ON_READ) {

        int pnum;

        ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);

        if (ret < 0) {

            goto out;

        }

        if (!ret || pnum != nb_sectors) {

            ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);

            goto out;

        }

    }

    /* Forward the request to the BlockDriver */

    if (!(bs->zero_beyond_eof && bs->growable)) {

        ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);

    } else {

        /* Read zeros after EOF of growable BDSes */

        int64_t len, total_sectors, max_nb_sectors;

        len = bdrv_getlength(bs);

        if (len < 0) {

            ret = len;

            goto out;

        }

        total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);

        max_nb_sectors = MAX(0, total_sectors - sector_num);

        if (max_nb_sectors > 0) {

            ret = drv->bdrv_co_readv(bs, sector_num,

                                     MIN(nb_sectors, max_nb_sectors), qiov);

        } else {

            ret = 0;

        }

        /* Reading beyond end of file is supposed to produce zeroes */

        if (ret == 0 && total_sectors < sector_num + nb_sectors) {

            uint64_t offset = MAX(0, total_sectors - sector_num);

            uint64_t bytes = (sector_num + nb_sectors - offset) *

                              BDRV_SECTOR_SIZE;

            qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);

        }

    }

out:

    tracked_request_end(&req);

    if (flags & BDRV_REQ_COPY_ON_READ) {

        bs->copy_on_read_in_flight--;

    }

    return ret;

}


void virtio_queue_notify_vq(VirtQueue *vq)

{

    if (vq->vring.desc) {

        VirtIODevice *vdev = vq->vdev;

        trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);

        vq->handle_output(vdev, vq);

    }

}


target_ulong helper_rdhwr_performance(CPUMIPSState *env)

{

    check_hwrena(env, 4);

    return env->CP0_Performance0;

}


static void openpic_reset(DeviceState *d)

{

    OpenPICState *opp = FROM_SYSBUS(typeof (*opp), sysbus_from_qdev(d));

    int i;

    opp->glbc = GLBC_RESET;

    /* Initialise controller registers */

    opp->frep = ((opp->nb_irqs - 1) << FREP_NIRQ_SHIFT) |

                ((opp->nb_cpus - 1) << FREP_NCPU_SHIFT) |

                (opp->vid << FREP_VID_SHIFT);

    opp->pint = 0;

    opp->spve = -1 & opp->vector_mask;

    opp->tifr = opp->tifr_reset;

    /* Initialise IRQ sources */

    for (i = 0; i < opp->max_irq; i++) {

        opp->src[i].ipvp = opp->ipvp_reset;

        opp->src[i].ide  = opp->ide_reset;

    }

    /* Initialise IRQ destinations */

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

        opp->dst[i].pctp      = 15;

        memset(&opp->dst[i].raised, 0, sizeof(IRQ_queue_t));

        opp->dst[i].raised.next = -1;

        memset(&opp->dst[i].servicing, 0, sizeof(IRQ_queue_t));

        opp->dst[i].servicing.next = -1;

    }

    /* Initialise timers */

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

        opp->timers[i].ticc = 0;

        opp->timers[i].tibc = TIBC_CI;

    }

    /* Go out of RESET state */

    opp->glbc = 0;

}


static uint64_t get_cluster_offset(BlockDriverState *bs,

                                   uint64_t offset, int allocate)

{

    BDRVVmdkState *s = bs->opaque;

    unsigned int l1_index, l2_offset, l2_index;

    int min_index, i, j;

    uint32_t min_count, *l2_table, tmp;

    uint64_t cluster_offset;

    l1_index = (offset >> 9) / s->l1_entry_sectors;

    if (l1_index >= s->l1_size)

        return 0;

    l2_offset = s->l1_table[l1_index];

    if (!l2_offset)

        return 0;

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

        if (l2_offset == s->l2_cache_offsets[i]) {

            /* increment the hit count */

            if (++s->l2_cache_counts[i] == 0xffffffff) {

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

                    s->l2_cache_counts[j] >>= 1;

                }

            }

            l2_table = s->l2_cache + (i * s->l2_size);

            goto found;

        }

    }

    /* not found: load a new entry in the least used one */

    min_index = 0;

    min_count = 0xffffffff;

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

        if (s->l2_cache_counts[i] < min_count) {

            min_count = s->l2_cache_counts[i];

            min_index = i;

        }

    }

    l2_table = s->l2_cache + (min_index * s->l2_size);

    if (bdrv_pread(s->hd, (int64_t)l2_offset * 512, l2_table, s->l2_size * sizeof(uint32_t)) !=

                                                                        s->l2_size * sizeof(uint32_t))

        return 0;

    s->l2_cache_offsets[min_index] = l2_offset;

    s->l2_cache_counts[min_index] = 1;

 found:

    l2_index = ((offset >> 9) / s->cluster_sectors) % s->l2_size;

    cluster_offset = le32_to_cpu(l2_table[l2_index]);

    if (!cluster_offset) {

        struct stat file_buf;

        if (!allocate)

            return 0;

        stat(s->hd->filename, &file_buf);

        cluster_offset = file_buf.st_size;

        bdrv_truncate(s->hd, cluster_offset + (s->cluster_sectors << 9));

        cluster_offset >>= 9;

        /* update L2 table */

        tmp = cpu_to_le32(cluster_offset);

        l2_table[l2_index] = tmp;

        if (bdrv_pwrite(s->hd, ((int64_t)l2_offset * 512) + (l2_index * sizeof(tmp)),

                        &tmp, sizeof(tmp)) != sizeof(tmp))

            return 0;

        /* update backup L2 table */

        if (s->l1_backup_table_offset != 0) {

            l2_offset = s->l1_backup_table[l1_index];

            if (bdrv_pwrite(s->hd, ((int64_t)l2_offset * 512) + (l2_index * sizeof(tmp)),

                            &tmp, sizeof(tmp)) != sizeof(tmp))

                return 0;

        }

        if (get_whole_cluster(bs, cluster_offset, offset, allocate) == -1)

            return 0;

    }

    cluster_offset <<= 9;

    return cluster_offset;

}


static void rbd_aio_bh_cb(void *opaque)

{

    RBDAIOCB *acb = opaque;

    if (acb->cmd == RBD_AIO_READ) {

        qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);

    }

    qemu_vfree(acb->bounce);

    acb->common.cb(acb->common.opaque, (acb->ret > 0 ? 0 : acb->ret));

    qemu_bh_delete(acb->bh);

    acb->bh = NULL;

    qemu_aio_release(acb);

}


static void test_tco_second_timeout_shutdown(void)

{

    TestData td;

    const uint16_t ticks = TCO_SECS_TO_TICKS(128);

    QDict *ad;

    td.args = "-watchdog-action shutdown";

    td.noreboot = false;

    test_init(&td);

    stop_tco(&td);

    clear_tco_status(&td);

    reset_on_second_timeout(true);

    set_tco_timeout(&td, ticks);

    load_tco(&td);

    start_tco(&td);

    clock_step(ticks * TCO_TICK_NSEC * 2);

    ad = get_watchdog_action();

    g_assert(!strcmp(qdict_get_str(ad, "action"), "shutdown"));

    QDECREF(ad);

    stop_tco(&td);

    qtest_end();

}


static void add_ptimer_tests(uint8_t policy)

{

    uint8_t *ppolicy = g_malloc(1);

    char *policy_name = g_malloc0(256);

    *ppolicy = policy;

    if (policy == PTIMER_POLICY_DEFAULT) {

        g_sprintf(policy_name, "default");

    }

    if (policy & PTIMER_POLICY_WRAP_AFTER_ONE_PERIOD) {

        g_strlcat(policy_name, "wrap_after_one_period,", 256);

    }

    if (policy & PTIMER_POLICY_CONTINUOUS_TRIGGER) {

        g_strlcat(policy_name, "continuous_trigger,", 256);

    }

    if (policy & PTIMER_POLICY_NO_IMMEDIATE_TRIGGER) {

        g_strlcat(policy_name, "no_immediate_trigger,", 256);

    }

    if (policy & PTIMER_POLICY_NO_IMMEDIATE_RELOAD) {

        g_strlcat(policy_name, "no_immediate_reload,", 256);

    }

    if (policy & PTIMER_POLICY_NO_COUNTER_ROUND_DOWN) {

        g_strlcat(policy_name, "no_counter_rounddown,", 256);

    }

    g_test_add_data_func(

        g_strdup_printf("/ptimer/set_count policy=%s", policy_name),

        ppolicy, check_set_count);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/set_limit policy=%s", policy_name),

        ppolicy, check_set_limit);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/oneshot policy=%s", policy_name),

        ppolicy, check_oneshot);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/periodic policy=%s", policy_name),

        ppolicy, check_periodic);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/on_the_fly_mode_change policy=%s", policy_name),

        ppolicy, check_on_the_fly_mode_change);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/on_the_fly_period_change policy=%s", policy_name),

        ppolicy, check_on_the_fly_period_change);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/on_the_fly_freq_change policy=%s", policy_name),

        ppolicy, check_on_the_fly_freq_change);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/run_with_period_0 policy=%s", policy_name),

        ppolicy, check_run_with_period_0);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/run_with_delta_0 policy=%s", policy_name),

        ppolicy, check_run_with_delta_0);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/periodic_with_load_0 policy=%s", policy_name),

        ppolicy, check_periodic_with_load_0);

    g_test_add_data_func(

        g_strdup_printf("/ptimer/oneshot_with_load_0 policy=%s", policy_name),

        ppolicy, check_oneshot_with_load_0);

}


void HELPER(entry)(CPUXtensaState *env, uint32_t pc, uint32_t s, uint32_t imm)
{
    int callinc = (env->sregs[PS] & PS_CALLINC) >> PS_CALLINC_SHIFT;
    if (s > 3 || ((env->sregs[PS] & (PS_WOE | PS_EXCM)) ^ PS_WOE) != 0) {
        qemu_log("Illegal entry instruction(pc = %08x), PS = %08x\n",
                pc, env->sregs[PS]);
        HELPER(exception_cause)(env, pc, ILLEGAL_INSTRUCTION_CAUSE);
    } else {
        env->regs[(callinc << 2) | (s & 3)] = env->regs[s] - (imm << 3);
        rotate_window(env, callinc);
        env->sregs[WINDOW_START] |=
            windowstart_bit(env->sregs[WINDOW_BASE], env);


static void macio_nvram_writeb(void *opaque, hwaddr addr,

                               uint64_t value, unsigned size)

{

    MacIONVRAMState *s = opaque;

    addr = (addr >> s->it_shift) & (s->size - 1);

    s->data[addr] = value;

    NVR_DPRINTF("writeb addr %04" PHYS_PRIx " val %" PRIx64 "\n", addr, value);

}