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

                      const uint8_t *buf, int buf_size)

{

    VP56Context *s = avctx->priv_data;

    AVFrame *const p = s->framep[VP56_FRAME_CURRENT];

    int remaining_buf_size = buf_size;

    int is_alpha, alpha_offset;

    if (s->has_alpha) {

        alpha_offset = bytestream_get_be24(&buf);

        remaining_buf_size -= 3;

    }

    for (is_alpha=0; is_alpha < 1+s->has_alpha; is_alpha++) {

        int mb_row, mb_col, mb_row_flip, mb_offset = 0;

        int block, y, uv, stride_y, stride_uv;

        int golden_frame = 0;

        int res;

        s->modelp = &s->models[is_alpha];

        res = s->parse_header(s, buf, remaining_buf_size, &golden_frame);

        if (!res)

            return -1;

        if (!is_alpha) {

            p->reference = 1;

            if (avctx->get_buffer(avctx, p) < 0) {

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

                return -1;

            }

            if (res == 2)

                if (vp56_size_changed(avctx)) {

                    avctx->release_buffer(avctx, p);

                    return -1;

                }

        }

        if (p->key_frame) {

            p->pict_type = FF_I_TYPE;

            s->default_models_init(s);

            for (block=0; block<s->mb_height*s->mb_width; block++)

                s->macroblocks[block].type = VP56_MB_INTRA;

        } else {

            p->pict_type = FF_P_TYPE;

            vp56_parse_mb_type_models(s);

            s->parse_vector_models(s);

            s->mb_type = VP56_MB_INTER_NOVEC_PF;

        }

        s->parse_coeff_models(s);

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

        s->prev_dc[1][VP56_FRAME_CURRENT] = 128;

        s->prev_dc[2][VP56_FRAME_CURRENT] = 128;

        for (block=0; block < 4*s->mb_width+6; block++) {

            s->above_blocks[block].ref_frame = VP56_FRAME_NONE;

            s->above_blocks[block].dc_coeff = 0;

            s->above_blocks[block].not_null_dc = 0;

        }

        s->above_blocks[2*s->mb_width + 2].ref_frame = VP56_FRAME_CURRENT;

        s->above_blocks[3*s->mb_width + 4].ref_frame = VP56_FRAME_CURRENT;

        stride_y  = p->linesize[0];

        stride_uv = p->linesize[1];

        if (s->flip < 0)

            mb_offset = 7;

        /* main macroblocks loop */

        for (mb_row=0; mb_row<s->mb_height; mb_row++) {

            if (s->flip < 0)

                mb_row_flip = s->mb_height - mb_row - 1;

            else

                mb_row_flip = mb_row;

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

                s->left_block[block].ref_frame = VP56_FRAME_NONE;

                s->left_block[block].dc_coeff = 0;

                s->left_block[block].not_null_dc = 0;

            }

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

            memset(s->coeff_ctx_last, 24, sizeof(s->coeff_ctx_last));

            s->above_block_idx[0] = 1;

            s->above_block_idx[1] = 2;

            s->above_block_idx[2] = 1;

            s->above_block_idx[3] = 2;

            s->above_block_idx[4] = 2*s->mb_width + 2 + 1;

            s->above_block_idx[5] = 3*s->mb_width + 4 + 1;

            s->block_offset[s->frbi] = (mb_row_flip*16 + mb_offset) * stride_y;

            s->block_offset[s->srbi] = s->block_offset[s->frbi] + 8*stride_y;

            s->block_offset[1] = s->block_offset[0] + 8;

            s->block_offset[3] = s->block_offset[2] + 8;

            s->block_offset[4] = (mb_row_flip*8 + mb_offset) * stride_uv;

            s->block_offset[5] = s->block_offset[4];

            for (mb_col=0; mb_col<s->mb_width; mb_col++) {

                vp56_decode_mb(s, mb_row, mb_col, is_alpha);

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

                    s->above_block_idx[y] += 2;

                    s->block_offset[y] += 16;

                }

                for (uv=4; uv<6; uv++) {

                    s->above_block_idx[uv] += 1;

                    s->block_offset[uv] += 8;

                }

            }

        }

        if (p->key_frame || golden_frame) {

            if (s->framep[VP56_FRAME_GOLDEN]->data[0] &&

                s->framep[VP56_FRAME_GOLDEN] != s->framep[VP56_FRAME_GOLDEN2])

                avctx->release_buffer(avctx, s->framep[VP56_FRAME_GOLDEN]);

            s->framep[VP56_FRAME_GOLDEN] = p;

        }

        if (s->has_alpha) {

            FFSWAP(AVFrame *, s->framep[VP56_FRAME_GOLDEN],

                              s->framep[VP56_FRAME_GOLDEN2]);

            buf += alpha_offset;

            remaining_buf_size -= alpha_offset;

        }

    }

    if (s->framep[VP56_FRAME_PREVIOUS] == s->framep[VP56_FRAME_GOLDEN] ||

        s->framep[VP56_FRAME_PREVIOUS] == s->framep[VP56_FRAME_GOLDEN2]) {

        if (s->framep[VP56_FRAME_UNUSED] != s->framep[VP56_FRAME_GOLDEN] &&

            s->framep[VP56_FRAME_UNUSED] != s->framep[VP56_FRAME_GOLDEN2])

            FFSWAP(AVFrame *, s->framep[VP56_FRAME_PREVIOUS],

                              s->framep[VP56_FRAME_UNUSED]);

        else

            FFSWAP(AVFrame *, s->framep[VP56_FRAME_PREVIOUS],

                              s->framep[VP56_FRAME_UNUSED2]);

    } else if (s->framep[VP56_FRAME_PREVIOUS]->data[0])

        avctx->release_buffer(avctx, s->framep[VP56_FRAME_PREVIOUS]);

    FFSWAP(AVFrame *, s->framep[VP56_FRAME_CURRENT],

                      s->framep[VP56_FRAME_PREVIOUS]);

    *(AVFrame*)data = *p;

    *data_size = sizeof(AVFrame);

    return buf_size;

}


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

{

#ifdef HAVE_MMX

	asm volatile(

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

		"1:				\n\t"

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

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

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

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

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

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

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

		" js 1b				\n\t"

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

		: "%"REG_a

	);

#else

	int i;

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

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

#endif

}


static av_cold int wmavoice_decode_init(AVCodecContext *ctx)

