static inline void RENAME(uyvytoyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,

                                      long width, long height,

                                      long lumStride, long chromStride, long srcStride)

{

    long y;

    const x86_reg chromWidth= width>>1;

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

#if COMPILE_TEMPLATE_MMX

        __asm__ volatile(

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

            "pcmpeqw             %%mm7, %%mm7   \n\t"

            "psrlw                  $8, %%mm7   \n\t" // FF,00,FF,00...

            ".p2align                4          \n\t"

            "1:                                 \n\t"

            PREFETCH" 64(%0, %%"REG_a", 4)          \n\t"

            "movq       (%0, %%"REG_a", 4), %%mm0   \n\t" // UYVY UYVY(0)

            "movq      8(%0, %%"REG_a", 4), %%mm1   \n\t" // UYVY UYVY(4)

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

            "movq                %%mm1, %%mm3   \n\t" // UYVY UYVY(4)

            "pand                %%mm7, %%mm0   \n\t" // U0V0 U0V0(0)

            "pand                %%mm7, %%mm1   \n\t" // U0V0 U0V0(4)

            "psrlw                  $8, %%mm2   \n\t" // Y0Y0 Y0Y0(0)

            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(4)

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

            "packuswb            %%mm3, %%mm2   \n\t" // YYYY YYYY(0)

            MOVNTQ"              %%mm2,  (%1, %%"REG_a", 2) \n\t"

            "movq     16(%0, %%"REG_a", 4), %%mm1   \n\t" // UYVY UYVY(8)

            "movq     24(%0, %%"REG_a", 4), %%mm2   \n\t" // UYVY UYVY(12)

            "movq                %%mm1, %%mm3   \n\t" // UYVY UYVY(8)

            "movq                %%mm2, %%mm4   \n\t" // UYVY UYVY(12)

            "pand                %%mm7, %%mm1   \n\t" // U0V0 U0V0(8)

            "pand                %%mm7, %%mm2   \n\t" // U0V0 U0V0(12)

            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(8)

            "psrlw                  $8, %%mm4   \n\t" // Y0Y0 Y0Y0(12)

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

            "packuswb            %%mm4, %%mm3   \n\t" // YYYY YYYY(8)

            MOVNTQ"              %%mm3, 8(%1, %%"REG_a", 2) \n\t"

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

            "movq                %%mm1, %%mm3   \n\t" // UVUV UVUV(8)

            "psrlw                  $8, %%mm0   \n\t" // V0V0 V0V0(0)

            "psrlw                  $8, %%mm1   \n\t" // V0V0 V0V0(8)

            "pand                %%mm7, %%mm2   \n\t" // U0U0 U0U0(0)

            "pand                %%mm7, %%mm3   \n\t" // U0U0 U0U0(8)

            "packuswb            %%mm1, %%mm0   \n\t" // VVVV VVVV(0)

            "packuswb            %%mm3, %%mm2   \n\t" // UUUU UUUU(0)

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

            MOVNTQ"              %%mm2, (%2, %%"REG_a") \n\t"

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

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

            " jb                    1b          \n\t"

            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

            : "memory", "%"REG_a

        );

        ydst += lumStride;

        src  += srcStride;

        __asm__ volatile(

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

            ".p2align                    4          \n\t"

            "1:                                 \n\t"

            PREFETCH" 64(%0, %%"REG_a", 4)          \n\t"

            "movq       (%0, %%"REG_a", 4), %%mm0   \n\t" // YUYV YUYV(0)

            "movq      8(%0, %%"REG_a", 4), %%mm1   \n\t" // YUYV YUYV(4)

            "movq     16(%0, %%"REG_a", 4), %%mm2   \n\t" // YUYV YUYV(8)

            "movq     24(%0, %%"REG_a", 4), %%mm3   \n\t" // YUYV YUYV(12)

            "psrlw                  $8, %%mm0   \n\t" // Y0Y0 Y0Y0(0)

            "psrlw                  $8, %%mm1   \n\t" // Y0Y0 Y0Y0(4)

            "psrlw                  $8, %%mm2   \n\t" // Y0Y0 Y0Y0(8)

            "psrlw                  $8, %%mm3   \n\t" // Y0Y0 Y0Y0(12)

            "packuswb            %%mm1, %%mm0   \n\t" // YYYY YYYY(0)

            "packuswb            %%mm3, %%mm2   \n\t" // YYYY YYYY(8)

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

            MOVNTQ"              %%mm2, 8(%1, %%"REG_a", 2) \n\t"

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

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

            " jb                    1b          \n\t"

            ::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

            : "memory", "%"REG_a

        );

#else

        long i;

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

            udst[i]     = src[4*i+0];

            ydst[2*i+0] = src[4*i+1];

            vdst[i]     = src[4*i+2];

            ydst[2*i+1] = src[4*i+3];

        }

        ydst += lumStride;

        src  += srcStride;

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

            ydst[2*i+0] = src[4*i+1];

            ydst[2*i+1] = src[4*i+3];

        }

#endif

        udst += chromStride;

        vdst += chromStride;

        ydst += lumStride;

        src  += srcStride;

    }

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(EMMS"       \n\t"

                     SFENCE"     \n\t"

                     :::"memory");

#endif

}


static struct omap_pwt_s *omap_pwt_init(MemoryRegion *system_memory,

                                        target_phys_addr_t base,

                                        omap_clk clk)

{

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

    s->clk = clk;

    omap_pwt_reset(s);

    memory_region_init_io(&s->iomem, &omap_pwt_ops, s,

                          "omap-pwt", 0x800);

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

    return s;

}


static int init_er(MpegEncContext *s)

{

    ERContext *er = &s->er;

    int mb_array_size = s->mb_height * s->mb_stride;

    int i;

    er->avctx       = s->avctx;

    er->mecc        = &s->mecc;

    er->mb_index2xy = s->mb_index2xy;

    er->mb_num      = s->mb_num;

    er->mb_width    = s->mb_width;

    er->mb_height   = s->mb_height;

    er->mb_stride   = s->mb_stride;

    er->b8_stride   = s->b8_stride;

    er->er_temp_buffer     = av_malloc(s->mb_height * s->mb_stride);

    er->error_status_table = av_mallocz(mb_array_size);

    if (!er->er_temp_buffer || !er->error_status_table)

        goto fail;

    er->mbskip_table  = s->mbskip_table;

    er->mbintra_table = s->mbintra_table;

    for (i = 0; i < FF_ARRAY_ELEMS(s->dc_val); i++)

        er->dc_val[i] = s->dc_val[i];

    er->decode_mb = mpeg_er_decode_mb;

    er->opaque    = s;

    return 0;

fail:

    av_freep(&er->er_temp_buffer);

    av_freep(&er->error_status_table);

    return AVERROR(ENOMEM);

}


static av_cold int xbm_encode_close(AVCodecContext *avctx)

{

    av_frame_free(&avctx->coded_frame);

    return 0;

}


int ff_lzw_decode_init(LZWState *p, int csize, uint8_t *buf, int buf_size, int mode)

{

    struct LZWState *s = (struct LZWState *)p;

    if(csize < 1 || csize > LZW_MAXBITS)

        return -1;

    /* read buffer */

    s->eob_reached = 0;

    s->pbuf = buf;

    s->ebuf = s->pbuf + buf_size;

    s->bbuf = 0;

    s->bbits = 0;

    s->bs = 0;

    /* decoder */

    s->codesize = csize;

    s->cursize = s->codesize + 1;

    s->curmask = mask[s->cursize];

    s->top_slot = 1 << s->cursize;

    s->clear_code = 1 << s->codesize;

    s->end_code = s->clear_code + 1;

    s->slot = s->newcodes = s->clear_code + 2;

    s->oc = s->fc = 0;

    s->sp = s->stack;

    s->mode = mode;

    switch(s->mode){

    case FF_LZW_GIF:

        s->extra_slot= 0;

        break;

    case FF_LZW_TIFF:

        s->extra_slot= 1;

        break;

    default:

        return -1;

    }

    return 0;

}


static target_long monitor_get_tbl (const struct MonitorDef *md, int val)

{

    CPUState *env = mon_get_cpu();

    if (!env)

        return 0;

    return cpu_ppc_load_tbl(env);

}


static void sub2video_update(InputStream *ist, AVSubtitle *sub)

{

    AVFrame *frame = ist->sub2video.frame;

    int8_t *dst;

    int     dst_linesize;

    int num_rects, i;

    int64_t pts, end_pts;

    if (!frame)

        return;

    if (sub) {

        pts       = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,

                                 AV_TIME_BASE_Q, ist->st->time_base);

        end_pts   = av_rescale_q(sub->pts + sub->end_display_time   * 1000LL,

                                 AV_TIME_BASE_Q, ist->st->time_base);

        num_rects = sub->num_rects;

    } else {

        pts       = ist->sub2video.end_pts;

        end_pts   = INT64_MAX;

        num_rects = 0;

    }

    if (sub2video_get_blank_frame(ist) < 0) {

        av_log(ist->dec_ctx, AV_LOG_ERROR,

               "Impossible to get a blank canvas.\n");

        return;

    }

    dst          = frame->data    [0];

    dst_linesize = frame->linesize[0];

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

        sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);

    sub2video_push_ref(ist, pts);

    ist->sub2video.end_pts = end_pts;

}


static void sdl_grab_start(void)

{

    if (guest_cursor) {

        SDL_SetCursor(guest_sprite);

        SDL_WarpMouse(guest_x, guest_y);

    } else

        sdl_hide_cursor();

    if (SDL_WM_GrabInput(SDL_GRAB_ON) == SDL_GRAB_ON) {

        gui_grab = 1;

        sdl_update_caption();

    } else

        sdl_show_cursor();

}


VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,

                            VirtIOHandleOutput handle_output)

{

    int i;

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

        if (vdev->vq[i].vring.num == 0)

            break;

    }

    if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)

        abort();

    vdev->vq[i].vring.num = queue_size;

    vdev->vq[i].vring.num_default = queue_size;

    vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;

    vdev->vq[i].handle_output = handle_output;

    vdev->vq[i].handle_aio_output = NULL;

    return &vdev->vq[i];

}


static void discard_vq_data(VirtQueue *vq, VirtIODevice *vdev)

{

    VirtQueueElement elem;

    if (!virtio_queue_ready(vq)) {

        return;

    }

    while (virtqueue_pop(vq, &elem)) {

        virtqueue_push(vq, &elem, 0);

    }

    virtio_notify(vdev, vq);

}


static void usbredir_chardev_open(USBRedirDevice *dev)

{

    uint32_t caps[USB_REDIR_CAPS_SIZE] = { 0, };

    char version[32];

    int flags = 0;

    /* Make sure any pending closes are handled (no-op if none pending) */

    usbredir_chardev_close_bh(dev);

    qemu_bh_cancel(dev->chardev_close_bh);

    DPRINTF("creating usbredirparser\n");

    strcpy(version, "qemu usb-redir guest ");

    pstrcat(version, sizeof(version), qemu_get_version());

    dev->parser = qemu_oom_check(usbredirparser_create());

    dev->parser->priv = dev;

    dev->parser->log_func = usbredir_log;

    dev->parser->read_func = usbredir_read;

    dev->parser->write_func = usbredir_write;

    dev->parser->hello_func = usbredir_hello;

    dev->parser->device_connect_func = usbredir_device_connect;

    dev->parser->device_disconnect_func = usbredir_device_disconnect;

    dev->parser->interface_info_func = usbredir_interface_info;

    dev->parser->ep_info_func = usbredir_ep_info;

    dev->parser->configuration_status_func = usbredir_configuration_status;

    dev->parser->alt_setting_status_func = usbredir_alt_setting_status;

    dev->parser->iso_stream_status_func = usbredir_iso_stream_status;

    dev->parser->interrupt_receiving_status_func =

        usbredir_interrupt_receiving_status;

    dev->parser->bulk_streams_status_func = usbredir_bulk_streams_status;

    dev->parser->control_packet_func = usbredir_control_packet;

    dev->parser->bulk_packet_func = usbredir_bulk_packet;

    dev->parser->iso_packet_func = usbredir_iso_packet;

    dev->parser->interrupt_packet_func = usbredir_interrupt_packet;

    dev->read_buf = NULL;

    dev->read_buf_size = 0;

    usbredirparser_caps_set_cap(caps, usb_redir_cap_connect_device_version);

    usbredirparser_caps_set_cap(caps, usb_redir_cap_filter);

    usbredirparser_caps_set_cap(caps, usb_redir_cap_ep_info_max_packet_size);

    usbredirparser_caps_set_cap(caps, usb_redir_cap_64bits_ids);

    if (runstate_check(RUN_STATE_INMIGRATE)) {

        flags |= usbredirparser_fl_no_hello;

    }

    usbredirparser_init(dev->parser, version, caps, USB_REDIR_CAPS_SIZE,

                        flags);

    usbredirparser_do_write(dev->parser);

}


void migrate_compress_threads_create(void)

{

    int i, thread_count;

    if (!migrate_use_compression()) {

        return;

    }

    quit_comp_thread = false;

    compression_switch = true;

    thread_count = migrate_compress_threads();

    compress_threads = g_new0(QemuThread, thread_count);

    comp_param = g_new0(CompressParam, thread_count);

    comp_done_cond = g_new0(QemuCond, 1);

    comp_done_lock = g_new0(QemuMutex, 1);

    qemu_cond_init(comp_done_cond);

    qemu_mutex_init(comp_done_lock);

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

        /* com_param[i].file is just used as a dummy buffer to save data, set

         * it's ops to empty.

         */

        comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);

        comp_param[i].done = true;

        qemu_mutex_init(&comp_param[i].mutex);

        qemu_cond_init(&comp_param[i].cond);

        qemu_thread_create(compress_threads + i, "compress",

                           do_data_compress, comp_param + i,

                           QEMU_THREAD_JOINABLE);

    }

}


void validate_bootdevices(const char *devices)

{

    /* We just do some generic consistency checks */

    const char *p;

    int bitmap = 0;

    for (p = devices; *p != '\0'; p++) {

        /* Allowed boot devices are:

         * a-b: floppy disk drives

         * c-f: IDE disk drives

         * g-m: machine implementation dependent drives

         * n-p: network devices

         * It's up to each machine implementation to check if the given boot

         * devices match the actual hardware implementation and firmware

         * features.

         */

        if (*p < 'a' || *p > 'p') {

            fprintf(stderr, "Invalid boot device '%c'\n", *p);

            exit(1);

        }

        if (bitmap & (1 << (*p - 'a'))) {

            fprintf(stderr, "Boot device '%c' was given twice\n", *p);

            exit(1);

        }

        bitmap |= 1 << (*p - 'a');

    }

}


static inline void cpu_loop_exec_tb(CPUState *cpu, TranslationBlock *tb,

                                    TranslationBlock **last_tb, int *tb_exit,

                                    SyncClocks *sc)

{

    uintptr_t ret;

    int32_t insns_left;

    if (unlikely(atomic_read(&cpu->exit_request))) {

        return;

    }

    trace_exec_tb(tb, tb->pc);

    ret = cpu_tb_exec(cpu, tb);

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

    *tb_exit = ret & TB_EXIT_MASK;

    if (*tb_exit != TB_EXIT_REQUESTED) {

        *last_tb = tb;

        return;

    }

    *last_tb = NULL;

    insns_left = atomic_read(&cpu->icount_decr.u32);

    atomic_set(&cpu->icount_decr.u16.high, 0);

    if (insns_left < 0) {

        /* Something asked us to stop executing

         * chained TBs; just continue round the main

         * loop. Whatever requested the exit will also

         * have set something else (eg exit_request or

         * interrupt_request) which we will handle

         * next time around the loop.  But we need to

         * ensure the zeroing of tcg_exit_req (see cpu_tb_exec)

         * comes before the next read of cpu->exit_request

         * or cpu->interrupt_request.

         */

        smp_mb();

        return;

    }

    /* Instruction counter expired.  */

    assert(use_icount);

#ifndef CONFIG_USER_ONLY

    if (cpu->icount_extra) {

        /* Refill decrementer and continue execution.  */

        cpu->icount_extra += insns_left;

        insns_left = MIN(0xffff, cpu->icount_extra);

        cpu->icount_extra -= insns_left;

        cpu->icount_decr.u16.low = insns_left;

    } else {

        /* Execute any remaining instructions, then let the main loop

         * handle the next event.

         */

        if (insns_left > 0) {

            cpu_exec_nocache(cpu, insns_left, tb, false);

            align_clocks(sc, cpu);

        }

        cpu->exception_index = EXCP_INTERRUPT;

        cpu_loop_exit(cpu);

    }

#endif

}


static int test_butterflies_float(AVFloatDSPContext *fdsp, AVFloatDSPContext *cdsp,

                                  const float *v1, const float *v2)

{

    LOCAL_ALIGNED(32, float, cv1, [LEN]);

    LOCAL_ALIGNED(32, float, cv2, [LEN]);

    LOCAL_ALIGNED(32, float, ov1, [LEN]);

    LOCAL_ALIGNED(32, float, ov2, [LEN]);

    int ret;

    memcpy(cv1, v1, LEN * sizeof(*v1));

    memcpy(cv2, v2, LEN * sizeof(*v2));

    memcpy(ov1, v1, LEN * sizeof(*v1));

    memcpy(ov2, v2, LEN * sizeof(*v2));

    cdsp->butterflies_float(cv1, cv2, LEN);

    fdsp->butterflies_float(ov1, ov2, LEN);

    if ((ret = compare_floats(cv1, ov1, LEN, FLT_EPSILON)) ||

        (ret = compare_floats(cv2, ov2, LEN, FLT_EPSILON)))

        av_log(NULL, AV_LOG_ERROR, "butterflies_float failed\n");

    return ret;

}


static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,

                               int64_t *ppos, int64_t pos_limit)

{

    int len, startcode;

    int64_t pos, pts, dts;

    pos = *ppos;

#ifdef DEBUG_SEEK

    printf("read_dts: pos=0x%"PRIx64" next=%d -> ", pos, find_next);

#endif

    url_fseek(s->pb, pos, SEEK_SET);

    for(;;) {

        len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);

        if (len < 0) {

#ifdef DEBUG_SEEK

            printf("none (ret=%d)\n", len);

#endif

            return AV_NOPTS_VALUE;

        }

        if (startcode == s->streams[stream_index]->id &&

            dts != AV_NOPTS_VALUE) {

            break;

        }

        url_fskip(s->pb, len);

    }

#ifdef DEBUG_SEEK

    printf("pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n", pos, dts, dts / 90000.0);

#endif

    *ppos = pos;

    return dts;

}


static void pc_dimm_realize(DeviceState *dev, Error **errp)

{

    PCDIMMDevice *dimm = PC_DIMM(dev);

    if (!dimm->hostmem) {

        error_setg(errp, "'" PC_DIMM_MEMDEV_PROP "' property is not set");

        return;

    }

    if ((nb_numa_nodes > 0) && (dimm->node >= nb_numa_nodes)) {

        error_setg(errp, "'DIMM property " PC_DIMM_NODE_PROP " has value %"

                   PRIu32 "' which exceeds the number of numa nodes: %d",

                   dimm->node, nb_numa_nodes);

        return;

    }

}


static int libssh_open(URLContext *h, const char *url, int flags)

{

    static const int verbosity = SSH_LOG_NOLOG;

    LIBSSHContext *s = h->priv_data;

    char proto[10], path[MAX_URL_SIZE], hostname[1024], credencials[1024];

    int port = 22, access, ret;

    long timeout = s->rw_timeout * 1000;

    const char *user = NULL, *pass = NULL;

    char *end = NULL;

    sftp_attributes stat;

    av_url_split(proto, sizeof(proto),

                 credencials, sizeof(credencials),

                 hostname, sizeof(hostname),

                 &port,

                 path, sizeof(path),

                 url);

    if (port <= 0 || port > 65535)

        port = 22;

    if (!(s->session = ssh_new())) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    user = av_strtok(credencials, ":", &end);

    pass = av_strtok(end, ":", &end);

    ssh_options_set(s->session, SSH_OPTIONS_HOST, hostname);

    ssh_options_set(s->session, SSH_OPTIONS_PORT, &port);

    ssh_options_set(s->session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);

    if (timeout > 0)

        ssh_options_set(s->session, SSH_OPTIONS_TIMEOUT_USEC, &timeout);

    if (user)

        ssh_options_set(s->session, SSH_OPTIONS_USER, user);

    if (ssh_connect(s->session) != SSH_OK) {

        av_log(h, AV_LOG_ERROR, "Connection failed. %s\n", ssh_get_error(s->session));

        ret = AVERROR(EIO);

        goto fail;

    }

    if (pass && ssh_userauth_password(s->session, NULL, pass) != SSH_AUTH_SUCCESS) {

        av_log(h, AV_LOG_ERROR, "Error authenticating with password: %s\n", ssh_get_error(s->session));

        ret = AVERROR(EACCES);

        goto fail;

    }

    if (!(s->sftp = sftp_new(s->session))) {

        av_log(h, AV_LOG_ERROR, "SFTP session creation failed: %s\n", ssh_get_error(s->session));

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    if (sftp_init(s->sftp) != SSH_OK) {

        av_log(h, AV_LOG_ERROR, "Error initializing sftp session: %s\n", ssh_get_error(s->session));

        ret = AVERROR(EIO);

        goto fail;

    }

    if ((flags & AVIO_FLAG_WRITE) && (flags & AVIO_FLAG_READ)) {

        access = O_CREAT | O_RDWR;

        if (s->trunc)

            access |= O_TRUNC;

    } else if (flags & AVIO_FLAG_WRITE) {

        access = O_CREAT | O_WRONLY;

        if (s->trunc)

            access |= O_TRUNC;

    } else {

        access = O_RDONLY;

    }

    /* 0666 = -rw-rw-rw- = read+write for everyone, minus umask */

    if (!(s->file = sftp_open(s->sftp, path, access, 0666))) {

        av_log(h, AV_LOG_ERROR, "Error opening sftp file: %s\n", ssh_get_error(s->session));

        ret = AVERROR(EIO);

        goto fail;

    }

    if (!(stat = sftp_fstat(s->file))) {

        av_log(h, AV_LOG_WARNING, "Cannot stat remote file %s.\n", path);

        s->filesize = -1;

    } else {

        s->filesize = stat->size;

        sftp_attributes_free(stat);

    }

    return 0;

  fail:

    libssh_close(h);

    return ret;

}


void cpu_write_xer(CPUPPCState *env, target_ulong xer)

{

    env->so = (xer >> XER_SO) & 1;

    env->ov = (xer >> XER_OV) & 1;

    env->ca = (xer >> XER_CA) & 1;

    env->xer = xer & ~((1u << XER_SO) | (1u << XER_OV) | (1u << XER_CA));

}


void helper_divq_EAX_T0(void)

{

    uint64_t r0, r1;

    if (T0 == 0) {

        raise_exception(EXCP00_DIVZ);

    }

    r0 = EAX;

    r1 = EDX;

    div64(&r0, &r1, T0);

    EAX = r0;

    EDX = r1;

}


static int hevc_init(AVCodecParserContext *s)

{

    HEVCContext  *h  = &((HEVCParseContext *)s->priv_data)->h;

    h->HEVClc = av_mallocz(sizeof(HEVCLocalContext));

    h->skipped_bytes_pos_size = INT_MAX;

    return 0;

}


matroska_probe (AVProbeData *p)

{

    uint64_t total = 0;

    int len_mask = 0x80, size = 1, n = 1;

    uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };

    if (p->buf_size < 5)

        return 0;

    /* ebml header? */

    if ((p->buf[0] << 24 | p->buf[1] << 16 |

         p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)

        return 0;

    /* length of header */

    total = p->buf[4];

    while (size <= 8 && !(total & len_mask)) {

        size++;

        len_mask >>= 1;

    }

    if (size > 8)

      return 0;

    total &= (len_mask - 1);

    while (n < size)

        total = (total << 8) | p->buf[4 + n++];

    /* does the probe data contain the whole header? */

    if (p->buf_size < 4 + size + total)

      return 0;

    /* the header must contain the document type 'matroska'. For now,

     * we don't parse the whole header but simply check for the

     * availability of that array of characters inside the header.

     * Not fully fool-proof, but good enough. */

    for (n = 4 + size; n < 4 + size + total - sizeof(probe_data); n++)

        if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))

            return AVPROBE_SCORE_MAX;

    return 0;

}