{

    int n, flags, pitch_range, lsp16_flag;

    WMAVoiceContext *s = ctx->priv_data;

    /**

     * Extradata layout:

     * - byte  0-18: WMAPro-in-WMAVoice extradata (see wmaprodec.c),

     * - byte 19-22: flags field (annoyingly in LE; see below for known

     *               values),

     * - byte 23-46: variable bitmode tree (really just 17 * 3 bits,

     *               rest is 0).

     */

    if (ctx->extradata_size != 46) {

        av_log(ctx, AV_LOG_ERROR,

               "Invalid extradata size %d (should be 46)\n",

               ctx->extradata_size);

    flags                = AV_RL32(ctx->extradata + 18);

    s->spillover_bitsize = 3 + av_ceil_log2(ctx->block_align);

    s->do_apf            =    flags & 0x1;

    if (s->do_apf) {

        ff_rdft_init(&s->rdft,  7, DFT_R2C);

        ff_rdft_init(&s->irdft, 7, IDFT_C2R);

        ff_dct_init(&s->dct,  6, DCT_I);

        ff_dct_init(&s->dst,  6, DST_I);

        ff_sine_window_init(s->cos, 256);

        memcpy(&s->sin[255], s->cos, 256 * sizeof(s->cos[0]));

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

            s->sin[n]       = -s->sin[510 - n];

            s->cos[510 - n] =  s->cos[n];

    s->denoise_strength  =   (flags >> 2) & 0xF;

    if (s->denoise_strength >= 12) {

        av_log(ctx, AV_LOG_ERROR,

               "Invalid denoise filter strength %d (max=11)\n",

               s->denoise_strength);

    s->denoise_tilt_corr = !!(flags & 0x40);

    s->dc_level          =   (flags >> 7) & 0xF;

    s->lsp_q_mode        = !!(flags & 0x2000);

    s->lsp_def_mode      = !!(flags & 0x4000);

    lsp16_flag           =    flags & 0x1000;

    if (lsp16_flag) {

        s->lsps               = 16;

        s->frame_lsp_bitsize  = 34;

        s->sframe_lsp_bitsize = 60;

    } else {

        s->lsps               = 10;

        s->frame_lsp_bitsize  = 24;

        s->sframe_lsp_bitsize = 48;

    for (n = 0; n < s->lsps; n++)

        s->prev_lsps[n] = M_PI * (n + 1.0) / (s->lsps + 1.0);

    init_get_bits(&s->gb, ctx->extradata + 22, (ctx->extradata_size - 22) << 3);

    if (decode_vbmtree(&s->gb, s->vbm_tree) < 0) {

        av_log(ctx, AV_LOG_ERROR, "Invalid VBM tree; broken extradata?\n");

    s->min_pitch_val    = ((ctx->sample_rate << 8)      /  400 + 50) >> 8;

    s->max_pitch_val    = ((ctx->sample_rate << 8) * 37 / 2000 + 50) >> 8;

    pitch_range         = s->max_pitch_val - s->min_pitch_val;

    if (pitch_range <= 0) {

        av_log(ctx, AV_LOG_ERROR, "Invalid pitch range; broken extradata?\n");

    s->pitch_nbits      = av_ceil_log2(pitch_range);

    s->last_pitch_val   = 40;

    s->last_acb_type    = ACB_TYPE_NONE;

    s->history_nsamples = s->max_pitch_val + 8;

    if (s->min_pitch_val < 1 || s->history_nsamples > MAX_SIGNAL_HISTORY) {

        int min_sr = ((((1 << 8) - 50) * 400) + 0xFF) >> 8,

            max_sr = ((((MAX_SIGNAL_HISTORY - 8) << 8) + 205) * 2000 / 37) >> 8;

        av_log(ctx, AV_LOG_ERROR,

               "Unsupported samplerate %d (min=%d, max=%d)\n",

               ctx->sample_rate, min_sr, max_sr); // 322-22097 Hz

    s->block_conv_table[0]      = s->min_pitch_val;

    s->block_conv_table[1]      = (pitch_range * 25) >> 6;

    s->block_conv_table[2]      = (pitch_range * 44) >> 6;

    s->block_conv_table[3]      = s->max_pitch_val - 1;

    s->block_delta_pitch_hrange = (pitch_range >> 3) & ~0xF;

    s->block_delta_pitch_nbits  = 1 + av_ceil_log2(s->block_delta_pitch_hrange);

    s->block_pitch_range        = s->block_conv_table[2] +

                                  s->block_conv_table[3] + 1 +

                                  2 * (s->block_conv_table[1] - 2 * s->min_pitch_val);

    s->block_pitch_nbits        = av_ceil_log2(s->block_pitch_range);

    ctx->sample_fmt             = AV_SAMPLE_FMT_FLT;

    return 0;


static void ehci_queues_rip_unused(EHCIState *ehci, int async)

{

    EHCIQueueHead *head = async ? &ehci->aqueues : &ehci->pqueues;

    EHCIQueue *q, *tmp;

    QTAILQ_FOREACH_SAFE(q, head, next, tmp) {

        if (q->seen) {

            q->seen = 0;

            q->ts = ehci->last_run_ns;

            continue;

        }

        if (ehci->last_run_ns < q->ts + 250000000) {

            /* allow 0.25 sec idle */

            continue;

        }

        ehci_free_queue(q, async);

    }

}


void kvm_arch_pre_run(CPUState *env, struct kvm_run *run)

{

    /* Inject NMI */

    if (env->interrupt_request & CPU_INTERRUPT_NMI) {

        env->interrupt_request &= ~CPU_INTERRUPT_NMI;

        DPRINTF("injected NMI\n");

        kvm_vcpu_ioctl(env, KVM_NMI);

    }

    if (!kvm_irqchip_in_kernel()) {

        /* Force the VCPU out of its inner loop to process the INIT request */

        if (env->interrupt_request & CPU_INTERRUPT_INIT) {

            env->exit_request = 1;

        }

        /* Try to inject an interrupt if the guest can accept it */

        if (run->ready_for_interrupt_injection &&

            (env->interrupt_request & CPU_INTERRUPT_HARD) &&

            (env->eflags & IF_MASK)) {

            int irq;

            env->interrupt_request &= ~CPU_INTERRUPT_HARD;

            irq = cpu_get_pic_interrupt(env);

            if (irq >= 0) {

                struct kvm_interrupt intr;

                intr.irq = irq;

                /* FIXME: errors */

                DPRINTF("injected interrupt %d\n", irq);

                kvm_vcpu_ioctl(env, KVM_INTERRUPT, &intr);

            }

        }

        /* If we have an interrupt but the guest is not ready to receive an

         * interrupt, request an interrupt window exit.  This will

         * cause a return to userspace as soon as the guest is ready to

         * receive interrupts. */

        if ((env->interrupt_request & CPU_INTERRUPT_HARD)) {

            run->request_interrupt_window = 1;

        } else {

            run->request_interrupt_window = 0;

        }

        DPRINTF("setting tpr\n");

        run->cr8 = cpu_get_apic_tpr(env->apic_state);

    }

}


static void test_acpi_one(const char *params, test_data *data)

{

    char *args;

    uint8_t signature_low;

    uint8_t signature_high;

    uint16_t signature;

    int i;

    const char *device = "";

    if (!g_strcmp0(data->machine, MACHINE_Q35)) {

        device = ",id=hd -device ide-hd,drive=hd";

    }

    args = g_strdup_printf("-net none -display none %s -drive file=%s%s,",

                           params ? params : "", disk, device);

    qtest_start(args);

   /* Wait at most 1 minute */

#define TEST_DELAY (1 * G_USEC_PER_SEC / 10)

#define TEST_CYCLES MAX((60 * G_USEC_PER_SEC / TEST_DELAY), 1)

    /* Poll until code has run and modified memory.  Once it has we know BIOS

     * initialization is done.  TODO: check that IP reached the halt

     * instruction.

     */

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

        signature_low = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET);

        signature_high = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1);

        signature = (signature_high << 8) | signature_low;

        if (signature == SIGNATURE) {

            break;

        }

        g_usleep(TEST_DELAY);

    }

    g_assert_cmphex(signature, ==, SIGNATURE);

    test_acpi_rsdp_address(data);

    test_acpi_rsdp_table(data);

    test_acpi_rsdt_table(data);

    test_acpi_fadt_table(data);

    test_acpi_facs_table(data);

    test_acpi_dsdt_table(data);

    test_acpi_tables(data);

    if (iasl) {

        if (getenv(ACPI_REBUILD_EXPECTED_AML)) {

            dump_aml_files(data, true);

        } else {

            test_acpi_asl(data);

        }

    }

    test_smbios_ep_address(data);

    test_smbios_ep_table(data);

    test_smbios_structs(data);

    qtest_quit(global_qtest);

    g_free(args);

}


static int ea_read_header(AVFormatContext *s,
                          AVFormatParameters *ap)
{
    EaDemuxContext *ea = s->priv_data;
    AVStream *st;
    if (!process_ea_header(s))
        return AVERROR(EIO);
    if (ea->video_codec) {
        /* initialize the video decoder stream */
        st = av_new_stream(s, 0);
        if (!st)
            return AVERROR(ENOMEM);
        ea->video_stream_index = st->index;
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
        st->codec->codec_id = ea->video_codec;
        st->codec->codec_tag = 0;  /* no fourcc */
        st->codec->time_base = ea->time_base;
        st->codec->width = ea->width;
        st->codec->height = ea->height;
    if (ea->num_channels <= 0) {
        av_log(s, AV_LOG_WARNING, "Unsupported number of channels: %d\n", ea->num_channels);
    if (ea->audio_codec) {
        /* initialize the audio decoder stream */
        st = av_new_stream(s, 0);
        if (!st)
            return AVERROR(ENOMEM);
        av_set_pts_info(st, 33, 1, ea->sample_rate);
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
        st->codec->codec_id = ea->audio_codec;
        st->codec->codec_tag = 0;  /* no tag */
        st->codec->channels = ea->num_channels;
        st->codec->sample_rate = ea->sample_rate;
        st->codec->bits_per_coded_sample = ea->bytes * 8;
        st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
            st->codec->bits_per_coded_sample / 4;
        st->codec->block_align = st->codec->channels*st->codec->bits_per_coded_sample;
        ea->audio_stream_index = st->index;
        ea->audio_frame_counter = 0;
    return 1;


PCIBus *pci_get_bus_devfn(int *devfnp, PCIBus *root, const char *devaddr)

{

    int dom, bus;

    unsigned slot;

    assert(!root->parent_dev);

    if (!root) {

        fprintf(stderr, "No primary PCI bus\n");

        return NULL;

    }

    if (!devaddr) {

        *devfnp = -1;

        return pci_find_bus_nr(root, 0);

    }

    if (pci_parse_devaddr(devaddr, &dom, &bus, &slot, NULL) < 0) {

        return NULL;

    }

    if (dom != 0) {

        fprintf(stderr, "No support for non-zero PCI domains\n");

        return NULL;

    }

    *devfnp = PCI_DEVFN(slot, 0);

    return pci_find_bus_nr(root, bus);

}


static void destroy_page_desc(uint16_t section_index)

{

    MemoryRegionSection *section = &phys_sections[section_index];

    MemoryRegion *mr = section->mr;

    if (mr->subpage) {

        subpage_t *subpage = container_of(mr, subpage_t, iomem);

        memory_region_destroy(&subpage->iomem);

        g_free(subpage);

    }

}


static void opt_output_file(const char *filename)

{

    AVFormatContext *oc;

    int err, use_video, use_audio, use_subtitle;

    int input_has_video, input_has_audio, input_has_subtitle;

    AVFormatParameters params, *ap = &params;

    AVOutputFormat *file_oformat;

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

        filename = "pipe:";

    oc = avformat_alloc_context();

    if (!oc) {

        print_error(filename, AVERROR(ENOMEM));

        ffmpeg_exit(1);

    }

    if (last_asked_format) {

        file_oformat = av_guess_format(last_asked_format, NULL, NULL);

        if (!file_oformat) {

            fprintf(stderr, "Requested output format '%s' is not a suitable output format\n", last_asked_format);

            ffmpeg_exit(1);

        }

        last_asked_format = NULL;

    } else {

        file_oformat = av_guess_format(NULL, filename, NULL);

        if (!file_oformat) {

            fprintf(stderr, "Unable to find a suitable output format for '%s'\n",

                    filename);

            ffmpeg_exit(1);

        }

    }

    oc->oformat = file_oformat;

    av_strlcpy(oc->filename, filename, sizeof(oc->filename));

    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);

            ffmpeg_exit(1);

        }

    } else {

        use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;

        use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;

        use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;

        /* disable if no corresponding type found and at least one

           input file */

        if (nb_input_files > 0) {

            check_audio_video_sub_inputs(&input_has_video, &input_has_audio,

                                         &input_has_subtitle);

            if (!input_has_video)

                use_video = 0;

            if (!input_has_audio)

                use_audio = 0;

            if (!input_has_subtitle)

                use_subtitle = 0;

        }

        /* manual disable */

        if (audio_disable) {

            use_audio = 0;

        }

        if (video_disable) {

            use_video = 0;

        }

        if (subtitle_disable) {

            use_subtitle = 0;

        }

        if (use_video) {

            new_video_stream(oc);

        }

        if (use_audio) {

            new_audio_stream(oc);

        }

        if (use_subtitle) {

            new_subtitle_stream(oc);

        }

        oc->timestamp = recording_timestamp;

        for(; metadata_count>0; metadata_count--){

            av_metadata_set2(&oc->metadata, metadata[metadata_count-1].key,

                                            metadata[metadata_count-1].value, 0);

        }

        av_metadata_conv(oc, oc->oformat->metadata_conv, NULL);

    }

    output_files[nb_output_files++] = oc;

    /* 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_NUMEXPECTED);

            ffmpeg_exit(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 (url_exist(filename)) {

                if (!using_stdin) {

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

                    fflush(stderr);

                    if (!read_yesno()) {

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

                        ffmpeg_exit(1);

                    }

                }

                else {

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

                    ffmpeg_exit(1);

                }

            }

        }

        /* open the file */

        if ((err = url_fopen(&oc->pb, filename, URL_WRONLY)) < 0) {

            print_error(filename, err);

            ffmpeg_exit(1);

        }

    }

    memset(ap, 0, sizeof(*ap));

    if (av_set_parameters(oc, ap) < 0) {

        fprintf(stderr, "%s: Invalid encoding parameters\n",

                oc->filename);

        ffmpeg_exit(1);

    }

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

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

    oc->loop_output = loop_output;

    oc->flags |= AVFMT_FLAG_NONBLOCK;

    set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);

    nb_streamid_map = 0;

}


void vnc_display_add_client(DisplayState *ds, int csock, int skipauth)

{

    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;

    vnc_connect(vs, csock, skipauth, 0);

}


av_cold void ff_vp9dsp_init_x86(VP9DSPContext *dsp)

{

#if HAVE_YASM

    int cpu_flags = av_get_cpu_flags();

#define init_fpel(idx1, idx2, sz, type, opt) \

    dsp->mc[idx1][FILTER_8TAP_SMOOTH ][idx2][0][0] = \

    dsp->mc[idx1][FILTER_8TAP_REGULAR][idx2][0][0] = \

    dsp->mc[idx1][FILTER_8TAP_SHARP  ][idx2][0][0] = \

    dsp->mc[idx1][FILTER_BILINEAR    ][idx2][0][0] = ff_vp9_##type##sz##_##opt

#define init_subpel1(idx1, idx2, idxh, idxv, sz, dir, type, opt) \

    dsp->mc[idx1][FILTER_8TAP_SMOOTH ][idx2][idxh][idxv] = type##_8tap_smooth_##sz##dir##_##opt; \

    dsp->mc[idx1][FILTER_8TAP_REGULAR][idx2][idxh][idxv] = type##_8tap_regular_##sz##dir##_##opt; \

    dsp->mc[idx1][FILTER_8TAP_SHARP  ][idx2][idxh][idxv] = type##_8tap_sharp_##sz##dir##_##opt

#define init_subpel2_32_64(idx, idxh, idxv, dir, type, opt) \

    init_subpel1(0, idx, idxh, idxv, 64, dir, type, opt); \

    init_subpel1(1, idx, idxh, idxv, 32, dir, type, opt)

#define init_subpel2(idx, idxh, idxv, dir, type, opt) \

    init_subpel2_32_64(idx, idxh, idxv, dir, type, opt); \

    init_subpel1(2, idx, idxh, idxv, 16, dir, type, opt); \

    init_subpel1(3, idx, idxh, idxv,  8, dir, type, opt); \

    init_subpel1(4, idx, idxh, idxv,  4, dir, type, opt)

#define init_subpel3(idx, type, opt) \

    init_subpel2(idx, 1, 1, hv, type, opt); \

    init_subpel2(idx, 0, 1, v, type, opt); \

    init_subpel2(idx, 1, 0, h, type, opt)

#define init_lpf(opt) do { \

    if (ARCH_X86_64) { \

        dsp->loop_filter_16[0] = ff_vp9_loop_filter_h_16_16_##opt; \

        dsp->loop_filter_16[1] = ff_vp9_loop_filter_v_16_16_##opt; \

        dsp->loop_filter_mix2[0][0][0] = ff_vp9_loop_filter_h_44_16_##opt; \

        dsp->loop_filter_mix2[0][0][1] = ff_vp9_loop_filter_v_44_16_##opt; \

        dsp->loop_filter_mix2[0][1][0] = ff_vp9_loop_filter_h_48_16_##opt; \

        dsp->loop_filter_mix2[0][1][1] = ff_vp9_loop_filter_v_48_16_##opt; \

        dsp->loop_filter_mix2[1][0][0] = ff_vp9_loop_filter_h_84_16_##opt; \

        dsp->loop_filter_mix2[1][0][1] = ff_vp9_loop_filter_v_84_16_##opt; \

        dsp->loop_filter_mix2[1][1][0] = ff_vp9_loop_filter_h_88_16_##opt; \

        dsp->loop_filter_mix2[1][1][1] = ff_vp9_loop_filter_v_88_16_##opt; \

    } \

} while (0)

#define init_ipred(tx, sz, opt) do { \

    dsp->intra_pred[tx][HOR_PRED]             = ff_vp9_ipred_h_##sz##x##sz##_##opt; \

    dsp->intra_pred[tx][DIAG_DOWN_LEFT_PRED]  = ff_vp9_ipred_dl_##sz##x##sz##_##opt; \

    dsp->intra_pred[tx][DIAG_DOWN_RIGHT_PRED] = ff_vp9_ipred_dr_##sz##x##sz##_##opt; \

    dsp->intra_pred[tx][HOR_DOWN_PRED]        = ff_vp9_ipred_hd_##sz##x##sz##_##opt; \

    dsp->intra_pred[tx][VERT_LEFT_PRED]       = ff_vp9_ipred_vl_##sz##x##sz##_##opt; \

    dsp->intra_pred[tx][HOR_UP_PRED]          = ff_vp9_ipred_hu_##sz##x##sz##_##opt; \

    if (ARCH_X86_64 || tx != TX_32X32) { \

        dsp->intra_pred[tx][VERT_RIGHT_PRED]      = ff_vp9_ipred_vr_##sz##x##sz##_##opt; \

        dsp->intra_pred[tx][TM_VP8_PRED]          = ff_vp9_ipred_tm_##sz##x##sz##_##opt; \

    } \

} while (0)

#define init_dc_ipred(tx, sz, opt) do { \

    init_ipred(tx, sz, opt); \

    dsp->intra_pred[tx][DC_PRED]              = ff_vp9_ipred_dc_##sz##x##sz##_##opt; \

    dsp->intra_pred[tx][LEFT_DC_PRED]         = ff_vp9_ipred_dc_left_##sz##x##sz##_##opt; \

    dsp->intra_pred[tx][TOP_DC_PRED]          = ff_vp9_ipred_dc_top_##sz##x##sz##_##opt; \

} while (0)

    if (EXTERNAL_MMX(cpu_flags)) {

        init_fpel(4, 0,  4, put, mmx);

        init_fpel(3, 0,  8, put, mmx);

        dsp->itxfm_add[4 /* lossless */][DCT_DCT] =

        dsp->itxfm_add[4 /* lossless */][ADST_DCT] =

        dsp->itxfm_add[4 /* lossless */][DCT_ADST] =

        dsp->itxfm_add[4 /* lossless */][ADST_ADST] = ff_vp9_iwht_iwht_4x4_add_mmx;

        dsp->intra_pred[TX_8X8][VERT_PRED] = ff_vp9_ipred_v_8x8_mmx;

    }

    if (EXTERNAL_MMXEXT(cpu_flags)) {

        init_fpel(4, 1,  4, avg, mmxext);

        init_fpel(3, 1,  8, avg, mmxext);

        dsp->itxfm_add[TX_4X4][DCT_DCT] = ff_vp9_idct_idct_4x4_add_mmxext;

    }

    if (EXTERNAL_SSE(cpu_flags)) {

        init_fpel(2, 0, 16, put, sse);

        init_fpel(1, 0, 32, put, sse);

        init_fpel(0, 0, 64, put, sse);

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        init_fpel(2, 1, 16, avg, sse2);

        init_fpel(1, 1, 32, avg, sse2);

        init_fpel(0, 1, 64, avg, sse2);

        init_lpf(sse2);

        dsp->itxfm_add[TX_4X4][ADST_DCT]  = ff_vp9_idct_iadst_4x4_add_sse2;

        dsp->itxfm_add[TX_4X4][DCT_ADST]  = ff_vp9_iadst_idct_4x4_add_sse2;

        dsp->itxfm_add[TX_4X4][ADST_ADST] = ff_vp9_iadst_iadst_4x4_add_sse2;

        dsp->itxfm_add[TX_8X8][DCT_DCT] = ff_vp9_idct_idct_8x8_add_sse2;

        dsp->itxfm_add[TX_8X8][ADST_DCT]  = ff_vp9_idct_iadst_8x8_add_sse2;

        dsp->itxfm_add[TX_8X8][DCT_ADST]  = ff_vp9_iadst_idct_8x8_add_sse2;

        dsp->itxfm_add[TX_8X8][ADST_ADST] = ff_vp9_iadst_iadst_8x8_add_sse2;

        dsp->itxfm_add[TX_16X16][DCT_DCT]   = ff_vp9_idct_idct_16x16_add_sse2;

        dsp->itxfm_add[TX_16X16][ADST_DCT]  = ff_vp9_idct_iadst_16x16_add_sse2;

        dsp->itxfm_add[TX_16X16][DCT_ADST]  = ff_vp9_iadst_idct_16x16_add_sse2;

        dsp->itxfm_add[TX_16X16][ADST_ADST] = ff_vp9_iadst_iadst_16x16_add_sse2;

        dsp->itxfm_add[TX_32X32][ADST_ADST] =

        dsp->itxfm_add[TX_32X32][ADST_DCT] =

        dsp->itxfm_add[TX_32X32][DCT_ADST] =

        dsp->itxfm_add[TX_32X32][DCT_DCT] = ff_vp9_idct_idct_32x32_add_sse2;

        dsp->intra_pred[TX_16X16][VERT_PRED] = ff_vp9_ipred_v_16x16_sse2;

        dsp->intra_pred[TX_32X32][VERT_PRED] = ff_vp9_ipred_v_32x32_sse2;

    }

    if (EXTERNAL_SSSE3(cpu_flags)) {

        init_subpel3(0, put, ssse3);

        init_subpel3(1, avg, ssse3);

        dsp->itxfm_add[TX_4X4][DCT_DCT] = ff_vp9_idct_idct_4x4_add_ssse3;

        dsp->itxfm_add[TX_4X4][ADST_DCT]  = ff_vp9_idct_iadst_4x4_add_ssse3;

        dsp->itxfm_add[TX_4X4][DCT_ADST]  = ff_vp9_iadst_idct_4x4_add_ssse3;

        dsp->itxfm_add[TX_4X4][ADST_ADST] = ff_vp9_iadst_iadst_4x4_add_ssse3;

        dsp->itxfm_add[TX_8X8][DCT_DCT] = ff_vp9_idct_idct_8x8_add_ssse3;

        dsp->itxfm_add[TX_8X8][ADST_DCT]  = ff_vp9_idct_iadst_8x8_add_ssse3;

        dsp->itxfm_add[TX_8X8][DCT_ADST]  = ff_vp9_iadst_idct_8x8_add_ssse3;

        dsp->itxfm_add[TX_8X8][ADST_ADST] = ff_vp9_iadst_iadst_8x8_add_ssse3;

        dsp->itxfm_add[TX_16X16][DCT_DCT]   = ff_vp9_idct_idct_16x16_add_ssse3;

        dsp->itxfm_add[TX_16X16][ADST_DCT]  = ff_vp9_idct_iadst_16x16_add_ssse3;

        dsp->itxfm_add[TX_16X16][DCT_ADST]  = ff_vp9_iadst_idct_16x16_add_ssse3;

        dsp->itxfm_add[TX_16X16][ADST_ADST] = ff_vp9_iadst_iadst_16x16_add_ssse3;

        dsp->itxfm_add[TX_32X32][ADST_ADST] =

        dsp->itxfm_add[TX_32X32][ADST_DCT] =

        dsp->itxfm_add[TX_32X32][DCT_ADST] =

        dsp->itxfm_add[TX_32X32][DCT_DCT] = ff_vp9_idct_idct_32x32_add_ssse3;

        init_lpf(ssse3);

        init_dc_ipred(TX_4X4,    4, ssse3);

        init_dc_ipred(TX_8X8,    8, ssse3);

        init_dc_ipred(TX_16X16, 16, ssse3);

        init_dc_ipred(TX_32X32, 32, ssse3);

    }

    if (EXTERNAL_AVX(cpu_flags)) {

        dsp->itxfm_add[TX_8X8][DCT_DCT] = ff_vp9_idct_idct_8x8_add_avx;

        dsp->itxfm_add[TX_8X8][ADST_DCT]  = ff_vp9_idct_iadst_8x8_add_avx;

        dsp->itxfm_add[TX_8X8][DCT_ADST]  = ff_vp9_iadst_idct_8x8_add_avx;

        dsp->itxfm_add[TX_8X8][ADST_ADST] = ff_vp9_iadst_iadst_8x8_add_avx;

        dsp->itxfm_add[TX_16X16][DCT_DCT] = ff_vp9_idct_idct_16x16_add_avx;

        dsp->itxfm_add[TX_16X16][ADST_DCT]  = ff_vp9_idct_iadst_16x16_add_avx;

        dsp->itxfm_add[TX_16X16][DCT_ADST]  = ff_vp9_iadst_idct_16x16_add_avx;

        dsp->itxfm_add[TX_16X16][ADST_ADST] = ff_vp9_iadst_iadst_16x16_add_avx;

        dsp->itxfm_add[TX_32X32][ADST_ADST] =

        dsp->itxfm_add[TX_32X32][ADST_DCT] =

        dsp->itxfm_add[TX_32X32][DCT_ADST] =

        dsp->itxfm_add[TX_32X32][DCT_DCT] = ff_vp9_idct_idct_32x32_add_avx;

        init_fpel(1, 0, 32, put, avx);

        init_fpel(0, 0, 64, put, avx);

        init_lpf(avx);

        init_ipred(TX_8X8,    8, avx);

        init_ipred(TX_16X16, 16, avx);

        init_ipred(TX_32X32, 32, avx);

    }

    if (EXTERNAL_AVX2(cpu_flags)) {

        init_fpel(1, 1, 32, avg, avx2);

        init_fpel(0, 1, 64, avg, avx2);

        if (ARCH_X86_64) {

#if ARCH_X86_64 && HAVE_AVX2_EXTERNAL

            init_subpel2_32_64(0, 1, 1, hv, put, avx2);

            init_subpel2_32_64(0, 0, 1, v,  put, avx2);

            init_subpel2_32_64(0, 1, 0, h,  put, avx2);

            init_subpel2_32_64(1, 1, 1, hv, avg, avx2);

            init_subpel2_32_64(1, 0, 1, v,  avg, avx2);

            init_subpel2_32_64(1, 1, 0, h,  avg, avx2);

#endif

        }

        dsp->intra_pred[TX_32X32][DC_PRED] = ff_vp9_ipred_dc_32x32_avx2;

        dsp->intra_pred[TX_32X32][LEFT_DC_PRED] = ff_vp9_ipred_dc_left_32x32_avx2;

        dsp->intra_pred[TX_32X32][TOP_DC_PRED] = ff_vp9_ipred_dc_top_32x32_avx2;

        dsp->intra_pred[TX_32X32][VERT_PRED] = ff_vp9_ipred_v_32x32_avx2;

        dsp->intra_pred[TX_32X32][HOR_PRED] = ff_vp9_ipred_h_32x32_avx2;

        dsp->intra_pred[TX_32X32][TM_VP8_PRED] = ff_vp9_ipred_tm_32x32_avx2;

    }

#undef init_fpel

#undef init_subpel1

#undef init_subpel2

#undef init_subpel3

#endif /* HAVE_YASM */

}


static void tracked_request_end(BdrvTrackedRequest *req)

{

    QLIST_REMOVE(req, list);

}


static TranslationBlock *tb_alloc(target_ulong pc)

{

    TranslationBlock *tb;

    if (tcg_ctx.tb_ctx.nb_tbs >= tcg_ctx.code_gen_max_blocks ||

        (tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer) >=

         tcg_ctx.code_gen_buffer_max_size) {

        return NULL;

    }

    tb = &tcg_ctx.tb_ctx.tbs[tcg_ctx.tb_ctx.nb_tbs++];

    tb->pc = pc;

    tb->cflags = 0;

    return tb;

}


static void mxf_write_partition(AVFormatContext *s, int bodysid,

                                int indexsid,

                                const uint8_t *key, int write_metadata)

{

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t header_byte_count_offset;

    unsigned index_byte_count = 0;

    uint64_t partition_offset = avio_tell(pb);

    if (!mxf->edit_unit_byte_count && mxf->edit_units_count)

        index_byte_count = 85 + 12+(s->nb_streams+1)*6 +

            12+mxf->edit_units_count*(11+mxf->slice_count*4);

    else if (mxf->edit_unit_byte_count && indexsid)

        index_byte_count = 80;

    if (index_byte_count) {

        // add encoded ber length

        index_byte_count += 16 + klv_ber_length(index_byte_count);

        index_byte_count += klv_fill_size(index_byte_count);

    }

    if (!memcmp(key, body_partition_key, 16)) {

        mxf->body_partition_offset =

            av_realloc(mxf->body_partition_offset,

                       (mxf->body_partitions_count+1)*

                       sizeof(*mxf->body_partition_offset));

        mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;

    }

    // write klv

    avio_write(pb, key, 16);

    klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);

    // write partition value

    avio_wb16(pb, 1); // majorVersion

    avio_wb16(pb, 2); // minorVersion

    avio_wb32(pb, KAG_SIZE); // KAGSize

    avio_wb64(pb, partition_offset); // ThisPartition

    if (!memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)

        avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition

    else if (!memcmp(key, footer_partition_key, 16) && mxf->body_partitions_count)

        avio_wb64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition

    else

        avio_wb64(pb, 0);

    avio_wb64(pb, mxf->footer_partition_offset); // footerPartition

    // set offset

    header_byte_count_offset = avio_tell(pb);

    avio_wb64(pb, 0); // headerByteCount, update later

    // indexTable

    avio_wb64(pb, index_byte_count); // indexByteCount

    avio_wb32(pb, index_byte_count ? indexsid : 0); // indexSID

    // BodyOffset

    if (bodysid && mxf->edit_units_count && mxf->body_partitions_count) {

        avio_wb64(pb, mxf->body_offset);

    } else

        avio_wb64(pb, 0);

    avio_wb32(pb, bodysid); // bodySID

    // operational pattern

    avio_write(pb, op1a_ul, 16);

    // essence container

    mxf_write_essence_container_refs(s);

    if (write_metadata) {

        // mark the start of the headermetadata and calculate metadata size

        int64_t pos, start;

        unsigned header_byte_count;

        mxf_write_klv_fill(s);

        start = avio_tell(s->pb);

        mxf_write_primer_pack(s);

        mxf_write_header_metadata_sets(s);

        pos = avio_tell(s->pb);

        header_byte_count = pos - start + klv_fill_size(pos);

        // update header_byte_count

        avio_seek(pb, header_byte_count_offset, SEEK_SET);

        avio_wb64(pb, header_byte_count);

        avio_seek(pb, pos, SEEK_SET);

    }

    avio_flush(pb);

}


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

	long width, long height,

	long lumStride, long chromStride, long dstStride, long vertLumPerChroma)