static void FUNCC(pred16x16_vertical)(uint8_t *_src, int _stride){

    int i;

    pixel *src = (pixel*)_src;

    int stride = _stride/sizeof(pixel);

    const pixel4 a = ((pixel4*)(src-stride))[0];

    const pixel4 b = ((pixel4*)(src-stride))[1];

    const pixel4 c = ((pixel4*)(src-stride))[2];

    const pixel4 d = ((pixel4*)(src-stride))[3];

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

        ((pixel4*)(src+i*stride))[0] = a;

        ((pixel4*)(src+i*stride))[1] = b;

        ((pixel4*)(src+i*stride))[2] = c;

        ((pixel4*)(src+i*stride))[3] = d;

    }

}


static void rgb24_to_pal8(AVPicture *dst, AVPicture *src,

                          int width, int height)

{

    const unsigned char *p;

    unsigned char *q;

    int r, g, b, dst_wrap, src_wrap;

    int x, y, i;

    static const uint8_t pal_value[6] = { 0x00, 0x33, 0x66, 0x99, 0xcc, 0xff };

    uint32_t *pal;

    p = src->data[0];

    src_wrap = src->linesize[0] - 3 * width;

    q = dst->data[0];

    dst_wrap = dst->linesize[0] - width;

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

        for(x=0;x<width;x++) {

            r = p[0];

            g = p[1];

            b = p[2];

            q[0] = gif_clut_index(r, g, b);

            q++;

            p += 3;

        }

        p += src_wrap;

        q += dst_wrap;

    }

    /* build palette */

    pal = (uint32_t *)dst->data[1];

    i = 0;

    for(r = 0; r < 6; r++) {

        for(g = 0; g < 6; g++) {

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

                pal[i++] = (0xff << 24) | (pal_value[r] << 16) |

                    (pal_value[g] << 8) | pal_value[b];

            }

        }

    }

    while (i < 256)

        pal[i++] = 0;

}


vu_queue_flush(VuDev *dev, VuVirtq *vq, unsigned int count)

{

    uint16_t old, new;

    if (unlikely(dev->broken)) {

        return;

    }

    /* Make sure buffer is written before we update index. */

    smp_wmb();

    old = vq->used_idx;

    new = old + count;

    vring_used_idx_set(dev, vq, new);

    vq->inuse -= count;

    if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old))) {

        vq->signalled_used_valid = false;

    }

}


static int ioh3420_initfn(PCIDevice *d)

{

    PCIEPort *p = PCIE_PORT(d);

    PCIESlot *s = PCIE_SLOT(d);

    int rc;

    pci_bridge_initfn(d, TYPE_PCIE_BUS);

    pcie_port_init_reg(d);

    rc = pci_bridge_ssvid_init(d, IOH_EP_SSVID_OFFSET,

                               IOH_EP_SSVID_SVID, IOH_EP_SSVID_SSID);

    if (rc < 0) {

        goto err_bridge;

    }

    rc = msi_init(d, IOH_EP_MSI_OFFSET, IOH_EP_MSI_NR_VECTOR,

                  IOH_EP_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_64BIT,

                  IOH_EP_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_MASKBIT);

    if (rc < 0) {

        goto err_bridge;

    }

    rc = pcie_cap_init(d, IOH_EP_EXP_OFFSET, PCI_EXP_TYPE_ROOT_PORT, p->port);

    if (rc < 0) {

        goto err_msi;

    }

    pcie_cap_arifwd_init(d);

    pcie_cap_deverr_init(d);

    pcie_cap_slot_init(d, s->slot);

    pcie_cap_root_init(d);

    pcie_chassis_create(s->chassis);

    rc = pcie_chassis_add_slot(s);

    if (rc < 0) {

        goto err_pcie_cap;

    }

    rc = pcie_aer_init(d, IOH_EP_AER_OFFSET, PCI_ERR_SIZEOF);

    if (rc < 0) {

        goto err;

    }

    pcie_aer_root_init(d);

    ioh3420_aer_vector_update(d);

    return 0;

err:

    pcie_chassis_del_slot(s);

err_pcie_cap:

    pcie_cap_exit(d);

err_msi:

    msi_uninit(d);

err_bridge:

    pci_bridge_exitfn(d);

    return rc;

}


int ff_h264_decode_mb_cabac(const H264Context *h, H264SliceContext *sl)

{

    int mb_xy;

    int mb_type, partition_count, cbp = 0;

    int dct8x8_allowed= h->pps.transform_8x8_mode;

    int decode_chroma = h->sps.chroma_format_idc == 1 || h->sps.chroma_format_idc == 2;

    const int pixel_shift = h->pixel_shift;

    mb_xy = sl->mb_xy = sl->mb_x + sl->mb_y*h->mb_stride;

    ff_tlog(h->avctx, "pic:%d mb:%d/%d\n", h->frame_num, sl->mb_x, sl->mb_y);

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {

        int skip;

        /* a skipped mb needs the aff flag from the following mb */

        if (FRAME_MBAFF(h) && (sl->mb_y & 1) == 1 && sl->prev_mb_skipped)

            skip = sl->next_mb_skipped;

        else

            skip = decode_cabac_mb_skip(h, sl, sl->mb_x, sl->mb_y );

        /* read skip flags */

        if( skip ) {

            if (FRAME_MBAFF(h) && (sl->mb_y & 1) == 0) {

                h->cur_pic.mb_type[mb_xy] = MB_TYPE_SKIP;

                sl->next_mb_skipped = decode_cabac_mb_skip(h, sl, sl->mb_x, sl->mb_y+1 );

                if(!sl->next_mb_skipped)

                    sl->mb_mbaff = sl->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h, sl);

            }

            decode_mb_skip(h, sl);

            h->cbp_table[mb_xy] = 0;

            h->chroma_pred_mode_table[mb_xy] = 0;

            sl->last_qscale_diff = 0;

            return 0;

        }

    }

    if (FRAME_MBAFF(h)) {

        if ((sl->mb_y & 1) == 0)

            sl->mb_mbaff =

            sl->mb_field_decoding_flag = decode_cabac_field_decoding_flag(h, sl);

    }

    sl->prev_mb_skipped = 0;

    fill_decode_neighbors(h, sl, -(MB_FIELD(sl)));

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {

        int ctx = 0;

        av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_B);

        if (!IS_DIRECT(sl->left_type[LTOP] - 1))

            ctx++;

        if (!IS_DIRECT(sl->top_type - 1))

            ctx++;

        if( !get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+ctx] ) ){

            mb_type= 0; /* B_Direct_16x16 */

        }else if( !get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+3] ) ) {

            mb_type= 1 + get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ); /* B_L[01]_16x16 */

        }else{

            int bits;

            bits = get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+4] ) << 3;

            bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 2;

            bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] ) << 1;

            bits+= get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] );

            if( bits < 8 ){

                mb_type= bits + 3; /* B_Bi_16x16 through B_L1_L0_16x8 */

            }else if( bits == 13 ){

                mb_type = decode_cabac_intra_mb_type(sl, 32, 0);

                goto decode_intra_mb;

            }else if( bits == 14 ){

                mb_type= 11; /* B_L1_L0_8x16 */

            }else if( bits == 15 ){

                mb_type= 22; /* B_8x8 */

            }else{

                bits= ( bits<<1 ) + get_cabac_noinline( &sl->cabac, &sl->cabac_state[27+5] );

                mb_type= bits - 4; /* B_L0_Bi_* through B_Bi_Bi_* */

            }

        }

            partition_count= b_mb_type_info[mb_type].partition_count;

            mb_type=         b_mb_type_info[mb_type].type;

    } else if (sl->slice_type_nos == AV_PICTURE_TYPE_P) {

        if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[14] ) == 0 ) {

            /* P-type */

            if( get_cabac_noinline( &sl->cabac, &sl->cabac_state[15] ) == 0 ) {

                /* P_L0_D16x16, P_8x8 */

                mb_type= 3 * get_cabac_noinline( &sl->cabac, &sl->cabac_state[16] );

            } else {

                /* P_L0_D8x16, P_L0_D16x8 */

                mb_type= 2 - get_cabac_noinline( &sl->cabac, &sl->cabac_state[17] );

            }

            partition_count= p_mb_type_info[mb_type].partition_count;

            mb_type=         p_mb_type_info[mb_type].type;

        } else {

            mb_type = decode_cabac_intra_mb_type(sl, 17, 0);

            goto decode_intra_mb;

        }

    } else {

        mb_type = decode_cabac_intra_mb_type(sl, 3, 1);

        if (sl->slice_type == AV_PICTURE_TYPE_SI && mb_type)

            mb_type--;

        av_assert2(sl->slice_type_nos == AV_PICTURE_TYPE_I);

decode_intra_mb:

        partition_count = 0;

        cbp= i_mb_type_info[mb_type].cbp;

        sl->intra16x16_pred_mode = i_mb_type_info[mb_type].pred_mode;

        mb_type= i_mb_type_info[mb_type].type;

    }

    if (MB_FIELD(sl))

        mb_type |= MB_TYPE_INTERLACED;

    h->slice_table[mb_xy] = sl->slice_num;

    if(IS_INTRA_PCM(mb_type)) {

        const int mb_size = ff_h264_mb_sizes[h->sps.chroma_format_idc] *

                            h->sps.bit_depth_luma >> 3;

        const uint8_t *ptr;

        // We assume these blocks are very rare so we do not optimize it.

        // FIXME The two following lines get the bitstream position in the cabac

        // decode, I think it should be done by a function in cabac.h (or cabac.c).

        ptr= sl->cabac.bytestream;

        if(sl->cabac.low&0x1) ptr--;

        if(CABAC_BITS==16){

            if(sl->cabac.low&0x1FF) ptr--;

        }

        // The pixels are stored in the same order as levels in h->mb array.

        if ((int) (sl->cabac.bytestream_end - ptr) < mb_size)

            return -1;

        sl->intra_pcm_ptr = ptr;

        ptr += mb_size;

        ff_init_cabac_decoder(&sl->cabac, ptr, sl->cabac.bytestream_end - ptr);

        // All blocks are present

        h->cbp_table[mb_xy] = 0xf7ef;

        h->chroma_pred_mode_table[mb_xy] = 0;

        // In deblocking, the quantizer is 0

        h->cur_pic.qscale_table[mb_xy] = 0;

        // All coeffs are present

        memset(h->non_zero_count[mb_xy], 16, 48);

        h->cur_pic.mb_type[mb_xy] = mb_type;

        sl->last_qscale_diff = 0;

        return 0;

    }

    fill_decode_caches(h, sl, mb_type);

    if( IS_INTRA( mb_type ) ) {

        int i, pred_mode;

        if( IS_INTRA4x4( mb_type ) ) {

            if (dct8x8_allowed && get_cabac_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size])) {

                mb_type |= MB_TYPE_8x8DCT;

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

                    int pred = pred_intra_mode(h, sl, i);

                    int mode = decode_cabac_mb_intra4x4_pred_mode(sl, pred);

                    fill_rectangle(&sl->intra4x4_pred_mode_cache[scan8[i]], 2, 2, 8, mode, 1);

                }

            } else {

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

                    int pred = pred_intra_mode(h, sl, i);

                    sl->intra4x4_pred_mode_cache[scan8[i]] = decode_cabac_mb_intra4x4_pred_mode(sl, pred);

                    ff_tlog(h->avctx, "i4x4 pred=%d mode=%d\n", pred,

                            sl->intra4x4_pred_mode_cache[scan8[i]]);

                }

            }

            write_back_intra_pred_mode(h, sl);

            if (ff_h264_check_intra4x4_pred_mode(h, sl) < 0 ) return -1;

        } else {

            sl->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, sl, sl->intra16x16_pred_mode, 0);

            if (sl->intra16x16_pred_mode < 0) return -1;

        }

        if(decode_chroma){

            h->chroma_pred_mode_table[mb_xy] =

            pred_mode                        = decode_cabac_mb_chroma_pre_mode(h, sl);

            pred_mode= ff_h264_check_intra_pred_mode(h, sl, pred_mode, 1 );

            if( pred_mode < 0 ) return -1;

            sl->chroma_pred_mode = pred_mode;

        } else {

            sl->chroma_pred_mode = DC_128_PRED8x8;

        }

    } else if( partition_count == 4 ) {

        int i, j, sub_partition_count[4], list, ref[2][4];

        if (sl->slice_type_nos == AV_PICTURE_TYPE_B ) {

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

                sl->sub_mb_type[i] = decode_cabac_b_mb_sub_type(sl);

                sub_partition_count[i] = b_sub_mb_type_info[sl->sub_mb_type[i]].partition_count;

                sl->sub_mb_type[i]     = b_sub_mb_type_info[sl->sub_mb_type[i]].type;

            }

            if (IS_DIRECT(sl->sub_mb_type[0] | sl->sub_mb_type[1] |

                          sl->sub_mb_type[2] | sl->sub_mb_type[3])) {

                ff_h264_pred_direct_motion(h, sl, &mb_type);

                sl->ref_cache[0][scan8[4]] =

                sl->ref_cache[1][scan8[4]] =

                sl->ref_cache[0][scan8[12]] =

                sl->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;

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

                        fill_rectangle(&sl->direct_cache[scan8[4*i]], 2, 2, 8, (sl->sub_mb_type[i] >> 1) & 0xFF, 1);

            }

        } else {

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

                sl->sub_mb_type[i] = decode_cabac_p_mb_sub_type(sl);

                sub_partition_count[i] = p_sub_mb_type_info[sl->sub_mb_type[i]].partition_count;

                sl->sub_mb_type[i]     = p_sub_mb_type_info[sl->sub_mb_type[i]].type;

            }

        }

        for( list = 0; list < sl->list_count; list++ ) {

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

                    if(IS_DIRECT(sl->sub_mb_type[i])) continue;

                    if(IS_DIR(sl->sub_mb_type[i], 0, list)){

                        unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);

                        if (rc > 1) {

                            ref[list][i] = decode_cabac_mb_ref(sl, list, 4 * i);

                            if (ref[list][i] >= rc) {

                                av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref[list][i], rc);

                                return -1;

                            }

                        }else

                            ref[list][i] = 0;

                    } else {

                        ref[list][i] = -1;

                    }

                    sl->ref_cache[list][scan8[4 * i] + 1] =

                    sl->ref_cache[list][scan8[4 * i] + 8] = sl->ref_cache[list][scan8[4 * i] + 9] = ref[list][i];

                }

        }

        if(dct8x8_allowed)

            dct8x8_allowed = get_dct8x8_allowed(h, sl);

        for (list = 0; list < sl->list_count; list++) {

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

                sl->ref_cache[list][scan8[4 * i]] = sl->ref_cache[list][scan8[4 * i] + 1];

                if(IS_DIRECT(sl->sub_mb_type[i])){

                    fill_rectangle(sl->mvd_cache[list][scan8[4*i]], 2, 2, 8, 0, 2);

                    continue;

                }

                if(IS_DIR(sl->sub_mb_type[i], 0, list) && !IS_DIRECT(sl->sub_mb_type[i])){

                    const int sub_mb_type= sl->sub_mb_type[i];

                    const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;

                    for(j=0; j<sub_partition_count[i]; j++){

                        int mpx, mpy;

                        int mx, my;

                        const int index= 4*i + block_width*j;

                        int16_t (* mv_cache)[2] = &sl->mv_cache[list][ scan8[index] ];

                        uint8_t (* mvd_cache)[2]= &sl->mvd_cache[list][ scan8[index] ];

                        pred_motion(h, sl, index, block_width, list, sl->ref_cache[list][ scan8[index] ], &mx, &my);

                        DECODE_CABAC_MB_MVD(sl, list, index)

                        ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                        if(IS_SUB_8X8(sub_mb_type)){

                            mv_cache[ 1 ][0]=

                            mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;

                            mv_cache[ 1 ][1]=

                            mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;

                            mvd_cache[ 1 ][0]=

                            mvd_cache[ 8 ][0]= mvd_cache[ 9 ][0]= mpx;

                            mvd_cache[ 1 ][1]=

                            mvd_cache[ 8 ][1]= mvd_cache[ 9 ][1]= mpy;

                        }else if(IS_SUB_8X4(sub_mb_type)){

                            mv_cache[ 1 ][0]= mx;

                            mv_cache[ 1 ][1]= my;

                            mvd_cache[ 1 ][0]=  mpx;

                            mvd_cache[ 1 ][1]= mpy;

                        }else if(IS_SUB_4X8(sub_mb_type)){

                            mv_cache[ 8 ][0]= mx;

                            mv_cache[ 8 ][1]= my;

                            mvd_cache[ 8 ][0]= mpx;

                            mvd_cache[ 8 ][1]= mpy;

                        }

                        mv_cache[ 0 ][0]= mx;

                        mv_cache[ 0 ][1]= my;

                        mvd_cache[ 0 ][0]= mpx;

                        mvd_cache[ 0 ][1]= mpy;

                    }

                }else{

                    fill_rectangle(sl->mv_cache [list][ scan8[4*i] ], 2, 2, 8, 0, 4);

                    fill_rectangle(sl->mvd_cache[list][ scan8[4*i] ], 2, 2, 8, 0, 2);

                }

            }

        }

    } else if( IS_DIRECT(mb_type) ) {

        ff_h264_pred_direct_motion(h, sl, &mb_type);

        fill_rectangle(sl->mvd_cache[0][scan8[0]], 4, 4, 8, 0, 2);

        fill_rectangle(sl->mvd_cache[1][scan8[0]], 4, 4, 8, 0, 2);

        dct8x8_allowed &= h->sps.direct_8x8_inference_flag;

    } else {

        int list, i;

        if(IS_16X16(mb_type)){

            for (list = 0; list < sl->list_count; list++) {

                if(IS_DIR(mb_type, 0, list)){

                    int ref;

                    unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);

                    if (rc > 1) {

                        ref= decode_cabac_mb_ref(sl, list, 0);

                        if (ref >= rc) {

                            av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, rc);

                            return -1;

                        }

                    }else

                        ref=0;

                    fill_rectangle(&sl->ref_cache[list][ scan8[0] ], 4, 4, 8, ref, 1);

                }

            }

            for (list = 0; list < sl->list_count; list++) {

                if(IS_DIR(mb_type, 0, list)){

                    int mx,my,mpx,mpy;

                    pred_motion(h, sl, 0, 4, list, sl->ref_cache[list][ scan8[0] ], &mx, &my);

                    DECODE_CABAC_MB_MVD(sl, list, 0)

                    ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                    fill_rectangle(sl->mvd_cache[list][ scan8[0] ], 4, 4, 8, pack8to16(mpx,mpy), 2);

                    fill_rectangle(sl->mv_cache[list][ scan8[0] ], 4, 4, 8, pack16to32(mx,my), 4);

                }

            }

        }

        else if(IS_16X8(mb_type)){

            for (list = 0; list < sl->list_count; list++) {

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

                        if(IS_DIR(mb_type, i, list)){

                            int ref;

                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);

                            if (rc > 1) {

                                ref= decode_cabac_mb_ref(sl, list, 8 * i);

                                if (ref >= rc) {

                                    av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, rc);

                                    return -1;

                                }

                            }else

                                ref=0;

                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, ref, 1);

                        }else

                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, (LIST_NOT_USED&0xFF), 1);

                    }

            }

            for (list = 0; list < sl->list_count; list++) {

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

                    if(IS_DIR(mb_type, i, list)){

                        int mx,my,mpx,mpy;

                        pred_16x8_motion(h, sl, 8*i, list, sl->ref_cache[list][scan8[0] + 16*i], &mx, &my);

                        DECODE_CABAC_MB_MVD(sl, list, 8*i)

                        ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack8to16(mpx,mpy), 2);

                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, pack16to32(mx,my), 4);

                    }else{

                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 2);

                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, 0, 4);

                    }

                }

            }

        }else{

            av_assert2(IS_8X16(mb_type));

            for (list = 0; list < sl->list_count; list++) {

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

                        if(IS_DIR(mb_type, i, list)){ //FIXME optimize

                            int ref;

                            unsigned rc = sl->ref_count[list] << MB_MBAFF(sl);

                            if (rc > 1) {

                                ref = decode_cabac_mb_ref(sl, list, 4 * i);

                                if (ref >= rc) {

                                    av_log(h->avctx, AV_LOG_ERROR, "Reference %d >= %d\n", ref, rc);

                                    return -1;

                                }

                            }else

                                ref=0;

                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, ref, 1);

                        }else

                            fill_rectangle(&sl->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, (LIST_NOT_USED&0xFF), 1);

                    }

            }

            for (list = 0; list < sl->list_count; list++) {

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

                    if(IS_DIR(mb_type, i, list)){

                        int mx,my,mpx,mpy;

                        pred_8x16_motion(h, sl, i*4, list, sl->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);

                        DECODE_CABAC_MB_MVD(sl, list, 4*i)

                        ff_tlog(h->avctx, "final mv:%d %d\n", mx, my);

                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack8to16(mpx,mpy), 2);

                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, pack16to32(mx,my), 4);

                    }else{

                        fill_rectangle(sl->mvd_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 2);

                        fill_rectangle(sl->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, 0, 4);

                    }

                }

            }

        }

    }

   if( IS_INTER( mb_type ) ) {

        h->chroma_pred_mode_table[mb_xy] = 0;

        write_back_motion(h, sl, mb_type);

   }

    if( !IS_INTRA16x16( mb_type ) ) {

        cbp  = decode_cabac_mb_cbp_luma(sl);

        if(decode_chroma)

            cbp |= decode_cabac_mb_cbp_chroma(sl) << 4;

    } else {

        if (!decode_chroma && cbp>15) {

            av_log(h->avctx, AV_LOG_ERROR, "gray chroma\n");

            return AVERROR_INVALIDDATA;

        }

    }

    h->cbp_table[mb_xy] = sl->cbp = cbp;

    if( dct8x8_allowed && (cbp&15) && !IS_INTRA( mb_type ) ) {

        mb_type |= MB_TYPE_8x8DCT * get_cabac_noinline(&sl->cabac, &sl->cabac_state[399 + sl->neighbor_transform_size]);

    }

    /* It would be better to do this in fill_decode_caches, but we don't know

     * the transform mode of the current macroblock there. */

    if (CHROMA444(h) && IS_8x8DCT(mb_type)){

        int i;

        uint8_t *nnz_cache = sl->non_zero_count_cache;

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

            if (sl->left_type[LEFT(i)] && !IS_8x8DCT(sl->left_type[LEFT(i)])) {

                nnz_cache[3+8* 1 + 2*8*i]=

                nnz_cache[3+8* 2 + 2*8*i]=

                nnz_cache[3+8* 6 + 2*8*i]=

                nnz_cache[3+8* 7 + 2*8*i]=

                nnz_cache[3+8*11 + 2*8*i]=

                nnz_cache[3+8*12 + 2*8*i]= IS_INTRA(mb_type) ? 64 : 0;

            }

        }

        if (sl->top_type && !IS_8x8DCT(sl->top_type)){

            uint32_t top_empty = CABAC(h) && !IS_INTRA(mb_type) ? 0 : 0x40404040;

            AV_WN32A(&nnz_cache[4+8* 0], top_empty);

            AV_WN32A(&nnz_cache[4+8* 5], top_empty);

            AV_WN32A(&nnz_cache[4+8*10], top_empty);

        }

    }

    h->cur_pic.mb_type[mb_xy] = mb_type;

    if( cbp || IS_INTRA16x16( mb_type ) ) {

        const uint8_t *scan, *scan8x8;

        const uint32_t *qmul;

        if(IS_INTERLACED(mb_type)){

            scan8x8 = sl->qscale ? h->field_scan8x8 : h->field_scan8x8_q0;

            scan    = sl->qscale ? h->field_scan : h->field_scan_q0;

        }else{

            scan8x8 = sl->qscale ? h->zigzag_scan8x8 : h->zigzag_scan8x8_q0;

            scan    = sl->qscale ? h->zigzag_scan : h->zigzag_scan_q0;

        }

        // decode_cabac_mb_dqp

        if(get_cabac_noinline( &sl->cabac, &sl->cabac_state[60 + (sl->last_qscale_diff != 0)])){

            int val = 1;

            int ctx= 2;

            const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);

            while( get_cabac_noinline( &sl->cabac, &sl->cabac_state[60 + ctx] ) ) {

                ctx= 3;

                val++;

                if(val > 2*max_qp){ //prevent infinite loop

                    av_log(h->avctx, AV_LOG_ERROR, "cabac decode of qscale diff failed at %d %d\n", sl->mb_x, sl->mb_y);

                    return -1;

                }

            }

            if( val&0x01 )

                val=   (val + 1)>>1 ;

            else

                val= -((val + 1)>>1);

            sl->last_qscale_diff = val;

            sl->qscale += val;

            if (((unsigned)sl->qscale) > max_qp){

                if (sl->qscale < 0) sl->qscale += max_qp + 1;

                else                sl->qscale -= max_qp + 1;

            }

            sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);

            sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);

        }else

            sl->last_qscale_diff=0;

        decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 0);

        if (CHROMA444(h)) {

            decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 1);

            decode_cabac_luma_residual(h, sl, scan, scan8x8, pixel_shift, mb_type, cbp, 2);

        } else if (CHROMA422(h)) {

            if( cbp&0x30 ){

                int c;

                for (c = 0; c < 2; c++)

                    decode_cabac_residual_dc_422(h, sl, sl->mb + ((256 + 16*16*c) << pixel_shift), 3,

                                                 CHROMA_DC_BLOCK_INDEX + c,

                                                 chroma422_dc_scan, 8);

            }

            if( cbp&0x20 ) {

                int c, i, i8x8;

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

                    int16_t *mb = sl->mb + (16*(16 + 16*c) << pixel_shift);

                    qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][sl->chroma_qp[c]];

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

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

                            const int index = 16 + 16 * c + 8*i8x8 + i;

                            decode_cabac_residual_nondc(h, sl, mb, 4, index, scan + 1, qmul, 15);

                            mb += 16<<pixel_shift;

                        }

                    }

                }

            } else {

                fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);

                fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);

            }

        } else /* yuv420 */ {

            if( cbp&0x30 ){

                int c;

                for (c = 0; c < 2; c++)

                    decode_cabac_residual_dc(h, sl, sl->mb + ((256 + 16*16*c) << pixel_shift), 3, CHROMA_DC_BLOCK_INDEX+c, chroma_dc_scan, 4);

            }

            if( cbp&0x20 ) {

                int c, i;

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

                    qmul = h->dequant4_coeff[c+1+(IS_INTRA( mb_type ) ? 0:3)][sl->chroma_qp[c]];

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

                        const int index = 16 + 16 * c + i;

                        decode_cabac_residual_nondc(h, sl, sl->mb + (16*index << pixel_shift), 4, index, scan + 1, qmul, 15);

                    }

                }

            } else {

                fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);

                fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);

            }

        }

    } else {

        fill_rectangle(&sl->non_zero_count_cache[scan8[ 0]], 4, 4, 8, 0, 1);

        fill_rectangle(&sl->non_zero_count_cache[scan8[16]], 4, 4, 8, 0, 1);

        fill_rectangle(&sl->non_zero_count_cache[scan8[32]], 4, 4, 8, 0, 1);

        sl->last_qscale_diff = 0;

    }

    h->cur_pic.qscale_table[mb_xy] = sl->qscale;

    write_back_non_zero_count(h, sl);

    return 0;

}