{

	long y;

	const long chromWidth= width>>1;

	for(y=0; y<height; y++)

	{

#ifdef HAVE_MMX

//FIXME handle 2 lines a once (fewer prefetch, reuse some chrom, but very likely limited by mem anyway)

		asm volatile(

			"xor %%"REG_a", %%"REG_a"	\n\t"

			ASMALIGN16

			"1:				\n\t"

			PREFETCH" 32(%1, %%"REG_a", 2)	\n\t"

			PREFETCH" 32(%2, %%"REG_a")	\n\t"

			PREFETCH" 32(%3, %%"REG_a")	\n\t"

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

			"movq %%mm0, %%mm2		\n\t" // U(0)

			"movq (%3, %%"REG_a"), %%mm1	\n\t" // V(0)

			"punpcklbw %%mm1, %%mm0		\n\t" // UVUV UVUV(0)

			"punpckhbw %%mm1, %%mm2		\n\t" // UVUV UVUV(8)

			"movq (%1, %%"REG_a",2), %%mm3	\n\t" // Y(0)

			"movq 8(%1, %%"REG_a",2), %%mm5	\n\t" // Y(8)

			"movq %%mm0, %%mm4		\n\t" // Y(0)

			"movq %%mm2, %%mm6		\n\t" // Y(8)

			"punpcklbw %%mm3, %%mm0		\n\t" // YUYV YUYV(0)

			"punpckhbw %%mm3, %%mm4		\n\t" // YUYV YUYV(4)

			"punpcklbw %%mm5, %%mm2		\n\t" // YUYV YUYV(8)

			"punpckhbw %%mm5, %%mm6		\n\t" // YUYV YUYV(12)

			MOVNTQ" %%mm0, (%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm4, 8(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm2, 16(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm6, 24(%0, %%"REG_a", 4)\n\t"

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

			"cmp %4, %%"REG_a"		\n\t"

			" jb 1b				\n\t"

			::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)

			: "%"REG_a

		);

#else

//FIXME adapt the alpha asm code from yv12->yuy2

#if __WORDSIZE >= 64

		int i;

		uint64_t *ldst = (uint64_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

			uint64_t k, l;

			k = uc[0] + (yc[0] << 8) +

			    (vc[0] << 16) + (yc[1] << 24);

			l = uc[1] + (yc[2] << 8) +

			    (vc[1] << 16) + (yc[3] << 24);

			*ldst++ = k + (l << 32);

			yc += 4;

			uc += 2;

			vc += 2;

		}

#else

		int i, *idst = (int32_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

#ifdef WORDS_BIGENDIAN

			*idst++ = (uc[0] << 24)+ (yc[0] << 16) +

			    (vc[0] << 8) + (yc[1] << 0);

#else

			*idst++ = uc[0] + (yc[0] << 8) +

			    (vc[0] << 16) + (yc[1] << 24);

#endif

			yc += 2;

			uc++;

			vc++;

		}

#endif

#endif

		if((y&(vertLumPerChroma-1))==(vertLumPerChroma-1) )

		{

			usrc += chromStride;

			vsrc += chromStride;

		}

		ysrc += lumStride;

		dst += dstStride;

	}

#ifdef HAVE_MMX

asm(    EMMS" \n\t"

        SFENCE" \n\t"

        :::"memory");

#endif

}


static void decodeplane32(uint32_t *dst, const uint8_t *const buf, int buf_size, int bps, int plane)

{

    GetBitContext gb;

    int i, b;

    init_get_bits(&gb, buf, buf_size * 8);

    for(i = 0; i < (buf_size * 8 + bps - 1) / bps; i++) {

        for (b = 0; b < bps; b++) {

            dst[ i*bps + b ] |= get_bits1(&gb) << plane;

        }

    }

}


static int swf_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    SWFContext *swf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *vst = NULL, *ast = NULL, *st = 0;

    int tag, len, i, frame, v;

    for(;;) {

        uint64_t pos = avio_tell(pb);

        tag = get_swf_tag(pb, &len);

        if (tag < 0)

            return AVERROR(EIO);

        if (tag == TAG_VIDEOSTREAM) {

            int ch_id = avio_rl16(pb);

            len -= 2;

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->id == ch_id)

                    goto skip;

            }

            avio_rl16(pb);

            avio_rl16(pb);

            avio_rl16(pb);

            avio_r8(pb);

            /* Check for FLV1 */

            vst = av_new_stream(s, ch_id);

            if (!vst)

                return -1;

            vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            vst->codec->codec_id = ff_codec_get_id(swf_codec_tags, avio_r8(pb));

            av_set_pts_info(vst, 16, 256, swf->frame_rate);

            vst->codec->time_base = (AVRational){ 256, swf->frame_rate };

            len -= 8;

        } else if (tag == TAG_STREAMHEAD || tag == TAG_STREAMHEAD2) {

            /* streaming found */

            int sample_rate_code;

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == -1)

                    goto skip;

            }

            avio_r8(pb);

            v = avio_r8(pb);

            swf->samples_per_frame = avio_rl16(pb);

            ast = av_new_stream(s, -1); /* -1 to avoid clash with video stream ch_id */

            if (!ast)

                return -1;

            ast->codec->channels = 1 + (v&1);

            ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            ast->codec->codec_id = ff_codec_get_id(swf_audio_codec_tags, (v>>4) & 15);

            ast->need_parsing = AVSTREAM_PARSE_FULL;

            sample_rate_code= (v>>2) & 3;

            if (!sample_rate_code)

                return AVERROR(EIO);

            ast->codec->sample_rate = 11025 << (sample_rate_code-1);

            av_set_pts_info(ast, 64, 1, ast->codec->sample_rate);

            len -= 4;

        } else if (tag == TAG_VIDEOFRAME) {

            int ch_id = avio_rl16(pb);

            len -= 2;

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->id == ch_id) {

                    frame = avio_rl16(pb);

                    av_get_packet(pb, pkt, len-2);

                    pkt->pos = pos;

                    pkt->pts = frame;

                    pkt->stream_index = st->index;

                    return pkt->size;

                }

            }

        } else if (tag == TAG_STREAMBLOCK) {

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

                st = s->streams[i];

                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->id == -1) {

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

                avio_skip(pb, 4);

                av_get_packet(pb, pkt, len-4);

            } else { // ADPCM, PCM

                av_get_packet(pb, pkt, len);

            }

            pkt->pos = pos;

            pkt->stream_index = st->index;

            return pkt->size;

                }

            }

        } else if (tag == TAG_JPEG2) {

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

                st = s->streams[i];

                if (st->codec->codec_id == CODEC_ID_MJPEG && st->id == -2)

                    break;

            }

            if (i == s->nb_streams) {

                vst = av_new_stream(s, -2); /* -2 to avoid clash with video stream and audio stream */

                if (!vst)

                    return -1;

                vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;

                vst->codec->codec_id = CODEC_ID_MJPEG;

                av_set_pts_info(vst, 64, 256, swf->frame_rate);

                vst->codec->time_base = (AVRational){ 256, swf->frame_rate };

                st = vst;

            }

            avio_rl16(pb); /* BITMAP_ID */

            av_new_packet(pkt, len-2);

            avio_read(pb, pkt->data, 4);

            if (AV_RB32(pkt->data) == 0xffd8ffd9 ||

                AV_RB32(pkt->data) == 0xffd9ffd8) {

                /* old SWF files containing SOI/EOI as data start */

                /* files created by swink have reversed tag */

                pkt->size -= 4;

                avio_read(pb, pkt->data, pkt->size);

            } else {

                avio_read(pb, pkt->data + 4, pkt->size - 4);

            }

            pkt->pos = pos;

            pkt->stream_index = st->index;

            return pkt->size;

        }

    skip:

        avio_skip(pb, len);

    }

    return 0;

}


void qxl_render_update(PCIQXLDevice *qxl)

{

    VGACommonState *vga = &qxl->vga;

    QXLRect dirty[32], update;

    void *ptr;

    int i;

    if (qxl->guest_primary.resized) {

        qxl->guest_primary.resized = 0;

        if (qxl->guest_primary.flipped) {

            g_free(qxl->guest_primary.flipped);

            qxl->guest_primary.flipped = NULL;

        }

        qemu_free_displaysurface(vga->ds);

        qxl->guest_primary.data = memory_region_get_ram_ptr(&qxl->vga.vram);

        if (qxl->guest_primary.stride < 0) {

            /* spice surface is upside down -> need extra buffer to flip */

            qxl->guest_primary.stride = -qxl->guest_primary.stride;

            qxl->guest_primary.flipped = g_malloc(qxl->guest_primary.surface.width *

                                                     qxl->guest_primary.stride);

            ptr = qxl->guest_primary.flipped;

        } else {

            ptr = qxl->guest_primary.data;

        }

        dprint(qxl, 1, "%s: %dx%d, stride %d, bpp %d, depth %d, flip %s\n",

               __FUNCTION__,

               qxl->guest_primary.surface.width,

               qxl->guest_primary.surface.height,

               qxl->guest_primary.stride,

               qxl->guest_primary.bytes_pp,

               qxl->guest_primary.bits_pp,

               qxl->guest_primary.flipped ? "yes" : "no");

        vga->ds->surface =

            qemu_create_displaysurface_from(qxl->guest_primary.surface.width,

                                            qxl->guest_primary.surface.height,

                                            qxl->guest_primary.bits_pp,

                                            qxl->guest_primary.stride,

                                            ptr);

        dpy_resize(vga->ds);

    }

    if (!qxl->guest_primary.commands) {

        return;

    }

    qxl->guest_primary.commands = 0;

    update.left   = 0;

    update.right  = qxl->guest_primary.surface.width;

    update.top    = 0;

    update.bottom = qxl->guest_primary.surface.height;

    memset(dirty, 0, sizeof(dirty));

    qxl_spice_update_area(qxl, 0, &update,

                          dirty, ARRAY_SIZE(dirty), 1, QXL_SYNC);

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

        if (qemu_spice_rect_is_empty(dirty+i)) {

            break;

        }

        if (qxl->guest_primary.flipped) {

            qxl_flip(qxl, dirty+i);

        }

        dpy_update(vga->ds,

                   dirty[i].left, dirty[i].top,

                   dirty[i].right - dirty[i].left,

                   dirty[i].bottom - dirty[i].top);

    }

}


static int local_fstat(FsContext *fs_ctx, int fid_type,

                       V9fsFidOpenState *fs, struct stat *stbuf)

{

    int err, fd;

    if (fid_type == P9_FID_DIR) {

        fd = dirfd(fs->dir);

    } else {

        fd = fs->fd;

    }

    err = fstat(fd, stbuf);

    if (err) {

        return err;

    }

    if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

        /* Actual credentials are part of extended attrs */

        uid_t tmp_uid;

        gid_t tmp_gid;

        mode_t tmp_mode;

        dev_t tmp_dev;

        if (fgetxattr(fd, "user.virtfs.uid",

                      &tmp_uid, sizeof(uid_t)) > 0) {

            stbuf->st_uid = tmp_uid;

        }

        if (fgetxattr(fd, "user.virtfs.gid",

                      &tmp_gid, sizeof(gid_t)) > 0) {

            stbuf->st_gid = tmp_gid;

        }

        if (fgetxattr(fd, "user.virtfs.mode",

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

            stbuf->st_mode = tmp_mode;

        }

        if (fgetxattr(fd, "user.virtfs.rdev",

                      &tmp_dev, sizeof(dev_t)) > 0) {

                stbuf->st_rdev = tmp_dev;

        }

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

        errno = EOPNOTSUPP;

        return -1;

    }

    return err;

}


static uint64_t malta_fpga_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

    MaltaFPGAState *s = opaque;

    uint32_t val = 0;

    uint32_t saddr;

    saddr = (addr & 0xfffff);

    switch (saddr) {

    /* SWITCH Register */

    case 0x00200:

        val = 0x00000000;		/* All switches closed */

        break;

    /* STATUS Register */

    case 0x00208:

#ifdef TARGET_WORDS_BIGENDIAN

        val = 0x00000012;

#else

        val = 0x00000010;

#endif

        break;

    /* JMPRS Register */

    case 0x00210:

        val = 0x00;

        break;

    /* LEDBAR Register */

    case 0x00408:

        val = s->leds;

        break;

    /* BRKRES Register */

    case 0x00508:

        val = s->brk;

        break;

    /* UART Registers are handled directly by the serial device */

    /* GPOUT Register */

    case 0x00a00:

        val = s->gpout;

        break;

    /* XXX: implement a real I2C controller */

    /* GPINP Register */

    case 0x00a08:

        /* IN = OUT until a real I2C control is implemented */

        if (s->i2csel)

            val = s->i2cout;

        else

            val = 0x00;

        break;

    /* I2CINP Register */

    case 0x00b00:

        val = ((s->i2cin & ~1) | eeprom24c0x_read());

        break;

    /* I2COE Register */

    case 0x00b08:

        val = s->i2coe;

        break;

    /* I2COUT Register */

    case 0x00b10:

        val = s->i2cout;

        break;

    /* I2CSEL Register */

    case 0x00b18:

        val = s->i2csel;

        break;

    default:

#if 0

        printf ("malta_fpga_read: Bad register offset 0x" TARGET_FMT_lx "\n",

                addr);

#endif

        break;

    }

    return val;

}