static void do_busid_cmd(ESPState *s, uint8_t *buf, uint8_t busid)

{

    int32_t datalen;

    int lun;

    DPRINTF("do_busid_cmd: busid 0x%x\n", busid);

    lun = busid & 7;

    datalen = s->current_dev->info->send_command(s->current_dev, 0, buf, lun);

    s->ti_size = datalen;

    if (datalen != 0) {

        s->rregs[ESP_RSTAT] = STAT_TC;

        s->dma_left = 0;

        s->dma_counter = 0;

        if (datalen > 0) {

            s->rregs[ESP_RSTAT] |= STAT_DI;

            s->current_dev->info->read_data(s->current_dev, 0);

        } else {

            s->rregs[ESP_RSTAT] |= STAT_DO;

            s->current_dev->info->write_data(s->current_dev, 0);

        }

    }

    s->rregs[ESP_RINTR] = INTR_BS | INTR_FC;

    s->rregs[ESP_RSEQ] = SEQ_CD;

    esp_raise_irq(s);

}


static int swf_write_header(AVFormatContext *s)

{

    SWFContext *swf = s->priv_data;

    AVIOContext *pb = s->pb;

    PutBitContext p;

    uint8_t buf1[256];

    int i, width, height, rate, rate_base;

    int version;

    swf->sound_samples = 0;

    swf->swf_frame_number = 0;

    swf->video_frame_number = 0;

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

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

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (swf->audio_enc) {

                av_log(s, AV_LOG_ERROR, "SWF muxer only supports 1 audio stream\n");

                return AVERROR_INVALIDDATA;

            if (enc->codec_id == AV_CODEC_ID_MP3) {

                if (!enc->frame_size) {

                    av_log(s, AV_LOG_ERROR, "audio frame size not set\n");

                    return -1;

                swf->audio_enc = enc;

                swf->audio_fifo= av_fifo_alloc(AUDIO_FIFO_SIZE);

                if (!swf->audio_fifo)

                    return AVERROR(ENOMEM);

            } else {

                av_log(s, AV_LOG_ERROR, "SWF muxer only supports MP3\n");

                return -1;

        } else {

            if (swf->video_enc) {

                av_log(s, AV_LOG_ERROR, "SWF muxer only supports 1 video stream\n");

                return AVERROR_INVALIDDATA;

            if (enc->codec_id == AV_CODEC_ID_VP6F ||

                enc->codec_id == AV_CODEC_ID_FLV1 ||

                enc->codec_id == AV_CODEC_ID_MJPEG) {

                swf->video_st  = s->streams[i];

                swf->video_enc = enc;

            } else {

                av_log(s, AV_LOG_ERROR, "SWF muxer only supports VP6, FLV1 and MJPEG\n");

                return -1;

    if (!swf->video_enc) {

        /* currently, cannot work correctly if audio only */

        width = 320;

        height = 200;

        rate = 10;

        rate_base= 1;

    } else {

        width = swf->video_enc->width;

        height = swf->video_enc->height;

        // TODO: should be avg_frame_rate

        rate = swf->video_st->time_base.den;

        rate_base = swf->video_st->time_base.num;

    if (!swf->audio_enc)

        swf->samples_per_frame = (44100LL * rate_base) / rate;

    else

        swf->samples_per_frame = (swf->audio_enc->sample_rate * rate_base) / rate;

    avio_write(pb, "FWS", 3);

    if (!strcmp("avm2", s->oformat->name))

        version = 9;

    else if (swf->video_enc && swf->video_enc->codec_id == AV_CODEC_ID_VP6F)

        version = 8; /* version 8 and above support VP6 codec */

    else if (swf->video_enc && swf->video_enc->codec_id == AV_CODEC_ID_FLV1)

        version = 6; /* version 6 and above support FLV1 codec */

    else

        version = 4; /* version 4 for mpeg audio support */

    avio_w8(pb, version);

    avio_wl32(pb, DUMMY_FILE_SIZE); /* dummy size

                                      (will be patched if not streamed) */

    put_swf_rect(pb, 0, width * 20, 0, height * 20);

    avio_wl16(pb, (rate * 256) / rate_base); /* frame rate */

    swf->duration_pos = avio_tell(pb);

    avio_wl16(pb, (uint16_t)(DUMMY_DURATION * (int64_t)rate / rate_base)); /* frame count */

    /* avm2/swf v9 (also v8?) files require a file attribute tag */

    if (version == 9) {

        put_swf_tag(s, TAG_FILEATTRIBUTES);

        avio_wl32(pb, 1<<3); /* set ActionScript v3/AVM2 flag */

        put_swf_end_tag(s);

    /* define a shape with the jpeg inside */

    if (swf->video_enc && swf->video_enc->codec_id == AV_CODEC_ID_MJPEG) {

        put_swf_tag(s, TAG_DEFINESHAPE);

        avio_wl16(pb, SHAPE_ID); /* ID of shape */

        /* bounding rectangle */

        put_swf_rect(pb, 0, width, 0, height);

        /* style info */

        avio_w8(pb, 1); /* one fill style */

        avio_w8(pb, 0x41); /* clipped bitmap fill */

        avio_wl16(pb, BITMAP_ID); /* bitmap ID */

        /* position of the bitmap */

        put_swf_matrix(pb, 1 << FRAC_BITS, 0,

                       0,  1 << FRAC_BITS, 0, 0);

        avio_w8(pb, 0); /* no line style */

        /* shape drawing */

        init_put_bits(&p, buf1, sizeof(buf1));

        put_bits(&p, 4, 1); /* one fill bit */

        put_bits(&p, 4, 0); /* zero line bit */

        put_bits(&p, 1, 0); /* not an edge */

        put_bits(&p, 5, FLAG_MOVETO | FLAG_SETFILL0);

        put_bits(&p, 5, 1); /* nbits */

        put_bits(&p, 1, 0); /* X */

        put_bits(&p, 1, 0); /* Y */

        put_bits(&p, 1, 1); /* set fill style 1 */

        /* draw the rectangle ! */

        put_swf_line_edge(&p, width, 0);

        put_swf_line_edge(&p, 0, height);

        put_swf_line_edge(&p, -width, 0);

        put_swf_line_edge(&p, 0, -height);

        /* end of shape */

        put_bits(&p, 1, 0); /* not an edge */

        put_bits(&p, 5, 0);

        flush_put_bits(&p);

        avio_write(pb, buf1, put_bits_ptr(&p) - p.buf);

        put_swf_end_tag(s);

    if (swf->audio_enc && swf->audio_enc->codec_id == AV_CODEC_ID_MP3) {

        int v = 0;

        /* start sound */

        put_swf_tag(s, TAG_STREAMHEAD2);

        switch(swf->audio_enc->sample_rate) {

        case 11025: v |= 1 << 2; break;

        case 22050: v |= 2 << 2; break;

        case 44100: v |= 3 << 2; break;

        default:

            /* not supported */

            av_log(s, AV_LOG_ERROR, "swf does not support that sample rate, choose from (44100, 22050, 11025).\n");

            return -1;

        v |= 0x02; /* 16 bit playback */

        if (swf->audio_enc->channels == 2)

            v |= 0x01; /* stereo playback */

        avio_w8(s->pb, v);

        v |= 0x20; /* mp3 compressed */

        avio_w8(s->pb, v);

        avio_wl16(s->pb, swf->samples_per_frame);  /* avg samples per frame */

        avio_wl16(s->pb, 0);

        put_swf_end_tag(s);

    avio_flush(s->pb);

    return 0;


static void decode(AVCodecContext *dec_ctx, AVFrame *frame, AVPacket *pkt,

                   const char *filename)

{

    char buf[1024];

    int ret;

    ret = avcodec_send_packet(dec_ctx, pkt);

    if (ret < 0) {

        fprintf(stderr, "Error sending a packet for decoding\n");

        exit(1);

    }

    while (ret >= 0) {

        ret = avcodec_receive_frame(dec_ctx, frame);

        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)

            return;

        else if (ret < 0) {

            fprintf(stderr, "Error during decoding\n");

            exit(1);

        }

        printf("saving frame %3d\n", dec_ctx->frame_number);

        fflush(stdout);

        /* the picture is allocated by the decoder. no need to

           free it */

        snprintf(buf, sizeof(buf), filename, dec_ctx->frame_number);

        pgm_save(frame->data[0], frame->linesize[0],

                 frame->width, frame->height, buf);

    }

}


static TCGv neon_load_scratch(int scratch)

{

    TCGv tmp = new_tmp();

    tcg_gen_ld_i32(tmp, cpu_env, offsetof(CPUARMState, vfp.scratch[scratch]));

    return tmp;

}


static int kvm_put_msrs(X86CPU *cpu, int level)

{

    CPUX86State *env = &cpu->env;

    int i;

    int ret;

    kvm_msr_buf_reset(cpu);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, env->sysenter_cs);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, env->sysenter_esp);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, env->sysenter_eip);

    kvm_msr_entry_add(cpu, MSR_PAT, env->pat);

    if (has_msr_star) {

        kvm_msr_entry_add(cpu, MSR_STAR, env->star);

    }

    if (has_msr_hsave_pa) {

        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, env->vm_hsave);

    }

    if (has_msr_tsc_aux) {

        kvm_msr_entry_add(cpu, MSR_TSC_AUX, env->tsc_aux);

    }

    if (has_msr_tsc_adjust) {

        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, env->tsc_adjust);

    }

    if (has_msr_misc_enable) {

        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE,

                          env->msr_ia32_misc_enable);

    }

    if (has_msr_smbase) {

        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, env->smbase);

    }

    if (has_msr_bndcfgs) {

        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, env->msr_bndcfgs);

    }

    if (has_msr_xss) {

        kvm_msr_entry_add(cpu, MSR_IA32_XSS, env->xss);

    }

#ifdef TARGET_X86_64

    if (lm_capable_kernel) {

        kvm_msr_entry_add(cpu, MSR_CSTAR, env->cstar);

        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, env->kernelgsbase);

        kvm_msr_entry_add(cpu, MSR_FMASK, env->fmask);

        kvm_msr_entry_add(cpu, MSR_LSTAR, env->lstar);

    }

#endif

    /*

     * The following MSRs have side effects on the guest or are too heavy

     * for normal writeback. Limit them to reset or full state updates.

     */

    if (level >= KVM_PUT_RESET_STATE) {

        kvm_msr_entry_add(cpu, MSR_IA32_TSC, env->tsc);

        kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, env->system_time_msr);

        kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, env->wall_clock_msr);

        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {

            kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, env->async_pf_en_msr);

        }

        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {

            kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, env->pv_eoi_en_msr);

        }

        if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {

            kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, env->steal_time_msr);

        }

        if (has_msr_architectural_pmu) {

            /* Stop the counter.  */

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);

            /* Set the counter values.  */

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

                kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i,

                                  env->msr_fixed_counters[i]);

            }

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

                kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i,

                                  env->msr_gp_counters[i]);

                kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i,

                                  env->msr_gp_evtsel[i]);

            }

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS,

                              env->msr_global_status);

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL,

                              env->msr_global_ovf_ctrl);

            /* Now start the PMU.  */

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL,

                              env->msr_fixed_ctr_ctrl);

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL,

                              env->msr_global_ctrl);

        }

        /*

         * Hyper-V partition-wide MSRs: to avoid clearing them on cpu hot-add,

         * only sync them to KVM on the first cpu

         */

        if (current_cpu == first_cpu) {

            if (has_msr_hv_hypercall) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID,

                                  env->msr_hv_guest_os_id);

                kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL,

                                  env->msr_hv_hypercall);

            }

            if (cpu->hyperv_time) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC,

                                  env->msr_hv_tsc);

            }

        }

        if (cpu->hyperv_vapic) {

            kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE,

                              env->msr_hv_vapic);

        }

        if (has_msr_hv_crash) {

            int j;

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

                kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j,

                                  env->msr_hv_crash_params[j]);

            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_CTL, HV_CRASH_CTL_NOTIFY);

        }

        if (has_msr_hv_runtime) {

            kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, env->msr_hv_runtime);

        }

        if (cpu->hyperv_synic) {

            int j;

            kvm_msr_entry_add(cpu, HV_X64_MSR_SVERSION, HV_SYNIC_VERSION);

            kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL,

                              env->msr_hv_synic_control);

            kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP,

                              env->msr_hv_synic_evt_page);

            kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP,

                              env->msr_hv_synic_msg_page);

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_synic_sint); j++) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_SINT0 + j,

                                  env->msr_hv_synic_sint[j]);

            }

        }

        if (has_msr_hv_stimer) {

            int j;

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_config); j++) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_CONFIG + j * 2,

                                env->msr_hv_stimer_config[j]);

            }

            for (j = 0; j < ARRAY_SIZE(env->msr_hv_stimer_count); j++) {

                kvm_msr_entry_add(cpu, HV_X64_MSR_STIMER0_COUNT + j * 2,

                                env->msr_hv_stimer_count[j]);

            }

        }

        if (env->features[FEAT_1_EDX] & CPUID_MTRR) {

            uint64_t phys_mask = MAKE_64BIT_MASK(0, cpu->phys_bits);

            kvm_msr_entry_add(cpu, MSR_MTRRdefType, env->mtrr_deftype);

            kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, env->mtrr_fixed[0]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, env->mtrr_fixed[1]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, env->mtrr_fixed[2]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, env->mtrr_fixed[3]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, env->mtrr_fixed[4]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, env->mtrr_fixed[5]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, env->mtrr_fixed[6]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, env->mtrr_fixed[7]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, env->mtrr_fixed[8]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, env->mtrr_fixed[9]);

            kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, env->mtrr_fixed[10]);

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

                /* The CPU GPs if we write to a bit above the physical limit of

                 * the host CPU (and KVM emulates that)

                 */

                uint64_t mask = env->mtrr_var[i].mask;

                mask &= phys_mask;

                kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i),

                                  env->mtrr_var[i].base);

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

            }

        }

        /* Note: MSR_IA32_FEATURE_CONTROL is written separately, see

         *       kvm_put_msr_feature_control. */

    }

    if (env->mcg_cap) {

        int i;

        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, env->mcg_status);

        kvm_msr_entry_add(cpu, MSR_MCG_CTL, env->mcg_ctl);

        if (has_msr_mcg_ext_ctl) {

            kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, env->mcg_ext_ctl);

        }

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

            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, env->mce_banks[i]);

        }

    }

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

    if (ret < 0) {

        return ret;

    }

    if (ret < cpu->kvm_msr_buf->nmsrs) {

        struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];

        error_report("error: failed to set MSR 0x%" PRIx32 " to 0x%" PRIx64,

                     (uint32_t)e->index, (uint64_t)e->data);

    }

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

    return 0;

}