static void replay_save_event(Event *event, int checkpoint)

{

    if (replay_mode != REPLAY_MODE_PLAY) {

        /* put the event into the file */

        replay_put_event(EVENT_ASYNC);

        replay_put_byte(checkpoint);

        replay_put_byte(event->event_kind);

        /* save event-specific data */

        switch (event->event_kind) {

        default:

            error_report("Unknown ID %d of replay event", read_event_kind);

            exit(1);

            break;

        }

    }

}


static USBDevice *usb_msd_init(USBBus *bus, const char *filename)

{

    static int nr=0;

    char id[8];

    QemuOpts *opts;

    DriveInfo *dinfo;

    USBDevice *dev;

    const char *p1;

    char fmt[32];

    /* parse -usbdevice disk: syntax into drive opts */

    do {

        snprintf(id, sizeof(id), "usb%d", nr++);

        opts = qemu_opts_create(qemu_find_opts("drive"), id, 1, NULL);

    } while (!opts);

    p1 = strchr(filename, ':');

    if (p1++) {

        const char *p2;

        if (strstart(filename, "format=", &p2)) {

            int len = MIN(p1 - p2, sizeof(fmt));

            pstrcpy(fmt, len, p2);

            qemu_opt_set(opts, "format", fmt);

        } else if (*filename != ':') {

            error_report("unrecognized USB mass-storage option %s", filename);

            return NULL;

        }

        filename = p1;

    }

    if (!*filename) {

        error_report("block device specification needed");

        return NULL;

    }

    qemu_opt_set(opts, "file", filename);

    qemu_opt_set(opts, "if", "none");

    /* create host drive */

    dinfo = drive_new(opts, 0);

    if (!dinfo) {

        qemu_opts_del(opts);

        return NULL;

    }

    /* create guest device */

    dev = usb_create(bus, "usb-storage");

    if (!dev) {

        return NULL;

    }

    if (qdev_prop_set_drive(&dev->qdev, "drive",

                            blk_bs(blk_by_legacy_dinfo(dinfo))) < 0) {

        object_unparent(OBJECT(dev));

        return NULL;

    }

    if (qdev_init(&dev->qdev) < 0)

        return NULL;

    return dev;

}


static size_t handle_aiocb_flush(struct qemu_paiocb *aiocb)

{

    int ret;

    ret = qemu_fdatasync(aiocb->aio_fildes);

    if (ret == -1)

        return -errno;

    return 0;

}


static int unin_internal_pci_host_init(PCIDevice *d)

{

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_APPLE);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_APPLE_UNI_N_I_PCI);

    d->config[0x08] = 0x00; // revision

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_HOST);

    d->config[0x0C] = 0x08; // cache_line_size

    d->config[0x0D] = 0x10; // latency_timer

    d->config[0x34] = 0x00; // capabilities_pointer

    return 0;

}


static int upload_texture(SDL_Texture *tex, AVFrame *frame, struct SwsContext **img_convert_ctx) {

    int ret = 0;

    switch (frame->format) {

        case AV_PIX_FMT_YUV420P:

            if (frame->linesize[0] < 0 || frame->linesize[1] < 0 || frame->linesize[2] < 0) {

                av_log(NULL, AV_LOG_ERROR, "Negative linesize is not supported for YUV.\n");

                return -1;

            }

            ret = SDL_UpdateYUVTexture(tex, NULL, frame->data[0], frame->linesize[0],

                                                  frame->data[1], frame->linesize[1],

                                                  frame->data[2], frame->linesize[2]);

            break;

        case AV_PIX_FMT_BGRA:

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

                ret = SDL_UpdateTexture(tex, NULL, frame->data[0] + frame->linesize[0] * (frame->height - 1), -frame->linesize[0]);

            } else {

                ret = SDL_UpdateTexture(tex, NULL, frame->data[0], frame->linesize[0]);

            }

            break;

        default:

            /* This should only happen if we are not using avfilter... */

            *img_convert_ctx = sws_getCachedContext(*img_convert_ctx,

                frame->width, frame->height, frame->format, frame->width, frame->height,

                AV_PIX_FMT_BGRA, sws_flags, NULL, NULL, NULL);

            if (*img_convert_ctx != NULL) {

                uint8_t *pixels[4];

                int pitch[4];

                if (!SDL_LockTexture(tex, NULL, (void **)pixels, pitch)) {

                    sws_scale(*img_convert_ctx, (const uint8_t * const *)frame->data, frame->linesize,

                              0, frame->height, pixels, pitch);

                    SDL_UnlockTexture(tex);

                }

            } else {

                av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");

                ret = -1;

            }

            break;

    }

    return ret;

}


static void load_linux(const char *kernel_filename,

		       const char *initrd_filename,

		       const char *kernel_cmdline)

{

    uint16_t protocol;

    uint32_t gpr[8];

    uint16_t seg[6];

    uint16_t real_seg;

    int setup_size, kernel_size, initrd_size, cmdline_size;

    uint32_t initrd_max;

    uint8_t header[1024];

    target_phys_addr_t real_addr, prot_addr, cmdline_addr, initrd_addr;

    FILE *f, *fi;

    /* Align to 16 bytes as a paranoia measure */

    cmdline_size = (strlen(kernel_cmdline)+16) & ~15;

    /* load the kernel header */

    f = fopen(kernel_filename, "rb");

    if (!f || !(kernel_size = get_file_size(f)) ||

	fread(header, 1, 1024, f) != 1024) {

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

		kernel_filename);

	exit(1);

    }

    /* kernel protocol version */

#if 0

    fprintf(stderr, "header magic: %#x\n", ldl_p(header+0x202));

#endif

    if (ldl_p(header+0x202) == 0x53726448)

	protocol = lduw_p(header+0x206);

    else

	protocol = 0;

    if (protocol < 0x200 || !(header[0x211] & 0x01)) {

	/* Low kernel */

	real_addr    = 0x90000;

	cmdline_addr = 0x9a000 - cmdline_size;

	prot_addr    = 0x10000;

    } else if (protocol < 0x202) {

	/* High but ancient kernel */

	real_addr    = 0x90000;

	cmdline_addr = 0x9a000 - cmdline_size;

	prot_addr    = 0x100000;

    } else {

	/* High and recent kernel */

	real_addr    = 0x10000;

	cmdline_addr = 0x20000;

	prot_addr    = 0x100000;

    }

#if 0

    fprintf(stderr,

	    "qemu: real_addr     = 0x" TARGET_FMT_plx "\n"

	    "qemu: cmdline_addr  = 0x" TARGET_FMT_plx "\n"

	    "qemu: prot_addr     = 0x" TARGET_FMT_plx "\n",

	    real_addr,

	    cmdline_addr,

	    prot_addr);

#endif

    /* highest address for loading the initrd */

    if (protocol >= 0x203)

	initrd_max = ldl_p(header+0x22c);

    else

	initrd_max = 0x37ffffff;

    if (initrd_max >= ram_size-ACPI_DATA_SIZE)

	initrd_max = ram_size-ACPI_DATA_SIZE-1;

    /* kernel command line */

    pstrcpy_targphys(cmdline_addr, 4096, kernel_cmdline);

    if (protocol >= 0x202) {

	stl_p(header+0x228, cmdline_addr);

    } else {

	stw_p(header+0x20, 0xA33F);

	stw_p(header+0x22, cmdline_addr-real_addr);

    }

    /* loader type */

    /* High nybble = B reserved for Qemu; low nybble is revision number.

       If this code is substantially changed, you may want to consider

       incrementing the revision. */

    if (protocol >= 0x200)

	header[0x210] = 0xB0;

    /* heap */

    if (protocol >= 0x201) {

	header[0x211] |= 0x80;	/* CAN_USE_HEAP */

	stw_p(header+0x224, cmdline_addr-real_addr-0x200);

    }

    /* load initrd */

    if (initrd_filename) {

	if (protocol < 0x200) {

	    fprintf(stderr, "qemu: linux kernel too old to load a ram disk\n");

	    exit(1);

	}

	fi = fopen(initrd_filename, "rb");

	if (!fi) {

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

		    initrd_filename);

	    exit(1);

	}

	initrd_size = get_file_size(fi);

	initrd_addr = (initrd_max-initrd_size) & ~4095;

        fprintf(stderr, "qemu: loading initrd (%#x bytes) at 0x" TARGET_FMT_plx

                "\n", initrd_size, initrd_addr);

	if (!fread_targphys_ok(initrd_addr, initrd_size, fi)) {

	    fprintf(stderr, "qemu: read error on initial ram disk '%s'\n",

		    initrd_filename);

	    exit(1);

	}

	fclose(fi);

	stl_p(header+0x218, initrd_addr);

	stl_p(header+0x21c, initrd_size);

    }

    /* store the finalized header and load the rest of the kernel */

    cpu_physical_memory_write(real_addr, header, 1024);

    setup_size = header[0x1f1];

    if (setup_size == 0)

	setup_size = 4;

    setup_size = (setup_size+1)*512;

    kernel_size -= setup_size;	/* Size of protected-mode code */

    if (!fread_targphys_ok(real_addr+1024, setup_size-1024, f) ||

	!fread_targphys_ok(prot_addr, kernel_size, f)) {

	fprintf(stderr, "qemu: read error on kernel '%s'\n",

		kernel_filename);

	exit(1);

    }

    fclose(f);

    /* generate bootsector to set up the initial register state */

    real_seg = real_addr >> 4;

    seg[0] = seg[2] = seg[3] = seg[4] = seg[4] = real_seg;

    seg[1] = real_seg+0x20;	/* CS */

    memset(gpr, 0, sizeof gpr);

    gpr[4] = cmdline_addr-real_addr-16;	/* SP (-16 is paranoia) */

    generate_bootsect(gpr, seg, 0);

}


static void gen_neon_zip_u8(TCGv t0, TCGv t1)

{

    TCGv rd, rm, tmp;

    rd = new_tmp();

    rm = new_tmp();

    tmp = new_tmp();

    tcg_gen_andi_i32(rd, t0, 0xff);

    tcg_gen_shli_i32(tmp, t1, 8);

    tcg_gen_andi_i32(tmp, tmp, 0xff00);

    tcg_gen_or_i32(rd, rd, tmp);

    tcg_gen_shli_i32(tmp, t0, 16);

    tcg_gen_andi_i32(tmp, tmp, 0xff0000);

    tcg_gen_or_i32(rd, rd, tmp);

    tcg_gen_shli_i32(tmp, t1, 24);

    tcg_gen_andi_i32(tmp, tmp, 0xff000000);

    tcg_gen_or_i32(rd, rd, tmp);

    tcg_gen_andi_i32(rm, t1, 0xff000000);

    tcg_gen_shri_i32(tmp, t0, 8);

    tcg_gen_andi_i32(tmp, tmp, 0xff0000);

    tcg_gen_or_i32(rm, rm, tmp);

    tcg_gen_shri_i32(tmp, t1, 8);

    tcg_gen_andi_i32(tmp, tmp, 0xff00);

    tcg_gen_or_i32(rm, rm, tmp);

    tcg_gen_shri_i32(tmp, t0, 16);

    tcg_gen_andi_i32(tmp, tmp, 0xff);

    tcg_gen_or_i32(t1, rm, tmp);

    tcg_gen_mov_i32(t0, rd);

    dead_tmp(tmp);

    dead_tmp(rm);

    dead_tmp(rd);

}


static boolean jpeg_empty_output_buffer(j_compress_ptr cinfo)

{

    VncState *vs = cinfo->client_data;

    Buffer *buffer = &vs->tight_jpeg;

    buffer->offset = buffer->capacity;

    buffer_reserve(buffer, 2048);

    jpeg_init_destination(cinfo);

    return TRUE;

}


static inline tcg_target_ulong cpu_tb_exec(CPUState *cpu, TranslationBlock *itb)

{

    CPUArchState *env = cpu->env_ptr;

    uintptr_t ret;

    TranslationBlock *last_tb;

    int tb_exit;

    uint8_t *tb_ptr = itb->tc_ptr;

    qemu_log_mask_and_addr(CPU_LOG_EXEC, itb->pc,

                           "Trace %p [" TARGET_FMT_lx "] %s\n",

                           itb->tc_ptr, itb->pc, lookup_symbol(itb->pc));

#if defined(DEBUG_DISAS)

    if (qemu_loglevel_mask(CPU_LOG_TB_CPU)) {

#if defined(TARGET_I386)

        log_cpu_state(cpu, CPU_DUMP_CCOP);

#elif defined(TARGET_M68K)

        /* ??? Should not modify env state for dumping.  */

        cpu_m68k_flush_flags(env, env->cc_op);

        env->cc_op = CC_OP_FLAGS;

        env->sr = (env->sr & 0xffe0) | env->cc_dest | (env->cc_x << 4);

        log_cpu_state(cpu, 0);

#else

        log_cpu_state(cpu, 0);

#endif

    }

#endif /* DEBUG_DISAS */

    cpu->can_do_io = !use_icount;

    ret = tcg_qemu_tb_exec(env, tb_ptr);

    cpu->can_do_io = 1;

    last_tb = (TranslationBlock *)(ret & ~TB_EXIT_MASK);

    tb_exit = ret & TB_EXIT_MASK;

    trace_exec_tb_exit(last_tb, tb_exit);

    if (tb_exit > TB_EXIT_IDX1) {

        /* We didn't start executing this TB (eg because the instruction

         * counter hit zero); we must restore the guest PC to the address

         * of the start of the TB.

         */

        CPUClass *cc = CPU_GET_CLASS(cpu);

        qemu_log_mask_and_addr(CPU_LOG_EXEC, last_tb->pc,

                               "Stopped execution of TB chain before %p ["

                               TARGET_FMT_lx "] %s\n",

                               last_tb->tc_ptr, last_tb->pc,

                               lookup_symbol(last_tb->pc));

        if (cc->synchronize_from_tb) {

            cc->synchronize_from_tb(cpu, last_tb);

        } else {

            assert(cc->set_pc);

            cc->set_pc(cpu, last_tb->pc);

        }

    }

    if (tb_exit == TB_EXIT_REQUESTED) {

        /* We were asked to stop executing TBs (probably a pending

         * interrupt. We've now stopped, so clear the flag.

         */

        cpu->tcg_exit_req = 0;

    }

    return ret;

}


static int get_para_features(CPUState *env)

{

        int i, features = 0;

        for (i = 0; i < ARRAY_SIZE(para_features) - 1; i++) {

                if (kvm_check_extension(env->kvm_state, para_features[i].cap))

                        features |= (1 << para_features[i].feature);

        }

        return features;

}


int msix_init_exclusive_bar(PCIDevice *dev, unsigned short nentries,

                            uint8_t bar_nr)

{

    int ret;

    char *name;

    /*

     * Migration compatibility dictates that this remains a 4k

     * BAR with the vector table in the lower half and PBA in

     * the upper half.  Do not use these elsewhere!

     */

#define MSIX_EXCLUSIVE_BAR_SIZE 4096

#define MSIX_EXCLUSIVE_BAR_TABLE_OFFSET 0

#define MSIX_EXCLUSIVE_BAR_PBA_OFFSET (MSIX_EXCLUSIVE_BAR_SIZE / 2)

#define MSIX_EXCLUSIVE_CAP_OFFSET 0

    if (nentries * PCI_MSIX_ENTRY_SIZE > MSIX_EXCLUSIVE_BAR_PBA_OFFSET) {

        return -EINVAL;

    }

    name = g_strdup_printf("%s-msix", dev->name);

    memory_region_init(&dev->msix_exclusive_bar, OBJECT(dev), name, MSIX_EXCLUSIVE_BAR_SIZE);

    g_free(name);

    ret = msix_init(dev, nentries, &dev->msix_exclusive_bar, bar_nr,

                    MSIX_EXCLUSIVE_BAR_TABLE_OFFSET, &dev->msix_exclusive_bar,

                    bar_nr, MSIX_EXCLUSIVE_BAR_PBA_OFFSET,

                    MSIX_EXCLUSIVE_CAP_OFFSET);

    if (ret) {

        return ret;

    }

    pci_register_bar(dev, bar_nr, PCI_BASE_ADDRESS_SPACE_MEMORY,

                     &dev->msix_exclusive_bar);

    return 0;

}


static int armv7m_nvic_init(SysBusDevice *dev)

{

    nvic_state *s = NVIC(dev);

    NVICClass *nc = NVIC_GET_CLASS(s);

    /* The NVIC always has only one CPU */

    s->gic.num_cpu = 1;

    /* Tell the common code we're an NVIC */

    s->gic.revision = 0xffffffff;

    s->gic.num_irq = s->num_irq;

    nc->parent_init(dev);

    gic_init_irqs_and_distributor(&s->gic, s->num_irq);

    /* The NVIC and system controller register area looks like this:

     *  0..0xff : system control registers, including systick

     *  0x100..0xcff : GIC-like registers

     *  0xd00..0xfff : system control registers

     * We use overlaying to put the GIC like registers

     * over the top of the system control register region.

     */

    memory_region_init(&s->container, "nvic", 0x1000);

    /* The system register region goes at the bottom of the priority

     * stack as it covers the whole page.

     */

    memory_region_init_io(&s->sysregmem, &nvic_sysreg_ops, s,

                          "nvic_sysregs", 0x1000);

    memory_region_add_subregion(&s->container, 0, &s->sysregmem);

    /* Alias the GIC region so we can get only the section of it

     * we need, and layer it on top of the system register region.

     */

    memory_region_init_alias(&s->gic_iomem_alias, "nvic-gic", &s->gic.iomem,

                             0x100, 0xc00);

    memory_region_add_subregion_overlap(&s->container, 0x100, &s->gic.iomem, 1);

    /* Map the whole thing into system memory at the location required

     * by the v7M architecture.

     */

    memory_region_add_subregion(get_system_memory(), 0xe000e000, &s->container);

    s->systick.timer = qemu_new_timer_ns(vm_clock, systick_timer_tick, s);

    return 0;

}


static int get_mmu_address(CPUState * env, target_ulong * physical,

			   int *prot, target_ulong address,

			   int rw, int access_type)

{

    int use_asid, n;

    tlb_t *matching = NULL;

    use_asid = (env->mmucr & MMUCR_SV) == 0 || (env->sr & SR_MD) == 0;

    if (rw == 2) {

	n = find_itlb_entry(env, address, use_asid, 1);

	if (n >= 0) {

	    matching = &env->itlb[n];

	    if ((env->sr & SR_MD) & !(matching->pr & 2))

		n = MMU_ITLB_VIOLATION;

	    else

		*prot = PAGE_READ;

	}

    } else {

	n = find_utlb_entry(env, address, use_asid);

	if (n >= 0) {

	    matching = &env->utlb[n];

	    switch ((matching->pr << 1) | ((env->sr & SR_MD) ? 1 : 0)) {

	    case 0:		/* 000 */

	    case 2:		/* 010 */

		n = (rw == 1) ? MMU_DTLB_VIOLATION_WRITE :

		    MMU_DTLB_VIOLATION_READ;

		break;

	    case 1:		/* 001 */

	    case 4:		/* 100 */

	    case 5:		/* 101 */

		if (rw == 1)

		    n = MMU_DTLB_VIOLATION_WRITE;

		else

		    *prot = PAGE_READ;

		break;

	    case 3:		/* 011 */

	    case 6:		/* 110 */

	    case 7:		/* 111 */

		*prot = (rw == 1)? PAGE_WRITE : PAGE_READ;

		break;

	    }

	} else if (n == MMU_DTLB_MISS) {

	    n = (rw == 1) ? MMU_DTLB_MISS_WRITE :

		MMU_DTLB_MISS_READ;

	}

    }

    if (n >= 0) {

	*physical = ((matching->ppn << 10) & ~(matching->size - 1)) |

	    (address & (matching->size - 1));

	if ((rw == 1) & !matching->d)

	    n = MMU_DTLB_INITIAL_WRITE;

	else

	    n = MMU_OK;

    }

    return n;

}


static void add_codec(FFStream *stream, AVCodecContext *av)

{

    AVStream *st;

    if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))

        return;

    /* compute default parameters */

    switch(av->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->sample_rate == 0)

            av->sample_rate = 22050;

        if (av->channels == 0)

            av->channels = 1;

        break;

    case AVMEDIA_TYPE_VIDEO:

        if (av->bit_rate == 0)

            av->bit_rate = 64000;

        if (av->time_base.num == 0){

            av->time_base.den = 5;

            av->time_base.num = 1;

        }

        if (av->width == 0 || av->height == 0) {

            av->width = 160;

            av->height = 128;

        }

        /* Bitrate tolerance is less for streaming */

        if (av->bit_rate_tolerance == 0)

            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,

                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);

        if (av->qmin == 0)

            av->qmin = 3;

        if (av->qmax == 0)

            av->qmax = 31;

        if (av->max_qdiff == 0)

            av->max_qdiff = 3;

        av->qcompress = 0.5;

        av->qblur = 0.5;

        if (!av->nsse_weight)

            av->nsse_weight = 8;

        av->frame_skip_cmp = FF_CMP_DCTMAX;

        if (!av->me_method)

            av->me_method = ME_EPZS;

        av->rc_buffer_aggressivity = 1.0;

        if (!av->rc_eq)

            av->rc_eq = "tex^qComp";

        if (!av->i_quant_factor)

            av->i_quant_factor = -0.8;

        if (!av->b_quant_factor)

            av->b_quant_factor = 1.25;

        if (!av->b_quant_offset)

            av->b_quant_offset = 1.25;

        if (!av->rc_max_rate)

            av->rc_max_rate = av->bit_rate * 2;

        if (av->rc_max_rate && !av->rc_buffer_size) {

            av->rc_buffer_size = av->rc_max_rate;

        }

        break;

    default:

        abort();

    }

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        return;

    st->codec = avcodec_alloc_context3(NULL);

    stream->streams[stream->nb_streams++] = st;

    memcpy(st->codec, av, sizeof(AVCodecContext));

}


START_TEST(qdict_put_obj_test)

{

    QInt *qi;

    QDict *qdict;

    QDictEntry *ent;

    const int num = 42;

    qdict = qdict_new();

    // key "" will have tdb hash 12345

    qdict_put_obj(qdict, "", QOBJECT(qint_from_int(num)));

    fail_unless(qdict_size(qdict) == 1);

    ent = QLIST_FIRST(&qdict->table[12345 % QDICT_BUCKET_MAX]);

    qi = qobject_to_qint(ent->value);

    fail_unless(qint_get_int(qi) == num);

    // destroy doesn't exit yet

    QDECREF(qi);

    g_free(ent->key);

    g_free(ent);

    g_free(qdict);

}


static int v9fs_do_mkdir(V9fsState *s, V9fsString *path, mode_t mode)

{

    return s->ops->mkdir(&s->ctx, path->data, mode);

}


static uint32_t slow_bar_readb(void *opaque, target_phys_addr_t addr)

{

    AssignedDevRegion *d = opaque;

    uint8_t *in = d->u.r_virtbase + addr;

    uint32_t r;

    r = *in;

    DEBUG("slow_bar_readl addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, r);

    return r;

}


uint32_t HELPER(tprot)(uint64_t a1, uint64_t a2)

{

    /* XXX implement */

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);

    k->init = ds1338_init;

    k->event = ds1338_event;

    k->recv = ds1338_recv;

    k->send = ds1338_send;

    dc->reset = ds1338_reset;

    dc->vmsd = &vmstate_ds1338;

}


static void extend_solid_area(VncState *vs, int x, int y, int w, int h,

                              uint32_t color, int *x_ptr, int *y_ptr,

                              int *w_ptr, int *h_ptr)

{

    int cx, cy;

    /* Try to extend the area upwards. */

    for ( cy = *y_ptr - 1;

          cy >= y && check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);

          cy-- );

    *h_ptr += *y_ptr - (cy + 1);

    *y_ptr = cy + 1;

    /* ... downwards. */

    for ( cy = *y_ptr + *h_ptr;

          cy < y + h &&

              check_solid_tile(vs, *x_ptr, cy, *w_ptr, 1, &color, true);

          cy++ );

    *h_ptr += cy - (*y_ptr + *h_ptr);

    /* ... to the left. */

    for ( cx = *x_ptr - 1;

          cx >= x && check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);

          cx-- );

    *w_ptr += *x_ptr - (cx + 1);

    *x_ptr = cx + 1;

    /* ... to the right. */

    for ( cx = *x_ptr + *w_ptr;

          cx < x + w &&

              check_solid_tile(vs, cx, *y_ptr, 1, *h_ptr, &color, true);

          cx++ );

    *w_ptr += cx - (*x_ptr + *w_ptr);

}


static inline void RET_CHG_FLOW (DisasContext *ctx)

{

    ctx->exception = EXCP_MTMSR;

}


static void setup_sigframe_v2(struct target_ucontext_v2 *uc,

                              target_sigset_t *set, CPUState *env)

{

    struct target_sigaltstack stack;

    int i;

    /* Clear all the bits of the ucontext we don't use.  */

    memset(uc, 0, offsetof(struct target_ucontext_v2, tuc_mcontext));

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

    __put_user(target_sigaltstack_used.ss_sp, &stack.ss_sp);

    __put_user(target_sigaltstack_used.ss_size, &stack.ss_size);

    __put_user(sas_ss_flags(get_sp_from_cpustate(env)), &stack.ss_flags);

    memcpy(&uc->tuc_stack, &stack, sizeof(stack));

    setup_sigcontext(&uc->tuc_mcontext, env, set->sig[0]);

    /* FIXME: Save coprocessor signal frame.  */

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

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

    }

}


static av_cold int vdadec_close(AVCodecContext *avctx)

{

    VDADecoderContext *ctx = avctx->priv_data;

    /* release buffers and decoder */

    ff_vda_destroy_decoder(&ctx->vda_ctx);

    /* close H.264 decoder */

    if (ctx->h264_initialized)

        ff_h264_decoder.close(avctx);

    return 0;

}