void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,

                 Error **errp)

{

    Error *local_err = NULL;

    assert(!atomic_read(&bs_top->in_flight));

    assert(!atomic_read(&bs_new->in_flight));

    bdrv_set_backing_hd(bs_new, bs_top, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    change_parent_backing_link(bs_top, bs_new);

    /* bs_new is now referenced by its new parents, we don't need the

     * additional reference any more. */

out:

    bdrv_unref(bs_new);

}


static abi_long do_sendto(int fd, abi_ulong msg, size_t len, int flags,

                          abi_ulong target_addr, socklen_t addrlen)

{

    void *addr;

    void *host_msg;

    abi_long ret;

    if (addrlen < 0 || addrlen > MAX_SOCK_ADDR)

        return -TARGET_EINVAL;

    host_msg = lock_user(VERIFY_READ, msg, len, 1);

    if (!host_msg)

        return -TARGET_EFAULT;

    if (target_addr) {

        addr = alloca(addrlen);

        target_to_host_sockaddr(addr, target_addr, addrlen);

        ret = get_errno(sendto(fd, host_msg, len, flags, addr, addrlen));

    } else {

        ret = get_errno(send(fd, host_msg, len, flags));

    }

    unlock_user(host_msg, msg, 0);

    return ret;

}


void qxl_render_resize(PCIQXLDevice *qxl)

{

    QXLSurfaceCreate *sc = &qxl->guest_primary.surface;

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

    qxl->guest_primary.resized++;

    switch (sc->format) {

    case SPICE_SURFACE_FMT_16_555:

        qxl->guest_primary.bytes_pp = 2;

        qxl->guest_primary.bits_pp = 15;

        break;

    case SPICE_SURFACE_FMT_16_565:

        qxl->guest_primary.bytes_pp = 2;

        qxl->guest_primary.bits_pp = 16;

        break;

    case SPICE_SURFACE_FMT_32_xRGB:

    case SPICE_SURFACE_FMT_32_ARGB:

        qxl->guest_primary.bytes_pp = 4;

        qxl->guest_primary.bits_pp = 32;

        break;

    default:

        fprintf(stderr, "%s: unhandled format: %x\n", __FUNCTION__,

                qxl->guest_primary.surface.format);

        qxl->guest_primary.bytes_pp = 4;

        qxl->guest_primary.bits_pp = 32;

        break;

    }

}


static av_cold int a64multi_init_encoder(AVCodecContext *avctx)

{

    A64Context *c = avctx->priv_data;

    int a;

    av_lfg_init(&c->randctx, 1);

    if (avctx->global_quality < 1) {

        c->mc_lifetime = 4;

    } else {

        c->mc_lifetime = avctx->global_quality /= FF_QP2LAMBDA;

    }

    av_log(avctx, AV_LOG_INFO, "charset lifetime set to %d frame(s)\n", c->mc_lifetime);

    /* precalc luma values for later use */

    for (a = 0; a < 5; a++) {

        c->mc_luma_vals[a]=a64_palette[mc_colors[a]][0] * 0.30 +

                           a64_palette[mc_colors[a]][1] * 0.59 +

                           a64_palette[mc_colors[a]][2] * 0.11;

    }

    c->mc_frame_counter = 0;

    c->mc_use_5col      = avctx->codec->id == CODEC_ID_A64_MULTI5;

    c->mc_meta_charset  = av_malloc (32000 * c->mc_lifetime * sizeof(int));

    c->mc_best_cb       = av_malloc (CHARSET_CHARS * 32 * sizeof(int));

    c->mc_charmap       = av_mallocz(1000 * c->mc_lifetime * sizeof(int));

    c->mc_colram        = av_mallocz(CHARSET_CHARS * sizeof(uint8_t));

    c->mc_charset       = av_malloc (0x800 * (INTERLACED+1) * sizeof(uint8_t));

    /* set up extradata */

    avctx->extradata      = av_mallocz(8 * 4 + FF_INPUT_BUFFER_PADDING_SIZE);

    avctx->extradata_size = 8 * 4;

    AV_WB32(avctx->extradata, c->mc_lifetime);

    AV_WB32(avctx->extradata+16, INTERLACED);

    avcodec_get_frame_defaults(&c->picture);

    avctx->coded_frame            = &c->picture;

    avctx->coded_frame->pict_type = FF_I_TYPE;

    avctx->coded_frame->key_frame = 1;

    if (!avctx->codec_tag)

         avctx->codec_tag = AV_RL32("a64m");

    return 0;

}


static bool insn_crosses_page(CPUARMState *env, DisasContext *s)

{

    /* Return true if the insn at dc->pc might cross a page boundary.

     * (False positives are OK, false negatives are not.)

     */

    uint16_t insn;

    if ((s->pc & 3) == 0) {

        /* At a 4-aligned address we can't be crossing a page */

        return false;

    }

    /* This must be a Thumb insn */

    insn = arm_lduw_code(env, s->pc, s->sctlr_b);

    if ((insn >> 11) >= 0x1d) {

        /* Top five bits 0b11101 / 0b11110 / 0b11111 : this is the

         * First half of a 32-bit Thumb insn. Thumb-1 cores might

         * end up actually treating this as two 16-bit insns (see the

         * code at the start of disas_thumb2_insn()) but we don't bother

         * to check for that as it is unlikely, and false positives here

         * are harmless.

         */

        return true;

    }

    /* Definitely a 16-bit insn, can't be crossing a page. */

    return false;

}


static int vmdk_is_cid_valid(BlockDriverState *bs)

{

#ifdef CHECK_CID

    BDRVVmdkState *s = bs->opaque;

    BlockDriverState *p_bs = bs->backing_hd;

    uint32_t cur_pcid;

    if (p_bs) {

        cur_pcid = vmdk_read_cid(p_bs, 0);

        if (s->parent_cid != cur_pcid) {

            /* CID not valid */

            return 0;

        }

    }

#endif

    /* CID valid */

    return 1;

}


static uint32_t slavio_timer_mem_readl(void *opaque, target_phys_addr_t addr)

{

    SLAVIO_TIMERState *s = opaque;

    uint32_t saddr, ret;

    saddr = (addr & TIMER_MAXADDR) >> 2;

    switch (saddr) {

    case 0:

        // read limit (system counter mode) or read most signifying

        // part of counter (user mode)

        if (slavio_timer_is_user(s)) {

            // read user timer MSW

            slavio_timer_get_out(s);

            ret = s->counthigh;

        } else {

            // read limit

            // clear irq

            qemu_irq_lower(s->irq);

            s->reached = 0;

            ret = s->limit & 0x7fffffff;

        }

        break;

    case 1:

        // read counter and reached bit (system mode) or read lsbits

        // of counter (user mode)

        slavio_timer_get_out(s);

        if (slavio_timer_is_user(s)) // read user timer LSW

            ret = s->count & 0xffffffe00;

        else // read limit

            ret = (s->count & 0x7ffffe00) | s->reached;

        break;

    case 3:

        // only available in processor counter/timer

        // read start/stop status

        ret = s->running;

        break;

    case 4:

        // only available in system counter

        // read user/system mode

        ret = s->slave_mode;

        break;

    default:

        DPRINTF("invalid read address " TARGET_FMT_plx "\n", addr);

        ret = 0;

        break;

    }

    DPRINTF("read " TARGET_FMT_plx " = %08x\n", addr, ret);

    return ret;

}


void qemu_system_suspend_request(void)

{

    if (is_suspended) {

        return;

    }

    suspend_requested = 1;

    cpu_stop_current();

    qemu_notify_event();

}


static void ssh_parse_filename(const char *filename, QDict *options,

                               Error **errp)

{

    if (qdict_haskey(options, "user") ||

        qdict_haskey(options, "host") ||

        qdict_haskey(options, "port") ||

        qdict_haskey(options, "path") ||

        qdict_haskey(options, "host_key_check")) {

        error_setg(errp, "user, host, port, path, host_key_check cannot be used at the same time as a file option");

        return;

    }

    parse_uri(filename, options, errp);

}


static int webm_dash_manifest_write_header(AVFormatContext *s)

{

    int i;

    double start = 0.0;

    WebMDashMuxContext *w = s->priv_data;

    parse_adaptation_sets(s);

    write_header(s);

    avio_printf(s->pb, "<Period id=\"0\"");

    avio_printf(s->pb, " start=\"PT%gS\"", start);

    if (!w->is_live) {

        avio_printf(s->pb, " duration=\"PT%gS\"", get_duration(s));

    }

    avio_printf(s->pb, " >\n");

    for (i = 0; i < w->nb_as; i++) {

        if (write_adaptation_set(s, i) < 0) return -1;

    }

    avio_printf(s->pb, "</Period>\n");

    write_footer(s);

    return 0;

}


static void do_acl_show(Monitor *mon, const QDict *qdict)

{

    const char *aclname = qdict_get_str(qdict, "aclname");

    qemu_acl *acl = find_acl(mon, aclname);

    qemu_acl_entry *entry;

    int i = 0;

    if (acl) {

        monitor_printf(mon, "policy: %s\n",

                       acl->defaultDeny ? "deny" : "allow");

        TAILQ_FOREACH(entry, &acl->entries, next) {

            i++;

            monitor_printf(mon, "%d: %s %s\n", i,

                           entry->deny ? "deny" : "allow", entry->match);

        }

    }

}


MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, target_phys_addr_t index)