void pci_bridge_write_config(PCIDevice *d,

                             uint32_t address, uint32_t val, int len)

{

    PCIBridge *s = PCI_BRIDGE(d);

    uint16_t oldctl = pci_get_word(d->config + PCI_BRIDGE_CONTROL);

    uint16_t newctl;

    pci_default_write_config(d, address, val, len);

    if (ranges_overlap(address, len, PCI_COMMAND, 2) ||

        /* io base/limit */

        ranges_overlap(address, len, PCI_IO_BASE, 2) ||

        /* memory base/limit, prefetchable base/limit and

           io base/limit upper 16 */

        ranges_overlap(address, len, PCI_MEMORY_BASE, 20) ||

        /* vga enable */

        ranges_overlap(address, len, PCI_BRIDGE_CONTROL, 2)) {

        pci_bridge_update_mappings(s);

    }

    newctl = pci_get_word(d->config + PCI_BRIDGE_CONTROL);

    if (~oldctl & newctl & PCI_BRIDGE_CTL_BUS_RESET) {

        /* Trigger hot reset on 0->1 transition. */

        pci_bus_reset(&s->sec_bus);

    }

}


static inline int ucf64_exceptbits_to_host(int target_bits)

{

    int host_bits = 0;

    if (target_bits & UCF64_FPSCR_FLAG_INVALID) {

        host_bits |= float_flag_invalid;

    }

    if (target_bits & UCF64_FPSCR_FLAG_DIVZERO) {

        host_bits |= float_flag_divbyzero;

    }

    if (target_bits & UCF64_FPSCR_FLAG_OVERFLOW) {

        host_bits |= float_flag_overflow;

    }

    if (target_bits & UCF64_FPSCR_FLAG_UNDERFLOW) {

        host_bits |= float_flag_underflow;

    }

    if (target_bits & UCF64_FPSCR_FLAG_INEXACT) {

        host_bits |= float_flag_inexact;

    }

    return host_bits;

}


static void qmp_output_start_list(Visitor *v, const char *name, Error **errp)

{

    QmpOutputVisitor *qov = to_qov(v);

    QList *list = qlist_new();

    qmp_output_add(qov, name, list);

    qmp_output_push(qov, list);

}


static int scsi_hot_add(Monitor *mon, DeviceState *adapter,

                        DriveInfo *dinfo, int printinfo)

{

    SCSIBus *scsibus;

    SCSIDevice *scsidev;

    scsibus = DO_UPCAST(SCSIBus, qbus, QLIST_FIRST(&adapter->child_bus));

    if (!scsibus || strcmp(scsibus->qbus.info->name, "SCSI") != 0) {

        error_report("Device is not a SCSI adapter");

        return -1;

    }

    /*

     * drive_init() tries to find a default for dinfo->unit.  Doesn't

     * work at all for hotplug though as we assign the device to a

     * specific bus instead of the first bus with spare scsi ids.

     *

     * Ditch the calculated value and reload from option string (if

     * specified).

     */

    dinfo->unit = qemu_opt_get_number(dinfo->opts, "unit", -1);

    scsidev = scsi_bus_legacy_add_drive(scsibus, dinfo, dinfo->unit);

    if (!scsidev) {

        return -1;

    }

    dinfo->unit = scsidev->id;

    if (printinfo)

        monitor_printf(mon, "OK bus %d, unit %d\n",

                       scsibus->busnr, scsidev->id);

    return 0;

}


float64 float64_round_to_int( float64 a STATUS_PARAM )

{

    flag aSign;

    int16 aExp;

    bits64 lastBitMask, roundBitsMask;

    int8 roundingMode;

    float64 z;

    aExp = extractFloat64Exp( a );

    if ( 0x433 <= aExp ) {

        if ( ( aExp == 0x7FF ) && extractFloat64Frac( a ) ) {

            return propagateFloat64NaN( a, a STATUS_VAR );

        }

        return a;

    }

    if ( aExp < 0x3FF ) {

        if ( (bits64) ( a<<1 ) == 0 ) return a;

        STATUS(float_exception_flags) |= float_flag_inexact;

        aSign = extractFloat64Sign( a );

        switch ( STATUS(float_rounding_mode) ) {

         case float_round_nearest_even:

            if ( ( aExp == 0x3FE ) && extractFloat64Frac( a ) ) {

                return packFloat64( aSign, 0x3FF, 0 );

            }

            break;

         case float_round_down:

            return aSign ? LIT64( 0xBFF0000000000000 ) : 0;

         case float_round_up:

            return

            aSign ? LIT64( 0x8000000000000000 ) : LIT64( 0x3FF0000000000000 );

        }

        return packFloat64( aSign, 0, 0 );

    }

    lastBitMask = 1;

    lastBitMask <<= 0x433 - aExp;

    roundBitsMask = lastBitMask - 1;

    z = a;

    roundingMode = STATUS(float_rounding_mode);

    if ( roundingMode == float_round_nearest_even ) {

        z += lastBitMask>>1;

        if ( ( z & roundBitsMask ) == 0 ) z &= ~ lastBitMask;

    }

    else if ( roundingMode != float_round_to_zero ) {

        if ( extractFloat64Sign( z ) ^ ( roundingMode == float_round_up ) ) {

            z += roundBitsMask;

        }

    }

    z &= ~ roundBitsMask;

    if ( z != a ) STATUS(float_exception_flags) |= float_flag_inexact;

    return z;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);

    sc->init         = scsi_cd_initfn;

    sc->destroy      = scsi_destroy;

    sc->alloc_req    = scsi_new_request;

    sc->unit_attention_reported = scsi_disk_unit_attention_reported;

    dc->fw_name = "disk";

    dc->desc = "virtual SCSI CD-ROM";

    dc->reset = scsi_disk_reset;

    dc->props = scsi_cd_properties;

    dc->vmsd  = &vmstate_scsi_disk_state;

}


static int local_post_create_passthrough(FsContext *fs_ctx, const char *path,

                                         FsCred *credp)

{

    char buffer[PATH_MAX];

    if (chmod(rpath(fs_ctx, path, buffer), credp->fc_mode & 07777) < 0) {

        return -1;

    }

    if (lchown(rpath(fs_ctx, path, buffer), credp->fc_uid,

                credp->fc_gid) < 0) {

        /*

         * If we fail to change ownership and if we are

         * using security model none. Ignore the error

         */

        if (fs_ctx->fs_sm != SM_NONE) {

            return -1;

        }

    }

    return 0;

}


uint8_t cpu_inb(pio_addr_t addr)

{

    uint8_t val;

    val = ioport_read(0, addr);

    trace_cpu_in(addr, val);

    LOG_IOPORT("inb : %04"FMT_pioaddr" %02"PRIx8"\n", addr, val);

    return val;

}


void s390_init_cpus(const char *cpu_model)

{

    int i;

    if (cpu_model == NULL) {

        cpu_model = "host";

    }

    ipi_states = g_malloc(sizeof(S390CPU *) * smp_cpus);

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

        S390CPU *cpu;

        CPUState *cs;

        cpu = cpu_s390x_init(cpu_model);

        cs = CPU(cpu);

        ipi_states[i] = cpu;

        cs->halted = 1;

        cs->exception_index = EXCP_HLT;

    }

}


static int virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req)

{

    SCSIDevice *d = virtio_scsi_device_find(s, req->req.tmf.lun);

    SCSIRequest *r, *next;

    BusChild *kid;

    int target;

    int ret = 0;

    if (s->dataplane_started && bdrv_get_aio_context(d->conf.bs) != s->ctx) {

        aio_context_acquire(s->ctx);

        bdrv_set_aio_context(d->conf.bs, s->ctx);

        aio_context_release(s->ctx);

    }

    /* Here VIRTIO_SCSI_S_OK means "FUNCTION COMPLETE".  */

    req->resp.tmf.response = VIRTIO_SCSI_S_OK;

    virtio_tswap32s(VIRTIO_DEVICE(s), &req->req.tmf.subtype);

    switch (req->req.tmf.subtype) {

    case VIRTIO_SCSI_T_TMF_ABORT_TASK:

    case VIRTIO_SCSI_T_TMF_QUERY_TASK:

        if (!d) {

            goto fail;

        }

        if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) {

            goto incorrect_lun;

        }

        QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) {

            VirtIOSCSIReq *cmd_req = r->hba_private;

            if (cmd_req && cmd_req->req.cmd.tag == req->req.tmf.tag) {

                break;

            }

        }

        if (r) {

            /*

             * Assert that the request has not been completed yet, we

             * check for it in the loop above.

             */

            assert(r->hba_private);

            if (req->req.tmf.subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK) {

                /* "If the specified command is present in the task set, then

                 * return a service response set to FUNCTION SUCCEEDED".

                 */

                req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED;

            } else {

                VirtIOSCSICancelNotifier *notifier;

                req->remaining = 1;

                notifier = g_slice_new(VirtIOSCSICancelNotifier);

                notifier->tmf_req = req;

                notifier->notifier.notify = virtio_scsi_cancel_notify;

                scsi_req_cancel_async(r, &notifier->notifier);

                ret = -EINPROGRESS;

            }

        }

        break;

    case VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET:

        if (!d) {

            goto fail;

        }

        if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) {

            goto incorrect_lun;

        }

        s->resetting++;

        qdev_reset_all(&d->qdev);

        s->resetting--;

        break;

    case VIRTIO_SCSI_T_TMF_ABORT_TASK_SET:

    case VIRTIO_SCSI_T_TMF_CLEAR_TASK_SET:

    case VIRTIO_SCSI_T_TMF_QUERY_TASK_SET:

        if (!d) {

            goto fail;

        }

        if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) {

            goto incorrect_lun;

        }

        /* Add 1 to "remaining" until virtio_scsi_do_tmf returns.

         * This way, if the bus starts calling back to the notifiers

         * even before we finish the loop, virtio_scsi_cancel_notify

         * will not complete the TMF too early.

         */

        req->remaining = 1;

        QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) {

            if (r->hba_private) {

                if (req->req.tmf.subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK_SET) {

                    /* "If there is any command present in the task set, then

                     * return a service response set to FUNCTION SUCCEEDED".

                     */

                    req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED;

                    break;

                } else {

                    VirtIOSCSICancelNotifier *notifier;

                    req->remaining++;

                    notifier = g_slice_new(VirtIOSCSICancelNotifier);

                    notifier->notifier.notify = virtio_scsi_cancel_notify;

                    notifier->tmf_req = req;

                    scsi_req_cancel_async(r, &notifier->notifier);

                }

            }

        }

        if (--req->remaining > 0) {

            ret = -EINPROGRESS;

        }

        break;

    case VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET:

        target = req->req.tmf.lun[1];

        s->resetting++;

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

             d = DO_UPCAST(SCSIDevice, qdev, kid->child);

             if (d->channel == 0 && d->id == target) {

                qdev_reset_all(&d->qdev);

             }

        }

        s->resetting--;

        break;

    case VIRTIO_SCSI_T_TMF_CLEAR_ACA:

    default:

        req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_REJECTED;

        break;

    }

    return ret;

incorrect_lun:

    req->resp.tmf.response = VIRTIO_SCSI_S_INCORRECT_LUN;

    return ret;

fail:

    req->resp.tmf.response = VIRTIO_SCSI_S_BAD_TARGET;

    return ret;

}


static BlockDriverAIOCB *raw_aio_write(BlockDriverState *bs,

        int64_t sector_num, const uint8_t *buf, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    RawAIOCB *acb;

    /*

     * If O_DIRECT is used and the buffer is not aligned fall back

     * to synchronous IO.

     */

    BDRVRawState *s = bs->opaque;

    if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {

        QEMUBH *bh;

        acb = qemu_aio_get(bs, cb, opaque);

        acb->ret = raw_pwrite(bs, 512 * sector_num, buf, 512 * nb_sectors);

        bh = qemu_bh_new(raw_aio_em_cb, acb);

        qemu_bh_schedule(bh);

        return &acb->common;

    }

    acb = raw_aio_setup(bs, sector_num, (uint8_t*)buf, nb_sectors, cb, opaque);

    if (!acb)

        return NULL;

    if (aio_write(&acb->aiocb) < 0) {

        qemu_aio_release(acb);

        return NULL;

    }

    return &acb->common;

}


static void vnc_init_basic_info_from_remote_addr(QIOChannelSocket *ioc,

                                                 VncBasicInfo *info,

                                                 Error **errp)

{

    SocketAddress *addr = NULL;

    addr = qio_channel_socket_get_remote_address(ioc, errp);

    if (!addr) {

        return;

    }

    vnc_init_basic_info(addr, info, errp);

    qapi_free_SocketAddress(addr);

}


static void vnc_write_u8(VncState *vs, uint8_t value)

{

    vnc_write(vs, (char *)&value, 1);

}


void helper_mtc0_pagemask(CPUMIPSState *env, target_ulong arg1)

{

    /* 1k pages not implemented */

    env->CP0_PageMask = arg1 & (0x1FFFFFFF & (TARGET_PAGE_MASK << 1));

}


static void memory_region_prepare_ram_addr(MemoryRegion *mr)

{

    if (mr->backend_registered) {

        return;

    }

    mr->destructor = memory_region_destructor_iomem;

    mr->ram_addr = cpu_register_io_memory(memory_region_read_thunk,

                                          memory_region_write_thunk,

                                          mr);

    mr->backend_registered = true;

}


static void virtio_blk_reset(VirtIODevice *vdev)

{

    VirtIOBlock *s = VIRTIO_BLK(vdev);

    AioContext *ctx;

    VirtIOBlockReq *req;

    ctx = blk_get_aio_context(s->blk);

    aio_context_acquire(ctx);

    blk_drain(s->blk);

    /* We drop queued requests after blk_drain() because blk_drain() itself can

     * produce them. */

    while (s->rq) {

        req = s->rq;

        s->rq = req->next;

        virtqueue_detach_element(req->vq, &req->elem, 0);

        virtio_blk_free_request(req);

    }

    if (s->dataplane) {

        virtio_blk_data_plane_stop(s->dataplane);

    }

    aio_context_release(ctx);

    blk_set_enable_write_cache(s->blk, s->original_wce);

}


static void avc_h_loop_filter_luma_mbaff_msa(uint8_t *in, int32_t stride,

                                             int32_t alpha_in, int32_t beta_in,

                                             int8_t *tc0)

{

    uint8_t *data = in;

    uint32_t out0, out1, out2, out3;

    uint64_t load;

    uint32_t tc_val;

    v16u8 alpha, beta;

    v16i8 inp0 = { 0 };

    v16i8 inp1 = { 0 };

    v16i8 inp2 = { 0 };

    v16i8 inp3 = { 0 };

    v16i8 inp4 = { 0 };

    v16i8 inp5 = { 0 };

    v16i8 inp6 = { 0 };

    v16i8 inp7 = { 0 };

    v16i8 src0, src1, src2, src3;

    v8i16 src4, src5, src6, src7;

    v16u8 p0_asub_q0, p1_asub_p0, q1_asub_q0, p2_asub_p0, q2_asub_q0;

    v16u8 is_less_than, is_less_than_alpha, is_less_than_beta;

    v16u8 is_less_than_beta1, is_less_than_beta2;

    v8i16 tc, tc_orig_r, tc_plus1;

    v16u8 is_tc_orig1, is_tc_orig2, tc_orig = { 0 };

    v8i16 p0_ilvr_q0, p0_add_q0, q0_sub_p0, p1_sub_q1;

    v8u16 src2_r, src3_r;

    v8i16 p2_r, p1_r, q2_r, q1_r;

    v16u8 p2, q2, p0, q0;

    v4i32 dst0, dst1;

    v16i8 zeros = { 0 };

    alpha = (v16u8) __msa_fill_b(alpha_in);

    beta = (v16u8) __msa_fill_b(beta_in);

    if (tc0[0] < 0) {

        data += (2 * stride);

    } else {

        load = LOAD_DWORD(data - 3);

        inp0 = (v16i8) __msa_insert_d((v2i64) inp0, 0, load);

        load = LOAD_DWORD(data - 3 + stride);

        inp1 = (v16i8) __msa_insert_d((v2i64) inp1, 0, load);

        data += (2 * stride);

    }

    if (tc0[1] < 0) {

        data += (2 * stride);

    } else {

        load = LOAD_DWORD(data - 3);

        inp2 = (v16i8) __msa_insert_d((v2i64) inp2, 0, load);

        load = LOAD_DWORD(data - 3 + stride);

        inp3 = (v16i8) __msa_insert_d((v2i64) inp3, 0, load);

        data += (2 * stride);

    }

    if (tc0[2] < 0) {

        data += (2 * stride);

    } else {

        load = LOAD_DWORD(data - 3);

        inp4 = (v16i8) __msa_insert_d((v2i64) inp4, 0, load);

        load = LOAD_DWORD(data - 3 + stride);

        inp5 = (v16i8) __msa_insert_d((v2i64) inp5, 0, load);

        data += (2 * stride);

    }

    if (tc0[3] < 0) {

        data += (2 * stride);

    } else {

        load = LOAD_DWORD(data - 3);

        inp6 = (v16i8) __msa_insert_d((v2i64) inp6, 0, load);

        load = LOAD_DWORD(data - 3 + stride);

        inp7 = (v16i8) __msa_insert_d((v2i64) inp7, 0, load);

        data += (2 * stride);

    }

    src0 = __msa_ilvr_b(inp1, inp0);

    src1 = __msa_ilvr_b(inp3, inp2);

    src2 = __msa_ilvr_b(inp5, inp4);

    src3 = __msa_ilvr_b(inp7, inp6);

    src4 = __msa_ilvr_h((v8i16) src1, (v8i16) src0);

    src5 = __msa_ilvl_h((v8i16) src1, (v8i16) src0);

    src6 = __msa_ilvr_h((v8i16) src3, (v8i16) src2);

    src7 = __msa_ilvl_h((v8i16) src3, (v8i16) src2);

    src0 = (v16i8) __msa_ilvr_w((v4i32) src6, (v4i32) src4);

    src1 = __msa_sldi_b(zeros, (v16i8) src0, 8);

    src2 = (v16i8) __msa_ilvl_w((v4i32) src6, (v4i32) src4);

    src3 = __msa_sldi_b(zeros, (v16i8) src2, 8);

    src4 = (v8i16) __msa_ilvr_w((v4i32) src7, (v4i32) src5);

    src5 = (v8i16) __msa_sldi_b(zeros, (v16i8) src4, 8);

    p0_asub_q0 = __msa_asub_u_b((v16u8) src2, (v16u8) src3);

    p1_asub_p0 = __msa_asub_u_b((v16u8) src1, (v16u8) src2);

    q1_asub_q0 = __msa_asub_u_b((v16u8) src4, (v16u8) src3);

    p2_asub_p0 = __msa_asub_u_b((v16u8) src0, (v16u8) src2);

    q2_asub_q0 = __msa_asub_u_b((v16u8) src5, (v16u8) src3);

    is_less_than_alpha = (p0_asub_q0 < alpha);

    is_less_than_beta = (p1_asub_p0 < beta);

    is_less_than = is_less_than_alpha & is_less_than_beta;

    is_less_than_beta = (q1_asub_q0 < beta);

    is_less_than = is_less_than_beta & is_less_than;

    is_less_than_beta1 = (p2_asub_p0 < beta);

    is_less_than_beta2 = (q2_asub_q0 < beta);

    p0_ilvr_q0 = (v8i16) __msa_ilvr_b((v16i8) src3, (v16i8) src2);

    p0_add_q0 = (v8i16) __msa_hadd_u_h((v16u8) p0_ilvr_q0, (v16u8) p0_ilvr_q0);

    p0_add_q0 = __msa_srari_h(p0_add_q0, 1);

    p2_r = (v8i16) __msa_ilvr_b(zeros, src0);

    p1_r = (v8i16) __msa_ilvr_b(zeros, src1);

    p2_r += p0_add_q0;

    p2_r >>= 1;

    p2_r -= p1_r;

    q2_r = (v8i16) __msa_ilvr_b(zeros, (v16i8) src5);

    q1_r = (v8i16) __msa_ilvr_b(zeros, (v16i8) src4);

    q2_r += p0_add_q0;

    q2_r >>= 1;

    q2_r -= q1_r;

    tc_val = LOAD_WORD(tc0);

    tc_orig = (v16u8) __msa_insert_w((v4i32) tc_orig, 0, tc_val);

    tc_orig = (v16u8) __msa_ilvr_b((v16i8) tc_orig, (v16i8) tc_orig);

    is_tc_orig1 = tc_orig;

    is_tc_orig2 = tc_orig;

    tc_orig_r = (v8i16) __msa_ilvr_b(zeros, (v16i8) tc_orig);

    tc = tc_orig_r;

    p2_r = CLIP_MIN_TO_MAX_H(p2_r, -tc_orig_r, tc_orig_r);

    q2_r = CLIP_MIN_TO_MAX_H(q2_r, -tc_orig_r, tc_orig_r);

    p2_r += p1_r;

    q2_r += q1_r;

    p2 = (v16u8) __msa_pckev_b((v16i8) p2_r, (v16i8) p2_r);

    q2 = (v16u8) __msa_pckev_b((v16i8) q2_r, (v16i8) q2_r);

    is_tc_orig1 = (zeros < is_tc_orig1);

    is_tc_orig2 = is_tc_orig1;

    is_tc_orig1 = is_less_than_beta1 & is_tc_orig1;

    is_tc_orig2 = is_less_than_beta2 & is_tc_orig2;

    is_tc_orig1 = is_less_than & is_tc_orig1;

    is_tc_orig2 = is_less_than & is_tc_orig2;

    p2 = __msa_bmnz_v((v16u8) src1, p2, is_tc_orig1);

    q2 = __msa_bmnz_v((v16u8) src4, q2, is_tc_orig2);

    q0_sub_p0 = __msa_hsub_u_h((v16u8) p0_ilvr_q0, (v16u8) p0_ilvr_q0);

    q0_sub_p0 <<= 2;

    p1_sub_q1 = p1_r - q1_r;

    q0_sub_p0 += p1_sub_q1;

    q0_sub_p0 = __msa_srari_h(q0_sub_p0, 3);

    tc_plus1 = tc + 1;

    is_less_than_beta1 = (v16u8) __msa_ilvr_b((v16i8) is_less_than_beta1,

                                              (v16i8) is_less_than_beta1);

    tc = (v8i16) __msa_bmnz_v((v16u8) tc, (v16u8) tc_plus1, is_less_than_beta1);

    tc_plus1 = tc + 1;

    is_less_than_beta2 = (v16u8) __msa_ilvr_b((v16i8) is_less_than_beta2,

                                              (v16i8) is_less_than_beta2);

    tc = (v8i16) __msa_bmnz_v((v16u8) tc, (v16u8) tc_plus1, is_less_than_beta2);

    q0_sub_p0 = CLIP_MIN_TO_MAX_H(q0_sub_p0, -tc, tc);

    src2_r = (v8u16) __msa_ilvr_b(zeros, src2);

    src3_r = (v8u16) __msa_ilvr_b(zeros, src3);

    src2_r += q0_sub_p0;

    src3_r -= q0_sub_p0;

    src2_r = (v8u16) CLIP_UNSIGNED_CHAR_H(src2_r);

    src3_r = (v8u16) CLIP_UNSIGNED_CHAR_H(src3_r);

    p0 = (v16u8) __msa_pckev_b((v16i8) src2_r, (v16i8) src2_r);

    q0 = (v16u8) __msa_pckev_b((v16i8) src3_r, (v16i8) src3_r);

    p0 = __msa_bmnz_v((v16u8) src2, p0, is_less_than);

    q0 = __msa_bmnz_v((v16u8) src3, q0, is_less_than);

    p2 = (v16u8) __msa_ilvr_b((v16i8) p0, (v16i8) p2);

    q2 = (v16u8) __msa_ilvr_b((v16i8) q2, (v16i8) q0);

    dst0 = (v4i32) __msa_ilvr_h((v8i16) q2, (v8i16) p2);

    dst1 = (v4i32) __msa_ilvl_h((v8i16) q2, (v8i16) p2);

    data = in;

    out0 = __msa_copy_u_w(dst0, 0);

    out1 = __msa_copy_u_w(dst0, 1);

    out2 = __msa_copy_u_w(dst0, 2);

    out3 = __msa_copy_u_w(dst0, 3);

    if (tc0[0] < 0) {

        data += (2 * stride);

    } else {

        STORE_WORD((data - 2), out0);

        data += stride;

        STORE_WORD((data - 2), out1);

        data += stride;

    }

    if (tc0[1] < 0) {

        data += (2 * stride);

    } else {

        STORE_WORD((data - 2), out2);

        data += stride;

        STORE_WORD((data - 2), out3);

        data += stride;

    }

    out0 = __msa_copy_u_w(dst1, 0);

    out1 = __msa_copy_u_w(dst1, 1);

    out2 = __msa_copy_u_w(dst1, 2);

    out3 = __msa_copy_u_w(dst1, 3);

    if (tc0[2] < 0) {

        data += (2 * stride);

    } else {

        STORE_WORD((data - 2), out0);

        data += stride;

        STORE_WORD((data - 2), out1);

        data += stride;

    }

    if (tc0[3] >= 0) {

        STORE_WORD((data - 2), out2);

        data += stride;

        STORE_WORD((data - 2), out3);

    }

}


ISADevice *rtc_init(ISABus *bus, int base_year, qemu_irq intercept_irq)

{

    DeviceState *dev;

    ISADevice *isadev;

    RTCState *s;

    isadev = isa_create(bus, TYPE_MC146818_RTC);

    dev = DEVICE(isadev);

    s = MC146818_RTC(isadev);

    qdev_prop_set_int32(dev, "base_year", base_year);

    qdev_init_nofail(dev);

    if (intercept_irq) {

        s->irq = intercept_irq;

    } else {

        isa_init_irq(isadev, &s->irq, RTC_ISA_IRQ);

    }

    QLIST_INSERT_HEAD(&rtc_devices, s, link);

    return isadev;

}