{

    PhysPageEntry lp = d->phys_map;

    PhysPageEntry *p;

    int i;

    uint16_t s_index = phys_section_unassigned;

    for (i = P_L2_LEVELS - 1; i >= 0 && !lp.is_leaf; i--) {

        if (lp.ptr == PHYS_MAP_NODE_NIL) {

            goto not_found;

        }

        p = phys_map_nodes[lp.ptr];

        lp = p[(index >> (i * L2_BITS)) & (L2_SIZE - 1)];

    }

    s_index = lp.ptr;

not_found:

    return &phys_sections[s_index];

}


int drive_get_max_bus(BlockInterfaceType type)

{

    int max_bus;

    DriveInfo *dinfo;

    max_bus = -1;

    TAILQ_FOREACH(dinfo, &drives, next) {

        if(dinfo->type == type &&

           dinfo->bus > max_bus)

            max_bus = dinfo->bus;

    }

    return max_bus;

}


PCIBus *pci_find_bus(PCIBus *bus, int bus_num)

{

    PCIBus *sec;

    if (!bus)

        return NULL;

    if (pci_bus_num(bus) == bus_num) {

        return bus;

    }

    /* try child bus */

    QLIST_FOREACH(sec, &bus->child, sibling) {

        if (!bus->parent_dev /* pci host bridge */

            || (pci_bus_num(sec) <= bus_num &&

                bus->parent_dev->config[PCI_SUBORDINATE_BUS])) {

            return pci_find_bus(sec, bus_num);

        }

    }

    return NULL;

}


ser_write(void *opaque, target_phys_addr_t addr,

          uint64_t val64, unsigned int size)

{

    struct etrax_serial *s = opaque;

    uint32_t value = val64;

    unsigned char ch = val64;

    D(CPUCRISState *env = s->env);

    D(qemu_log("%s " TARGET_FMT_plx "=%x\n",  __func__, addr, value));

    addr >>= 2;

    switch (addr)

    {

        case RW_DOUT:

            qemu_chr_fe_write(s->chr, &ch, 1);

            s->regs[R_INTR] |= 3;

            s->pending_tx = 1;

            s->regs[addr] = value;

            break;

        case RW_ACK_INTR:

            if (s->pending_tx) {

                value &= ~1;

                s->pending_tx = 0;

                D(qemu_log("fixedup value=%x r_intr=%x\n",

                           value, s->regs[R_INTR]));

            }

            s->regs[addr] = value;

            s->regs[R_INTR] &= ~value;

            D(printf("r_intr=%x\n", s->regs[R_INTR]));

            break;

        default:

            s->regs[addr] = value;

            break;

    }

    ser_update_irq(s);

}


static void gic_dist_writeb(void *opaque, target_phys_addr_t offset,

                            uint32_t value)

{

    GICState *s = (GICState *)opaque;

    int irq;

    int i;

    int cpu;

    cpu = gic_get_current_cpu(s);

    if (offset < 0x100) {

        if (offset == 0) {

            s->enabled = (value & 1);

            DPRINTF("Distribution %sabled\n", s->enabled ? "En" : "Dis");

        } else if (offset < 4) {

            /* ignored.  */

        } else if (offset >= 0x80) {

            /* Interrupt Security Registers, RAZ/WI */

        } else {

            goto bad_reg;

        }

    } else if (offset < 0x180) {

        /* Interrupt Set Enable.  */

        irq = (offset - 0x100) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < 16)

          value = 0xff;

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

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

                int mask = (irq < GIC_INTERNAL) ? (1 << cpu) : GIC_TARGET(irq);

                int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;

                if (!GIC_TEST_ENABLED(irq + i, cm)) {

                    DPRINTF("Enabled IRQ %d\n", irq + i);

                }

                GIC_SET_ENABLED(irq + i, cm);

                /* If a raised level triggered IRQ enabled then mark

                   is as pending.  */

                if (GIC_TEST_LEVEL(irq + i, mask)

                        && !GIC_TEST_TRIGGER(irq + i)) {

                    DPRINTF("Set %d pending mask %x\n", irq + i, mask);

                    GIC_SET_PENDING(irq + i, mask);

                }

            }

        }

    } else if (offset < 0x200) {

        /* Interrupt Clear Enable.  */

        irq = (offset - 0x180) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < 16)

          value = 0;

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

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

                int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;

                if (GIC_TEST_ENABLED(irq + i, cm)) {

                    DPRINTF("Disabled IRQ %d\n", irq + i);

                }

                GIC_CLEAR_ENABLED(irq + i, cm);

            }

        }

    } else if (offset < 0x280) {

        /* Interrupt Set Pending.  */

        irq = (offset - 0x200) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < 16)

          irq = 0;

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

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

                GIC_SET_PENDING(irq + i, GIC_TARGET(irq));

            }

        }

    } else if (offset < 0x300) {

        /* Interrupt Clear Pending.  */

        irq = (offset - 0x280) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

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

            /* ??? This currently clears the pending bit for all CPUs, even

               for per-CPU interrupts.  It's unclear whether this is the

               corect behavior.  */

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

                GIC_CLEAR_PENDING(irq + i, ALL_CPU_MASK);

            }

        }

    } else if (offset < 0x400) {

        /* Interrupt Active.  */

        goto bad_reg;

    } else if (offset < 0x800) {

        /* Interrupt Priority.  */

        irq = (offset - 0x400) + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_INTERNAL) {

            s->priority1[irq][cpu] = value;

        } else {

            s->priority2[irq - GIC_INTERNAL] = value;

        }

    } else if (offset < 0xc00) {

        /* Interrupt CPU Target. RAZ/WI on uniprocessor GICs, with the

         * annoying exception of the 11MPCore's GIC.

         */

        if (s->num_cpu != 1 || s->revision == REV_11MPCORE) {

            irq = (offset - 0x800) + GIC_BASE_IRQ;

            if (irq >= s->num_irq) {

                goto bad_reg;

            }

            if (irq < 29) {

                value = 0;

            } else if (irq < GIC_INTERNAL) {

                value = ALL_CPU_MASK;

            }

            s->irq_target[irq] = value & ALL_CPU_MASK;

        }

    } else if (offset < 0xf00) {

        /* Interrupt Configuration.  */

        irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_INTERNAL)

            value |= 0xaa;

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

            if (value & (1 << (i * 2))) {

                GIC_SET_MODEL(irq + i);

            } else {

                GIC_CLEAR_MODEL(irq + i);

            }

            if (value & (2 << (i * 2))) {

                GIC_SET_TRIGGER(irq + i);

            } else {

                GIC_CLEAR_TRIGGER(irq + i);

            }

        }

    } else {

        /* 0xf00 is only handled for 32-bit writes.  */

        goto bad_reg;

    }

    gic_update(s);

    return;

bad_reg:

    hw_error("gic_dist_writeb: Bad offset %x\n", (int)offset);

}


static void virtio_blk_handle_request(VirtIOBlockReq *req,

    MultiReqBuffer *mrb)

{

    uint32_t type;

    struct iovec *iov = req->elem->out_sg;

    unsigned out_num = req->elem->out_num;

    if (req->elem->out_num < 1 || req->elem->in_num < 1) {

        error_report("virtio-blk missing headers");

        exit(1);

    }

    if (req->elem->out_sg[0].iov_len < sizeof(req->out) ||

        req->elem->in_sg[req->elem->in_num - 1].iov_len < sizeof(*req->in)) {

        error_report("virtio-blk header not in correct element");

        exit(1);

    }

    if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,

                            sizeof(req->out)) != sizeof(req->out))) {

        error_report("virtio-blk request outhdr too short");

        exit(1);

    }

    iov_discard_front(&iov, &out_num, sizeof(req->out));

    req->in = (void *)req->elem->in_sg[req->elem->in_num - 1].iov_base;

    type = ldl_p(&req->out.type);

    if (type & VIRTIO_BLK_T_FLUSH) {

        virtio_blk_handle_flush(req, mrb);

    } else if (type & VIRTIO_BLK_T_SCSI_CMD) {

        virtio_blk_handle_scsi(req);

    } else if (type & VIRTIO_BLK_T_GET_ID) {

        VirtIOBlock *s = req->dev;

        /*

         * NB: per existing s/n string convention the string is

         * terminated by '\0' only when shorter than buffer.

         */

        strncpy(req->elem->in_sg[0].iov_base,

                s->blk.serial ? s->blk.serial : "",

                MIN(req->elem->in_sg[0].iov_len, VIRTIO_BLK_ID_BYTES));

        virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);

        virtio_blk_free_request(req);

    } else if (type & VIRTIO_BLK_T_OUT) {

        qemu_iovec_init_external(&req->qiov, &req->elem->out_sg[1],

                                 req->elem->out_num - 1);

        virtio_blk_handle_write(req, mrb);

    } else if (type == VIRTIO_BLK_T_IN || type == VIRTIO_BLK_T_BARRIER) {

        /* VIRTIO_BLK_T_IN is 0, so we can't just & it. */

        qemu_iovec_init_external(&req->qiov, &req->elem->in_sg[0],

                                 req->elem->in_num - 1);

        virtio_blk_handle_read(req);

    } else {

        virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);

        virtio_blk_free_request(req);

    }

}


static void gen_addq_lo(DisasContext *s, TCGv val, int rlow)

{

    TCGv tmp;

    TCGv tmp2;

    /* Load value and extend to 64 bits.  */

    tmp = tcg_temp_new(TCG_TYPE_I64);

    tmp2 = load_reg(s, rlow);

    tcg_gen_extu_i32_i64(tmp, tmp2);

    dead_tmp(tmp2);

    tcg_gen_add_i64(val, val, tmp);

}


static int analyze_chunk(AVFormatContext *s, const uint8_t *chunk)
{
    TYDemuxContext *ty = s->priv_data;
    int num_recs, i;
    TyRecHdr *hdrs;
    int num_6e0, num_be0, num_9c0, num_3c0;
    /* skip if it's a Part header */
    if (AV_RB32(&chunk[0]) == TIVO_PES_FILEID)
        return 0;
    /* number of records in chunk (we ignore high order byte;
     * rarely are there > 256 chunks & we don't need that many anyway) */
    num_recs = chunk[0];
    if (num_recs < 5) {
        /* try again with the next chunk.  Sometimes there are dead ones */
        return 0;
    }
    chunk += 4;       /* skip past rec count & SEQ bytes */
    ff_dlog(s, "probe: chunk has %d recs\n", num_recs);
    hdrs = parse_chunk_headers(chunk, num_recs);
    if (!hdrs)
        return AVERROR(ENOMEM);
    /* scan headers.
     * 1. check video packets.  Presence of 0x6e0 means S1.
     *    No 6e0 but have be0 means S2.
     * 2. probe for audio 0x9c0 vs 0x3c0 (AC3 vs Mpeg)
     *    If AC-3, then we have DTivo.
     *    If MPEG, search for PTS offset.  This will determine SA vs. DTivo.
     */
    num_6e0 = num_be0 = num_9c0 = num_3c0 = 0;
    for (i = 0; i < num_recs; i++) {
        switch (hdrs[i].subrec_type << 8 | hdrs[i].rec_type) {
        case 0x6e0:
            num_6e0++;
        case 0xbe0:
            num_be0++;
        case 0x3c0:
            num_3c0++;
        case 0x9c0:
            num_9c0++;
        }
    }
    ff_dlog(s, "probe: chunk has %d 0x6e0 recs, %d 0xbe0 recs.\n",
            num_6e0, num_be0);
    /* set up our variables */
    if (num_6e0 > 0) {
        ff_dlog(s, "detected Series 1 Tivo\n");
        ty->tivo_series = TIVO_SERIES1;
        ty->pes_length = SERIES1_PES_LENGTH;
    } else if (num_be0 > 0) {
        ff_dlog(s, "detected Series 2 Tivo\n");
        ty->tivo_series = TIVO_SERIES2;
        ty->pes_length = SERIES2_PES_LENGTH;
    }
    if (num_9c0 > 0) {
        ff_dlog(s, "detected AC-3 Audio (DTivo)\n");
        ty->audio_type = TIVO_AUDIO_AC3;
        ty->tivo_type = TIVO_TYPE_DTIVO;
        ty->pts_offset = AC3_PTS_OFFSET;
        ty->pes_length = AC3_PES_LENGTH;
    } else if (num_3c0 > 0) {
        ty->audio_type = TIVO_AUDIO_MPEG;
        ff_dlog(s, "detected MPEG Audio\n");
    }
    /* if tivo_type still unknown, we can check PTS location
     * in MPEG packets to determine tivo_type */
    if (ty->tivo_type == TIVO_TYPE_UNKNOWN) {
        uint32_t data_offset = 16 * num_recs;
        for (i = 0; i < num_recs; i++) {
            if ((hdrs[i].subrec_type << 0x08 | hdrs[i].rec_type) == 0x3c0 && hdrs[i].rec_size > 15) {
                /* first make sure we're aligned */
                int pes_offset = find_es_header(ty_MPEGAudioPacket,
                        &chunk[data_offset], 5);
                if (pes_offset >= 0) {
                    /* pes found. on SA, PES has hdr data at offset 6, not PTS. */
                    if ((chunk[data_offset + 6 + pes_offset] & 0x80) == 0x80) {
                        /* S1SA or S2(any) Mpeg Audio (PES hdr, not a PTS start) */
                        if (ty->tivo_series == TIVO_SERIES1)
                            ff_dlog(s, "detected Stand-Alone Tivo\n");
                        ty->tivo_type = TIVO_TYPE_SA;
                        ty->pts_offset = SA_PTS_OFFSET;
                    } else {
                        if (ty->tivo_series == TIVO_SERIES1)
                            ff_dlog(s, "detected DirecTV Tivo\n");
                        ty->tivo_type = TIVO_TYPE_DTIVO;
                        ty->pts_offset = DTIVO_PTS_OFFSET;
                    }
                }
            }
            data_offset += hdrs[i].rec_size;
        }
    }
    av_free(hdrs);
    return 0;
}


static void nbd_close(BlockDriverState *bs)
{
    nbd_teardown_connection(bs);
}


static void vmxnet3_handle_command(VMXNET3State *s, uint64_t cmd)

{

    s->last_command = cmd;

    switch (cmd) {

    case VMXNET3_CMD_GET_PERM_MAC_HI:

        VMW_CBPRN("Set: Get upper part of permanent MAC");

        break;

    case VMXNET3_CMD_GET_PERM_MAC_LO:

        VMW_CBPRN("Set: Get lower part of permanent MAC");

        break;

    case VMXNET3_CMD_GET_STATS:

        VMW_CBPRN("Set: Get device statistics");

        vmxnet3_fill_stats(s);

        break;

    case VMXNET3_CMD_ACTIVATE_DEV:

        VMW_CBPRN("Set: Activating vmxnet3 device");

        vmxnet3_activate_device(s);

        break;

    case VMXNET3_CMD_UPDATE_RX_MODE:

        VMW_CBPRN("Set: Update rx mode");

        vmxnet3_update_rx_mode(s);

        break;

    case VMXNET3_CMD_UPDATE_VLAN_FILTERS:

        VMW_CBPRN("Set: Update VLAN filters");

        vmxnet3_update_vlan_filters(s);

        break;

    case VMXNET3_CMD_UPDATE_MAC_FILTERS:

        VMW_CBPRN("Set: Update MAC filters");

        vmxnet3_update_mcast_filters(s);

        break;

    case VMXNET3_CMD_UPDATE_FEATURE:

        VMW_CBPRN("Set: Update features");

        vmxnet3_update_features(s);

        break;

    case VMXNET3_CMD_UPDATE_PMCFG:

        VMW_CBPRN("Set: Update power management config");

        vmxnet3_update_pm_state(s);

        break;

    case VMXNET3_CMD_GET_LINK:

        VMW_CBPRN("Set: Get link");

        break;

    case VMXNET3_CMD_RESET_DEV:

        VMW_CBPRN("Set: Reset device");

        vmxnet3_reset(s);

        break;

    case VMXNET3_CMD_QUIESCE_DEV:

        VMW_CBPRN("Set: VMXNET3_CMD_QUIESCE_DEV - pause the device");

        vmxnet3_deactivate_device(s);

        break;

    case VMXNET3_CMD_GET_CONF_INTR:

        VMW_CBPRN("Set: VMXNET3_CMD_GET_CONF_INTR - interrupt configuration");

        break;

    case VMXNET3_CMD_GET_ADAPTIVE_RING_INFO:

        VMW_CBPRN("Set: VMXNET3_CMD_GET_ADAPTIVE_RING_INFO - "

                  "adaptive ring info flags");

        break;

    default:

        VMW_CBPRN("Received unknown command: %" PRIx64, cmd);

        break;

    }

}


static void kvm_s390_flic_realize(DeviceState *dev, Error **errp)

{

    KVMS390FLICState *flic_state = KVM_S390_FLIC(dev);

    struct kvm_create_device cd = {0};

    struct kvm_device_attr test_attr = {0};

    int ret;

    Error *errp_local = NULL;

    flic_state->fd = -1;

    if (!kvm_check_extension(kvm_state, KVM_CAP_DEVICE_CTRL)) {

        error_setg_errno(&errp_local, errno, "KVM is missing capability"

                         " KVM_CAP_DEVICE_CTRL");

        trace_flic_no_device_api(errno);

    cd.type = KVM_DEV_TYPE_FLIC;

    ret = kvm_vm_ioctl(kvm_state, KVM_CREATE_DEVICE, &cd);

    if (ret < 0) {

        error_setg_errno(&errp_local, errno, "Creating the KVM device failed");

        trace_flic_create_device(errno);

    flic_state->fd = cd.fd;

    /* Check clear_io_irq support */

    test_attr.group = KVM_DEV_FLIC_CLEAR_IO_IRQ;

    flic_state->clear_io_supported = !ioctl(flic_state->fd,

                                            KVM_HAS_DEVICE_ATTR, test_attr);

    return;

fail:

    error_propagate(errp, errp_local);


static void test_visitor_out_empty(TestOutputVisitorData *data,

                                   const void *unused)

{

    QObject *arg;

    arg = qmp_output_get_qobject(data->qov);

    g_assert(qobject_type(arg) == QTYPE_QNULL);

    qobject_decref(arg);

}


uint32_t gic_acknowledge_irq(GICState *s, int cpu, MemTxAttrs attrs)

{

    int ret, irq, src;

    int cm = 1 << cpu;

    /* gic_get_current_pending_irq() will return 1022 or 1023 appropriately

     * for the case where this GIC supports grouping and the pending interrupt

     * is in the wrong group.

     */

    irq = gic_get_current_pending_irq(s, cpu, attrs);

    if (irq >= GIC_MAXIRQ) {

        DPRINTF("ACK, no pending interrupt or it is hidden: %d\n", irq);

        return irq;

    }

    if (GIC_GET_PRIORITY(irq, cpu) >= s->running_priority[cpu]) {

        DPRINTF("ACK, pending interrupt (%d) has insufficient priority\n", irq);

        return 1023;

    }

    if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

        /* Clear pending flags for both level and edge triggered interrupts.

         * Level triggered IRQs will be reasserted once they become inactive.

         */

        GIC_CLEAR_PENDING(irq, GIC_TEST_MODEL(irq) ? ALL_CPU_MASK : cm);

        ret = irq;

    } else {

        if (irq < GIC_NR_SGIS) {

            /* Lookup the source CPU for the SGI and clear this in the

             * sgi_pending map.  Return the src and clear the overall pending

             * state on this CPU if the SGI is not pending from any CPUs.

             */

            assert(s->sgi_pending[irq][cpu] != 0);

            src = ctz32(s->sgi_pending[irq][cpu]);

            s->sgi_pending[irq][cpu] &= ~(1 << src);

            if (s->sgi_pending[irq][cpu] == 0) {

                GIC_CLEAR_PENDING(irq, GIC_TEST_MODEL(irq) ? ALL_CPU_MASK : cm);

            }

            ret = irq | ((src & 0x7) << 10);

        } else {

            /* Clear pending state for both level and edge triggered

             * interrupts. (level triggered interrupts with an active line

             * remain pending, see gic_test_pending)

             */

            GIC_CLEAR_PENDING(irq, GIC_TEST_MODEL(irq) ? ALL_CPU_MASK : cm);

            ret = irq;

        }

    }

    gic_activate_irq(s, cpu, irq);

    gic_update(s);

    DPRINTF("ACK %d\n", irq);

    return ret;

}


static void virtio_net_receive(void *opaque, const uint8_t *buf, size_t size)

{

    VirtIONet *n = opaque;

    struct virtio_net_hdr_mrg_rxbuf *mhdr = NULL;

    size_t hdr_len, offset, i;

    if (!do_virtio_net_can_receive(n, size))

        return;

    if (!receive_filter(n, buf, size))

        return;

    /* hdr_len refers to the header we supply to the guest */

    hdr_len = n->mergeable_rx_bufs ?

        sizeof(struct virtio_net_hdr_mrg_rxbuf) : sizeof(struct virtio_net_hdr);

    offset = i = 0;

    while (offset < size) {

        VirtQueueElement elem;

        int len, total;

        struct iovec sg[VIRTQUEUE_MAX_SIZE];

        len = total = 0;

        if ((i != 0 && !n->mergeable_rx_bufs) ||

            virtqueue_pop(n->rx_vq, &elem) == 0) {

            if (i == 0)

                return;

            fprintf(stderr, "virtio-net truncating packet\n");

            exit(1);

        }

        if (elem.in_num < 1) {

            fprintf(stderr, "virtio-net receive queue contains no in buffers\n");

            exit(1);

        }

        if (!n->mergeable_rx_bufs && elem.in_sg[0].iov_len != hdr_len) {

            fprintf(stderr, "virtio-net header not in first element\n");

            exit(1);

        }

        memcpy(&sg, &elem.in_sg[0], sizeof(sg[0]) * elem.in_num);

        if (i == 0) {

            if (n->mergeable_rx_bufs)

                mhdr = (struct virtio_net_hdr_mrg_rxbuf *)sg[0].iov_base;

            offset += receive_header(n, sg, elem.in_num,

                                     buf + offset, size - offset, hdr_len);

            total += hdr_len;

        }

        /* copy in packet.  ugh */

        len = iov_fill(sg, elem.in_num,

                       buf + offset, size - offset);

        total += len;

        /* signal other side */

        virtqueue_fill(n->rx_vq, &elem, total, i++);

        offset += len;

    }

    if (mhdr)

        mhdr->num_buffers = i;

    virtqueue_flush(n->rx_vq, i);

    virtio_notify(&n->vdev, n->rx_vq);

}


static inline int writer_print_string(WriterContext *wctx,

                                      const char *key, const char *val, int opt)

{

    const struct section *section = wctx->section[wctx->level];

    int ret = 0;

    if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))

        return 0;

    if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {

        wctx->writer->print_string(wctx, key, val);

        wctx->nb_item[wctx->level]++;

    }

    return ret;

}