MigrationState *migrate_init(const MigrationParams *params)

{

    MigrationState *s = migrate_get_current();

    int64_t bandwidth_limit = s->bandwidth_limit;

    bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];

    int64_t xbzrle_cache_size = s->xbzrle_cache_size;

    int compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];

    int compress_thread_count =

            s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];

    int decompress_thread_count =

            s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];

    int x_cpu_throttle_initial =

            s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];

    int x_cpu_throttle_increment =

            s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];

    memcpy(enabled_capabilities, s->enabled_capabilities,

           sizeof(enabled_capabilities));

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

    s->params = *params;

    memcpy(s->enabled_capabilities, enabled_capabilities,

           sizeof(enabled_capabilities));

    s->xbzrle_cache_size = xbzrle_cache_size;

    s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;

    s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =

               compress_thread_count;

    s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =

               decompress_thread_count;

    s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =

                x_cpu_throttle_initial;

    s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =

                x_cpu_throttle_increment;

    s->bandwidth_limit = bandwidth_limit;

    migrate_set_state(s, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);

    QSIMPLEQ_INIT(&s->src_page_requests);

    s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);

    return s;

}


static void vc1_put_ver_16b_shift2_mmx(int16_t *dst,

                                       const uint8_t *src, x86_reg stride,

                                       int rnd, int64_t shift)

{

    __asm__ volatile(

        "mov       $3, %%"REG_c"           \n\t"

        LOAD_ROUNDER_MMX("%5")

        "movq      "MANGLE(ff_pw_9)", %%mm6 \n\t"

        "1:                                \n\t"

        "movd      (%0), %%mm2             \n\t"

        "add       %2, %0                  \n\t"

        "movd      (%0), %%mm3             \n\t"

        "punpcklbw %%mm0, %%mm2            \n\t"

        "punpcklbw %%mm0, %%mm3            \n\t"

        SHIFT2_LINE(  0, 1, 2, 3, 4)

        SHIFT2_LINE( 24, 2, 3, 4, 1)

        SHIFT2_LINE( 48, 3, 4, 1, 2)

        SHIFT2_LINE( 72, 4, 1, 2, 3)

        SHIFT2_LINE( 96, 1, 2, 3, 4)

        SHIFT2_LINE(120, 2, 3, 4, 1)

        SHIFT2_LINE(144, 3, 4, 1, 2)

        SHIFT2_LINE(168, 4, 1, 2, 3)

        "sub       %6, %0                  \n\t"

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

        "dec       %%"REG_c"               \n\t"

        "jnz 1b                            \n\t"

        : "+r"(src), "+r"(dst)

        : "r"(stride), "r"(-2*stride),

          "m"(shift), "m"(rnd), "r"(9*stride-4)

          NAMED_CONSTRAINTS_ADD(ff_pw_9)

        : "%"REG_c, "memory"

    );

}


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

{

    int64_t end = avio_tell(pb) + atom.size;

    uint8_t *key = NULL, *val = NULL, *mean = NULL;

    int i;

    AVStream *st;

    MOVStreamContext *sc;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    sc = st->priv_data;

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

        uint8_t **p;

        uint32_t len, tag;

        int ret;

        if (end - avio_tell(pb) <= 12)

            break;

        len = avio_rb32(pb);

        tag = avio_rl32(pb);

        avio_skip(pb, 4); // flags

        if (len < 12 || len - 12 > end - avio_tell(pb))

            break;

        len -= 12;

        if (tag == MKTAG('m', 'e', 'a', 'n'))

            p = &mean;

        else if (tag == MKTAG('n', 'a', 'm', 'e'))

            p = &key;

        else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {

            avio_skip(pb, 4);

            len -= 4;

            p = &val;

        } else

            break;

        *p = av_malloc(len + 1);

        if (!*p)

            break;

        ret = ffio_read_size(pb, *p, len);

        if (ret < 0) {

            av_freep(p);

            return ret;

        }

        (*p)[len] = 0;

    }

    if (mean && key && val) {

        if (strcmp(key, "iTunSMPB") == 0) {

            int priming, remainder, samples;

            if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){

                if(priming>0 && priming<16384)

                    sc->start_pad = priming;

            }

        }

        if (strcmp(key, "cdec") != 0) {

            av_dict_set(&c->fc->metadata, key, val,

                        AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);

            key = val = NULL;

        }

    } else {

        av_log(c->fc, AV_LOG_VERBOSE,

               "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);

    }

    avio_seek(pb, end, SEEK_SET);

    av_freep(&key);

    av_freep(&val);

    av_freep(&mean);

    return 0;

}


static AVBufferRef *dxva2_pool_alloc(void *opaque, int size)

{

    AVHWFramesContext      *ctx = (AVHWFramesContext*)opaque;

    DXVA2FramesContext       *s = ctx->internal->priv;

    AVDXVA2FramesContext *hwctx = ctx->hwctx;

    if (s->nb_surfaces_used < hwctx->nb_surfaces) {

        s->nb_surfaces_used++;

        return av_buffer_create((uint8_t*)s->surfaces_internal[s->nb_surfaces_used - 1],

                                sizeof(*hwctx->surfaces), NULL, 0, 0);

    }

    return NULL;

}


void put_string(PutBitContext * pbc, char *s)

{

    while(*s){

        put_bits(pbc, 8, *s);

        s++;

    }

    put_bits(pbc, 8, 0);

}


static void mp_decode_frame_helper(MotionPixelsContext *mp, GetBitContext *gb)
{
    YuvPixel p;
    int y, y0;
    for (y = 0; y < mp->avctx->height; ++y) {
        if (mp->changes_map[y * mp->avctx->width] != 0) {
            memset(mp->gradient_scale, 1, sizeof(mp->gradient_scale));
            p = mp_get_yuv_from_rgb(mp, 0, y);
        } else {
            p.y += mp_gradient(mp, 0, mp_get_vlc(mp, gb));
            p.y = av_clip(p.y, 0, 31);
            if ((y & 3) == 0) {
                p.v += mp_gradient(mp, 1, mp_get_vlc(mp, gb));
                p.v = av_clip(p.v, -32, 31);
                p.u += mp_gradient(mp, 2, mp_get_vlc(mp, gb));
                p.u = av_clip(p.u, -32, 31);
            }
            mp->vpt[y] = p;
            mp_set_rgb_from_yuv(mp, 0, y, &p);
        }
    }
    for (y0 = 0; y0 < 2; ++y0)
        for (y = y0; y < mp->avctx->height; y += 2)
            mp_decode_line(mp, gb, y);
}


static int find_start_code(const uint8_t **pbuf_ptr, const uint8_t *buf_end)

{

    const uint8_t *buf_ptr= *pbuf_ptr;

    buf_ptr++; //gurantees that -1 is within the array

    buf_end -= 2; // gurantees that +2 is within the array

    while (buf_ptr < buf_end) {

        if(*buf_ptr==0){

            while(buf_ptr < buf_end && buf_ptr[1]==0)

                buf_ptr++;

            if(buf_ptr[-1] == 0 && buf_ptr[1] == 1){

                *pbuf_ptr = buf_ptr+3;

                return buf_ptr[2] + 0x100;

            }

        }

        buf_ptr += 2;

    }

    buf_end += 2; //undo the hack above

    *pbuf_ptr = buf_end;

    return -1;

}


static void pc_q35_2_4_machine_options(MachineClass *m)

{

    PCMachineClass *pcmc = PC_MACHINE_CLASS(m);

    pc_q35_2_5_machine_options(m);

    m->alias = NULL;

    pcmc->broken_reserved_end = true;

    pcmc->inter_dimm_gap = false;

    SET_MACHINE_COMPAT(m, PC_COMPAT_2_4);

}


av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)

{

    int ret;

    if ((ret = nvenc_load_libraries(avctx)) < 0)

        return ret;

    if ((ret = nvenc_setup_device(avctx)) < 0)

        return ret;

    if ((ret = nvenc_setup_encoder(avctx)) < 0)

        return ret;

    if ((ret = nvenc_setup_surfaces(avctx)) < 0)

        return ret;

    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {

        if ((ret = nvenc_setup_extradata(avctx)) < 0)

            return ret;

    }

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    return 0;

}


static int qemu_rdma_exchange_get_response(RDMAContext *rdma,

                RDMAControlHeader *head, int expecting, int idx)

{

    uint32_t byte_len;

    int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx,

                                       &byte_len);

    if (ret < 0) {

        fprintf(stderr, "rdma migration: recv polling control error!\n");

        return ret;

    }

    network_to_control((void *) rdma->wr_data[idx].control);

    memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader));

    DDDPRINTF("CONTROL: %s receiving...\n", control_desc[expecting]);

    if (expecting == RDMA_CONTROL_NONE) {

        DDDPRINTF("Surprise: got %s (%d)\n",

                  control_desc[head->type], head->type);

    } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) {

        fprintf(stderr, "Was expecting a %s (%d) control message"

                ", but got: %s (%d), length: %d\n",

                control_desc[expecting], expecting,

                control_desc[head->type], head->type, head->len);

        return -EIO;

    }

    if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) {

        fprintf(stderr, "too long length: %d\n", head->len);

        return -EINVAL;

    }

    if (sizeof(*head) + head->len != byte_len) {

        fprintf(stderr, "Malformed length: %d byte_len %d\n",

                head->len, byte_len);

        return -EINVAL;

    }

    return 0;

}


static inline void kqemu_load_seg(struct kqemu_segment_cache *ksc,

                                  const SegmentCache *sc)

{

    ksc->selector = sc->selector;

    ksc->flags = sc->flags;

    ksc->limit = sc->limit;

    ksc->base = sc->base;

}


int avcodec_decode_audio2(AVCodecContext *avctx, int16_t *samples,

                         int *frame_size_ptr,

                         uint8_t *buf, int buf_size)

{

    int ret;

    //FIXME remove the check below _after_ ensuring that all audio check that the available space is enough

    if(*frame_size_ptr < AVCODEC_MAX_AUDIO_FRAME_SIZE){

        av_log(avctx, AV_LOG_ERROR, "buffer smaller than AVCODEC_MAX_AUDIO_FRAME_SIZE\n");

        return -1;

    }

    if(*frame_size_ptr < FF_MIN_BUFFER_SIZE ||

       *frame_size_ptr < avctx->channels * avctx->frame_size * sizeof(int16_t) ||

       *frame_size_ptr < buf_size){

        av_log(avctx, AV_LOG_ERROR, "buffer %d too small\n", *frame_size_ptr);

        return -1;

    }

    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || buf_size){

        ret = avctx->codec->decode(avctx, samples, frame_size_ptr,

                                buf, buf_size);

        avctx->frame_number++;

    }else{

        ret= 0;

        *frame_size_ptr=0;

    }

    return ret;

}


static int64_t ffm_read_write_index(int fd)

{

    uint8_t buf[8];

    lseek(fd, 8, SEEK_SET);

    if (read(fd, buf, 8) != 8)

        return AVERROR(EIO);

    return AV_RB64(buf);

}


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

{

    VirtIONet *n = VIRTIO_NET(vdev);

    struct virtio_net_ctrl_hdr ctrl;

    virtio_net_ctrl_ack status = VIRTIO_NET_ERR;

    VirtQueueElement elem;

    size_t s;

    struct iovec *iov, *iov2;

    unsigned int iov_cnt;

    while (virtqueue_pop(vq, &elem)) {

        if (iov_size(elem.in_sg, elem.in_num) < sizeof(status) ||

            iov_size(elem.out_sg, elem.out_num) < sizeof(ctrl)) {

            error_report("virtio-net ctrl missing headers");

            exit(1);

        }

        iov_cnt = elem.out_num;

        iov2 = iov = g_memdup(elem.out_sg, sizeof(struct iovec) * elem.out_num);

        s = iov_to_buf(iov, iov_cnt, 0, &ctrl, sizeof(ctrl));

        iov_discard_front(&iov, &iov_cnt, sizeof(ctrl));

        if (s != sizeof(ctrl)) {

            status = VIRTIO_NET_ERR;

        } else if (ctrl.class == VIRTIO_NET_CTRL_RX) {

            status = virtio_net_handle_rx_mode(n, ctrl.cmd, iov, iov_cnt);

        } else if (ctrl.class == VIRTIO_NET_CTRL_MAC) {

            status = virtio_net_handle_mac(n, ctrl.cmd, iov, iov_cnt);

        } else if (ctrl.class == VIRTIO_NET_CTRL_VLAN) {

            status = virtio_net_handle_vlan_table(n, ctrl.cmd, iov, iov_cnt);

        } else if (ctrl.class == VIRTIO_NET_CTRL_ANNOUNCE) {

            status = virtio_net_handle_announce(n, ctrl.cmd, iov, iov_cnt);

        } else if (ctrl.class == VIRTIO_NET_CTRL_MQ) {

            status = virtio_net_handle_mq(n, ctrl.cmd, iov, iov_cnt);

        } else if (ctrl.class == VIRTIO_NET_CTRL_GUEST_OFFLOADS) {

            status = virtio_net_handle_offloads(n, ctrl.cmd, iov, iov_cnt);

        }

        s = iov_from_buf(elem.in_sg, elem.in_num, 0, &status, sizeof(status));

        assert(s == sizeof(status));

        virtqueue_push(vq, &elem, sizeof(status));

        virtio_notify(vdev, vq);

        g_free(iov2);

    }

}


void cpu_exec_realizefn(CPUState *cpu, Error **errp)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    cpu_list_add(cpu);

    if (tcg_enabled() && !cc->tcg_initialized) {

        cc->tcg_initialized = true;

        cc->tcg_initialize();

    }

#ifndef CONFIG_USER_ONLY

    if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {

        vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);

    }

    if (cc->vmsd != NULL) {

        vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);

    }

#endif

}


float32 helper_fitos(CPUSPARCState *env, int32_t src)

{

    /* Inexact error possible converting int to float.  */

    float32 ret;

    clear_float_exceptions(env);

    ret = int32_to_float32(src, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


static void test_wait_event_notifier(void)

{

    EventNotifierTestData data = { .n = 0, .active = 1 };

    event_notifier_init(&data.e, false);

    aio_set_event_notifier(ctx, &data.e, event_ready_cb);

    g_assert(!aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 0);

    g_assert_cmpint(data.active, ==, 1);

    event_notifier_set(&data.e);

    g_assert(aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.active, ==, 0);

    g_assert(!aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.active, ==, 0);

    aio_set_event_notifier(ctx, &data.e, NULL);

    g_assert(!aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 1);

    event_notifier_cleanup(&data.e);

}


static void bswap_shdr(struct elf_shdr *shdr)

{

    bswap32s(&shdr->sh_name);

    bswap32s(&shdr->sh_type);

    bswaptls(&shdr->sh_flags);

    bswaptls(&shdr->sh_addr);

    bswaptls(&shdr->sh_offset);

    bswaptls(&shdr->sh_size);

    bswap32s(&shdr->sh_link);

    bswap32s(&shdr->sh_info);

    bswaptls(&shdr->sh_addralign);

    bswaptls(&shdr->sh_entsize);

}


void fdt_build_clock_node(void *host_fdt, void *guest_fdt,

                         uint32_t host_phandle,

                         uint32_t guest_phandle)

{

    char *node_path = NULL;

    char *nodename;

    const void *r;

    int ret, node_offset, prop_len, path_len = 16;

    node_offset = fdt_node_offset_by_phandle(host_fdt, host_phandle);

    if (node_offset <= 0) {

        error_setg(&error_fatal,

                   "not able to locate clock handle %d in host device tree",

                   host_phandle);

    }

    node_path = g_malloc(path_len);

    while ((ret = fdt_get_path(host_fdt, node_offset, node_path, path_len))

            == -FDT_ERR_NOSPACE) {

        path_len += 16;

        node_path = g_realloc(node_path, path_len);

    }

    if (ret < 0) {

        error_setg(&error_fatal,

                   "not able to retrieve node path for clock handle %d",

                   host_phandle);

    }

    r = qemu_fdt_getprop(host_fdt, node_path, "compatible", &prop_len,

                         &error_fatal);

    if (strcmp(r, "fixed-clock")) {

        error_setg(&error_fatal,

                   "clock handle %d is not a fixed clock", host_phandle);

    }

    nodename = strrchr(node_path, '/');

    qemu_fdt_add_subnode(guest_fdt, nodename);

    copy_properties_from_host(clock_copied_properties,

                              ARRAY_SIZE(clock_copied_properties),

                              host_fdt, guest_fdt,

                              node_path, nodename);

    qemu_fdt_setprop_cell(guest_fdt, nodename, "phandle", guest_phandle);

    g_free(node_path);

}


static always_inline int _find_pte (mmu_ctx_t *ctx, int is_64b, int h, int rw)

{

    target_ulong base, pte0, pte1;

    int i, good = -1;

    int ret, r;

    ret = -1; /* No entry found */

    base = ctx->pg_addr[h];

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

#if defined(TARGET_PPC64)

        if (is_64b) {

            pte0 = ldq_phys(base + (i * 16));

            pte1 =  ldq_phys(base + (i * 16) + 8);

            r = pte64_check(ctx, pte0, pte1, h, rw);

#if defined (DEBUG_MMU)

            if (loglevel != 0) {

                fprintf(logfile, "Load pte from 0x" ADDRX " => 0x" ADDRX

                        " 0x" ADDRX " %d %d %d 0x" ADDRX "\n",

                        base + (i * 16), pte0, pte1,

                        (int)(pte0 & 1), h, (int)((pte0 >> 1) & 1),

                        ctx->ptem);

            }

#endif

        } else

#endif

        {

            pte0 = ldl_phys(base + (i * 8));

            pte1 =  ldl_phys(base + (i * 8) + 4);

            r = pte32_check(ctx, pte0, pte1, h, rw);

#if defined (DEBUG_MMU)

            if (loglevel != 0) {

                fprintf(logfile, "Load pte from 0x" ADDRX " => 0x" ADDRX

                        " 0x" ADDRX " %d %d %d 0x" ADDRX "\n",

                        base + (i * 8), pte0, pte1,

                        (int)(pte0 >> 31), h, (int)((pte0 >> 6) & 1),

                        ctx->ptem);

            }

#endif

        }

        switch (r) {

        case -3:

            /* PTE inconsistency */

            return -1;

        case -2:

            /* Access violation */

            ret = -2;

            good = i;

            break;

        case -1:

        default:

            /* No PTE match */

            break;

        case 0:

            /* access granted */

            /* XXX: we should go on looping to check all PTEs consistency

             *      but if we can speed-up the whole thing as the

             *      result would be undefined if PTEs are not consistent.

             */

            ret = 0;

            good = i;

            goto done;

        }

    }

    if (good != -1) {

    done:

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "found PTE at addr 0x" PADDRX " prot=0x%01x "

                    "ret=%d\n",

                    ctx->raddr, ctx->prot, ret);

        }

#endif

        /* Update page flags */

        pte1 = ctx->raddr;

        if (pte_update_flags(ctx, &pte1, ret, rw) == 1) {

#if defined(TARGET_PPC64)

            if (is_64b) {

                stq_phys_notdirty(base + (good * 16) + 8, pte1);

            } else

#endif

            {

                stl_phys_notdirty(base + (good * 8) + 4, pte1);

            }

        }

    }

    return ret;

}


static void x86_cpu_register_feature_bit_props(X86CPU *cpu,

                                               FeatureWord w,

                                               int bitnr)

{

    Object *obj = OBJECT(cpu);

    int i;

    char **names;

    FeatureWordInfo *fi = &feature_word_info[w];

    if (!fi->feat_names[bitnr]) {

        return;

    }

    names = g_strsplit(fi->feat_names[bitnr], "|", 0);

    feat2prop(names[0]);

    x86_cpu_register_bit_prop(cpu, names[0], &cpu->env.features[w], bitnr);

    for (i = 1; names[i]; i++) {

        feat2prop(names[i]);

        object_property_add_alias(obj, names[i], obj, names[0],

                                  &error_abort);

    }

    g_strfreev(names);

}


static void reschedule_dma(void *opaque)

{

    DMAAIOCB *dbs = (DMAAIOCB *)opaque;

    qemu_bh_delete(dbs->bh);

    dbs->bh = NULL;

    dma_bdrv_cb(dbs, 0);

}


static inline void gen_lookup_tb(DisasContext *s)

{

    tcg_gen_movi_i32(cpu_R[15], s->pc & ~1);

    s->is_jmp = DISAS_JUMP;

}


int kvm_arch_init_vcpu(CPUState *env)

{

    struct {

        struct kvm_cpuid2 cpuid;

        struct kvm_cpuid_entry2 entries[100];

    } __attribute__((packed)) cpuid_data;

    uint32_t limit, i, j, cpuid_i;

    uint32_t unused;

    struct kvm_cpuid_entry2 *c;

    uint32_t signature[3];

    env->cpuid_features &= kvm_arch_get_supported_cpuid(env, 1, 0, R_EDX);

    i = env->cpuid_ext_features & CPUID_EXT_HYPERVISOR;

    env->cpuid_ext_features &= kvm_arch_get_supported_cpuid(env, 1, 0, R_ECX);

    env->cpuid_ext_features |= i;

    env->cpuid_ext2_features &= kvm_arch_get_supported_cpuid(env, 0x80000001,

                                                             0, R_EDX);

    env->cpuid_ext3_features &= kvm_arch_get_supported_cpuid(env, 0x80000001,

                                                             0, R_ECX);

    env->cpuid_svm_features  &= kvm_arch_get_supported_cpuid(env, 0x8000000A,

                                                             0, R_EDX);

    cpuid_i = 0;

    /* Paravirtualization CPUIDs */

    memcpy(signature, "KVMKVMKVM\0\0\0", 12);

    c = &cpuid_data.entries[cpuid_i++];

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

    c->function = KVM_CPUID_SIGNATURE;

    c->eax = 0;

    c->ebx = signature[0];

    c->ecx = signature[1];

    c->edx = signature[2];

    c = &cpuid_data.entries[cpuid_i++];

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

    c->function = KVM_CPUID_FEATURES;

    c->eax = env->cpuid_kvm_features & kvm_arch_get_supported_cpuid(env,

                                                KVM_CPUID_FEATURES, 0, R_EAX);

    has_msr_async_pf_en = c->eax & (1 << KVM_FEATURE_ASYNC_PF);

    cpu_x86_cpuid(env, 0, 0, &limit, &unused, &unused, &unused);

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

        c = &cpuid_data.entries[cpuid_i++];

        switch (i) {

        case 2: {

            /* Keep reading function 2 till all the input is received */

            int times;

            c->function = i;

            c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC |

                       KVM_CPUID_FLAG_STATE_READ_NEXT;

            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);

            times = c->eax & 0xff;

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

                c = &cpuid_data.entries[cpuid_i++];

                c->function = i;

                c->flags = KVM_CPUID_FLAG_STATEFUL_FUNC;

                cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);

            }

            break;

        }

        case 4:

        case 0xb:

        case 0xd:

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

                c->function = i;

                c->flags = KVM_CPUID_FLAG_SIGNIFCANT_INDEX;

                c->index = j;

                cpu_x86_cpuid(env, i, j, &c->eax, &c->ebx, &c->ecx, &c->edx);

                if (i == 4 && c->eax == 0) {

                    break;

                }

                if (i == 0xb && !(c->ecx & 0xff00)) {

                    break;

                }

                if (i == 0xd && c->eax == 0) {

                    break;

                }

                c = &cpuid_data.entries[cpuid_i++];

            }

            break;

        default:

            c->function = i;

            c->flags = 0;

            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);

            break;

        }

    }

    cpu_x86_cpuid(env, 0x80000000, 0, &limit, &unused, &unused, &unused);

    for (i = 0x80000000; i <= limit; i++) {

        c = &cpuid_data.entries[cpuid_i++];

        c->function = i;

        c->flags = 0;

        cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);

    }

    /* Call Centaur's CPUID instructions they are supported. */

    if (env->cpuid_xlevel2 > 0) {

        env->cpuid_ext4_features &=

            kvm_arch_get_supported_cpuid(env, 0xC0000001, 0, R_EDX);

        cpu_x86_cpuid(env, 0xC0000000, 0, &limit, &unused, &unused, &unused);

        for (i = 0xC0000000; i <= limit; i++) {

            c = &cpuid_data.entries[cpuid_i++];

            c->function = i;

            c->flags = 0;

            cpu_x86_cpuid(env, i, 0, &c->eax, &c->ebx, &c->ecx, &c->edx);

        }

    }

    cpuid_data.cpuid.nent = cpuid_i;

    if (((env->cpuid_version >> 8)&0xF) >= 6

        && (env->cpuid_features&(CPUID_MCE|CPUID_MCA)) == (CPUID_MCE|CPUID_MCA)

        && kvm_check_extension(env->kvm_state, KVM_CAP_MCE) > 0) {

        uint64_t mcg_cap;

        int banks;

        int ret;

        ret = kvm_get_mce_cap_supported(env->kvm_state, &mcg_cap, &banks);

        if (ret < 0) {

            fprintf(stderr, "kvm_get_mce_cap_supported: %s", strerror(-ret));

            return ret;

        }

        if (banks > MCE_BANKS_DEF) {

            banks = MCE_BANKS_DEF;

        }

        mcg_cap &= MCE_CAP_DEF;

        mcg_cap |= banks;

        ret = kvm_vcpu_ioctl(env, KVM_X86_SETUP_MCE, &mcg_cap);

        if (ret < 0) {

            fprintf(stderr, "KVM_X86_SETUP_MCE: %s", strerror(-ret));

            return ret;

        }

        env->mcg_cap = mcg_cap;

    }

    qemu_add_vm_change_state_handler(cpu_update_state, env);

    return kvm_vcpu_ioctl(env, KVM_SET_CPUID2, &cpuid_data);

}


static int pci_bridge_initfn(PCIDevice *dev)

{

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

    pci_config_set_vendor_id(s->dev.config, s->vid);

    pci_config_set_device_id(s->dev.config, s->did);

    s->dev.config[0x04] = 0x06; // command = bus master, pci mem

    s->dev.config[0x05] = 0x00;

    s->dev.config[0x06] = 0xa0; // status = fast back-to-back, 66MHz, no error

    s->dev.config[0x07] = 0x00; // status = fast devsel

    s->dev.config[0x08] = 0x00; // revision

    s->dev.config[0x09] = 0x00; // programming i/f

    pci_config_set_class(s->dev.config, PCI_CLASS_BRIDGE_PCI);

    s->dev.config[0x0D] = 0x10; // latency_timer

    s->dev.config[PCI_HEADER_TYPE] =

        PCI_HEADER_TYPE_MULTI_FUNCTION | PCI_HEADER_TYPE_BRIDGE; // header_type

    s->dev.config[0x1E] = 0xa0; // secondary status

    return 0;

}


static void write_palette(const char *key, QObject *obj, void *opaque)

{

    struct palette_cb_priv *priv = opaque;

    VncState *vs = priv->vs;

    uint32_t bytes = vs->clientds.pf.bytes_per_pixel;

    uint8_t idx = qint_get_int(qobject_to_qint(obj));

    if (bytes == 4) {

        uint32_t color = tight_palette_buf2rgb(32, (uint8_t *)key);

        ((uint32_t*)priv->header)[idx] = color;

    } else {

        uint16_t color = tight_palette_buf2rgb(16, (uint8_t *)key);

        ((uint16_t*)priv->header)[idx] = color;

    }

}


static void rtas_get_xive(sPAPREnvironment *spapr, uint32_t token,

                          uint32_t nargs, target_ulong args,

                          uint32_t nret, target_ulong rets)

{

    struct ics_state *ics = spapr->icp->ics;

    uint32_t nr;

    if ((nargs != 1) || (nret != 3)) {

        rtas_st(rets, 0, -3);

        return;

    }

    nr = rtas_ld(args, 0);

    if (!ics_valid_irq(ics, nr)) {

        rtas_st(rets, 0, -3);

        return;

    }

    rtas_st(rets, 0, 0); /* Success */

    rtas_st(rets, 1, ics->irqs[nr - ics->offset].server);

    rtas_st(rets, 2, ics->irqs[nr - ics->offset].priority);

}


VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_WARNING)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_WARNING_RET_CORUPT)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_WARNING_BUF_END_BEFORE_LE)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_WARNING_INVALID_FILE_SELECTED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_WARNING_FCI_FORMAT_INVALID)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_WARNING_CHANGE)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_WARNING_FILE_FILLED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_EXC_ERROR)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_EXC_ERROR_CHANGE)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_WRONG_LENGTH)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_CLA_NOT_SUPPORTED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_CHANNEL_NOT_SUPPORTED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_SECURE_NOT_SUPPORTED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_COMMAND_NOT_SUPPORTED)

VCARD_RESPONSE_NEW_STATIC_STATUS(

                    VCARD7816_STATUS_ERROR_COMMAND_INCOMPATIBLE_WITH_FILE)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_SECURITY_NOT_SATISFIED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_AUTHENTICATION_BLOCKED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_DATA_INVALID)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_CONDITION_NOT_SATISFIED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_DATA_NO_EF)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_SM_OBJECT_MISSING)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_SM_OBJECT_INCORRECT)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_WRONG_PARAMETERS)

VCARD_RESPONSE_NEW_STATIC_STATUS(

                            VCARD7816_STATUS_ERROR_WRONG_PARAMETERS_IN_DATA)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_FUNCTION_NOT_SUPPORTED)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_FILE_NOT_FOUND)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_RECORD_NOT_FOUND)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_NO_SPACE_FOR_FILE)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_LC_TLV_INCONSISTENT)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_P1_P2_INCORRECT)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_LC_P1_P2_INCONSISTENT)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_DATA_NOT_FOUND)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_WRONG_PARAMETERS_2)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_INS_CODE_INVALID)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_CLA_INVALID)

VCARD_RESPONSE_NEW_STATIC_STATUS(VCARD7816_STATUS_ERROR_GENERAL)

/*

 * return a single response code. This function cannot fail. It will always

 * return a response.

 */

VCardResponse *

vcard_make_response(vcard_7816_status_t status)

{

    VCardResponse *response = NULL;

    switch (status) {

    /* known 7816 response codes */

    case VCARD7816_STATUS_SUCCESS:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_SUCCESS);

    case VCARD7816_STATUS_WARNING:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_WARNING);

    case VCARD7816_STATUS_WARNING_RET_CORUPT:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_WARNING_RET_CORUPT);

    case VCARD7816_STATUS_WARNING_BUF_END_BEFORE_LE:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_WARNING_BUF_END_BEFORE_LE);

    case VCARD7816_STATUS_WARNING_INVALID_FILE_SELECTED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_WARNING_INVALID_FILE_SELECTED);

    case VCARD7816_STATUS_WARNING_FCI_FORMAT_INVALID:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_WARNING_FCI_FORMAT_INVALID);

    case VCARD7816_STATUS_WARNING_CHANGE:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_WARNING_CHANGE);

    case VCARD7816_STATUS_WARNING_FILE_FILLED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_WARNING_FILE_FILLED);

    case VCARD7816_STATUS_EXC_ERROR:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_EXC_ERROR);

    case VCARD7816_STATUS_EXC_ERROR_CHANGE:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_EXC_ERROR_CHANGE);

    case VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE);

    case VCARD7816_STATUS_ERROR_WRONG_LENGTH:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_WRONG_LENGTH);

    case VCARD7816_STATUS_ERROR_CLA_NOT_SUPPORTED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_CLA_NOT_SUPPORTED);

    case VCARD7816_STATUS_ERROR_CHANNEL_NOT_SUPPORTED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_CHANNEL_NOT_SUPPORTED);

    case VCARD7816_STATUS_ERROR_SECURE_NOT_SUPPORTED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_SECURE_NOT_SUPPORTED);

    case VCARD7816_STATUS_ERROR_COMMAND_NOT_SUPPORTED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_COMMAND_NOT_SUPPORTED);

    case VCARD7816_STATUS_ERROR_COMMAND_INCOMPATIBLE_WITH_FILE:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_COMMAND_INCOMPATIBLE_WITH_FILE);

    case VCARD7816_STATUS_ERROR_SECURITY_NOT_SATISFIED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_SECURITY_NOT_SATISFIED);

    case VCARD7816_STATUS_ERROR_AUTHENTICATION_BLOCKED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_AUTHENTICATION_BLOCKED);

    case VCARD7816_STATUS_ERROR_DATA_INVALID:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_DATA_INVALID);

    case VCARD7816_STATUS_ERROR_CONDITION_NOT_SATISFIED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_CONDITION_NOT_SATISFIED);

    case VCARD7816_STATUS_ERROR_DATA_NO_EF:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_DATA_NO_EF);

    case VCARD7816_STATUS_ERROR_SM_OBJECT_MISSING:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_SM_OBJECT_MISSING);

    case VCARD7816_STATUS_ERROR_SM_OBJECT_INCORRECT:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_SM_OBJECT_INCORRECT);

    case VCARD7816_STATUS_ERROR_WRONG_PARAMETERS:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_WRONG_PARAMETERS);

    case VCARD7816_STATUS_ERROR_WRONG_PARAMETERS_IN_DATA:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_WRONG_PARAMETERS_IN_DATA);

    case VCARD7816_STATUS_ERROR_FUNCTION_NOT_SUPPORTED:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_FUNCTION_NOT_SUPPORTED);

    case VCARD7816_STATUS_ERROR_FILE_NOT_FOUND:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_FILE_NOT_FOUND);

    case VCARD7816_STATUS_ERROR_RECORD_NOT_FOUND:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_RECORD_NOT_FOUND);

    case VCARD7816_STATUS_ERROR_NO_SPACE_FOR_FILE:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_NO_SPACE_FOR_FILE);

    case VCARD7816_STATUS_ERROR_LC_TLV_INCONSISTENT:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_LC_TLV_INCONSISTENT);

    case VCARD7816_STATUS_ERROR_P1_P2_INCORRECT:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_P1_P2_INCORRECT);

    case VCARD7816_STATUS_ERROR_LC_P1_P2_INCONSISTENT:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_LC_P1_P2_INCONSISTENT);

    case VCARD7816_STATUS_ERROR_DATA_NOT_FOUND:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_DATA_NOT_FOUND);

    case VCARD7816_STATUS_ERROR_WRONG_PARAMETERS_2:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_WRONG_PARAMETERS_2);

    case VCARD7816_STATUS_ERROR_INS_CODE_INVALID:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_INS_CODE_INVALID);

    case VCARD7816_STATUS_ERROR_CLA_INVALID:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_CLA_INVALID);

    case VCARD7816_STATUS_ERROR_GENERAL:

        return VCARD_RESPONSE_GET_STATIC(

                    VCARD7816_STATUS_ERROR_GENERAL);

    default:

        /* we don't know this status code, create a response buffer to

         * hold it */

        response = vcard_response_new_status(status);

        if (response == NULL) {

            /* couldn't allocate the buffer, return memmory error */

            return VCARD_RESPONSE_GET_STATIC(

                        VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE);

        }

    }

    assert(response);

    return response;

}


static inline void dv_decode_video_segment(DVVideoContext *s,

                                           uint8_t *buf_ptr1,

                                           const uint16_t *mb_pos_ptr)

{

    int quant, dc, dct_mode, class1, j;

    int mb_index, mb_x, mb_y, v, last_index;

    DCTELEM *block, *block1;

    int c_offset;

    uint8_t *y_ptr;

    void (*idct_put)(uint8_t *dest, int line_size, DCTELEM *block);

    uint8_t *buf_ptr;

    PutBitContext pb, vs_pb;

    GetBitContext gb;

    BlockInfo mb_data[5 * 6], *mb, *mb1;

    DCTELEM sblock[5*6][64] __align8;

    uint8_t mb_bit_buffer[80 + 4]; /* allow some slack */

    uint8_t vs_bit_buffer[5 * 80 + 4]; /* allow some slack */

    memset(sblock, 0, sizeof(sblock));

    /* pass 1 : read DC and AC coefficients in blocks */

    buf_ptr = buf_ptr1;

    block1 = &sblock[0][0];

    mb1 = mb_data;

    init_put_bits(&vs_pb, vs_bit_buffer, 5 * 80);

    for(mb_index = 0; mb_index < 5; mb_index++, mb1 += 6, block1 += 6 * 64) {

        /* skip header */

        quant = buf_ptr[3] & 0x0f;

        buf_ptr += 4;

        init_put_bits(&pb, mb_bit_buffer, 80);

        mb = mb1;

        block = block1;

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

            last_index = block_sizes[j];

	    init_get_bits(&gb, buf_ptr, last_index);

            /* get the dc */

            dc = get_sbits(&gb, 9);

            dct_mode = get_bits1(&gb);

            mb->dct_mode = dct_mode;

            mb->scan_table = s->dv_zigzag[dct_mode];

            class1 = get_bits(&gb, 2);

            mb->shift_table = s->dv_idct_shift[class1 == 3][dct_mode]

                [quant + dv_quant_offset[class1]];

            dc = dc << 2;

            /* convert to unsigned because 128 is not added in the

               standard IDCT */

            dc += 1024;

            block[0] = dc;

            buf_ptr += last_index >> 3;

            mb->pos = 0;

            mb->partial_bit_count = 0;

#ifdef VLC_DEBUG

            printf("MB block: %d, %d ", mb_index, j);

#endif

            dv_decode_ac(&gb, mb, block);

            /* write the remaining bits  in a new buffer only if the

               block is finished */

            if (mb->pos >= 64)

                bit_copy(&pb, &gb);

            block += 64;

            mb++;

        }

        /* pass 2 : we can do it just after */

#ifdef VLC_DEBUG

        printf("***pass 2 size=%d MB#=%d\n", put_bits_count(&pb), mb_index);

#endif

        block = block1;

        mb = mb1;

        init_get_bits(&gb, mb_bit_buffer, put_bits_count(&pb));

	flush_put_bits(&pb);

        for(j = 0;j < 6; j++, block += 64, mb++) {

            if (mb->pos < 64 && get_bits_left(&gb) > 0) {

                dv_decode_ac(&gb, mb, block);

                /* if still not finished, no need to parse other blocks */

                if (mb->pos < 64)

                    break;

            }

        }

        /* all blocks are finished, so the extra bytes can be used at

           the video segment level */

        if (j >= 6)

	    bit_copy(&vs_pb, &gb);

    }

    /* we need a pass other the whole video segment */

#ifdef VLC_DEBUG

    printf("***pass 3 size=%d\n", put_bits_count(&vs_pb));

#endif

    block = &sblock[0][0];

    mb = mb_data;

    init_get_bits(&gb, vs_bit_buffer, put_bits_count(&vs_pb));

    flush_put_bits(&vs_pb);

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

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

            if (mb->pos < 64) {

#ifdef VLC_DEBUG

                printf("start %d:%d\n", mb_index, j);

#endif

                dv_decode_ac(&gb, mb, block);

            }

	    if (mb->pos >= 64 && mb->pos < 127)

		av_log(NULL, AV_LOG_ERROR, "AC EOB marker is absent pos=%d\n", mb->pos);

            block += 64;

            mb++;

        }

    }

    /* compute idct and place blocks */

    block = &sblock[0][0];

    mb = mb_data;

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

        v = *mb_pos_ptr++;

        mb_x = v & 0xff;

        mb_y = v >> 8;

        y_ptr = s->picture.data[0] + (mb_y * s->picture.linesize[0] * 8) + (mb_x * 8);

        if (s->sys->pix_fmt == PIX_FMT_YUV411P)

            c_offset = (mb_y * s->picture.linesize[1] * 8) + ((mb_x >> 2) * 8);

        else

            c_offset = ((mb_y >> 1) * s->picture.linesize[1] * 8) + ((mb_x >> 1) * 8);

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

            idct_put = s->idct_put[mb->dct_mode];

            if (j < 4) {

                if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x < (704 / 8)) {

                    /* NOTE: at end of line, the macroblock is handled as 420 */

                    idct_put(y_ptr + (j * 8), s->picture.linesize[0], block);

                } else {

                    idct_put(y_ptr + ((j & 1) * 8) + ((j >> 1) * 8 * s->picture.linesize[0]),

                             s->picture.linesize[0], block);

                }

            } else {

                if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {

                    uint64_t aligned_pixels[64/8];

                    uint8_t *pixels= (uint8_t*)aligned_pixels;

		    uint8_t *c_ptr, *c_ptr1, *ptr;

                    int y, linesize;

                    /* NOTE: at end of line, the macroblock is handled as 420 */

                    idct_put(pixels, 8, block);

                    linesize = s->picture.linesize[6 - j];

                    c_ptr = s->picture.data[6 - j] + c_offset;

                    ptr = pixels;

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

                        /* convert to 411P */

                        c_ptr1 = c_ptr + 8*linesize;

                        c_ptr[0]= ptr[0]; c_ptr1[0]= ptr[4];

                        c_ptr[1]= ptr[1]; c_ptr1[1]= ptr[5];

                        c_ptr[2]= ptr[2]; c_ptr1[2]= ptr[6];

                        c_ptr[3]= ptr[3]; c_ptr1[3]= ptr[7];

                        c_ptr += linesize;

                        ptr += 8;

                    }

                } else {

                    /* don't ask me why they inverted Cb and Cr ! */

                    idct_put(s->picture.data[6 - j] + c_offset,

                             s->picture.linesize[6 - j], block);

                }

            }

            block += 64;

            mb++;

        }

    }

}


BlockDeviceInfo *bdrv_block_device_info(BlockDriverState *bs, Error **errp)

{

    ImageInfo **p_image_info;

    BlockDriverState *bs0;

    BlockDeviceInfo *info = g_malloc0(sizeof(*info));

    info->file                   = g_strdup(bs->filename);

    info->ro                     = bs->read_only;

    info->drv                    = g_strdup(bs->drv->format_name);

    info->encrypted              = bs->encrypted;

    info->encryption_key_missing = bdrv_key_required(bs);

    info->cache = g_new(BlockdevCacheInfo, 1);

    *info->cache = (BlockdevCacheInfo) {

        .writeback      = bdrv_enable_write_cache(bs),

        .direct         = !!(bs->open_flags & BDRV_O_NOCACHE),

        .no_flush       = !!(bs->open_flags & BDRV_O_NO_FLUSH),

    };

    if (bs->node_name[0]) {

        info->has_node_name = true;

        info->node_name = g_strdup(bs->node_name);

    }

    if (bs->backing_file[0]) {

        info->has_backing_file = true;

        info->backing_file = g_strdup(bs->backing_file);

    }

    info->backing_file_depth = bdrv_get_backing_file_depth(bs);

    info->detect_zeroes = bs->detect_zeroes;

    if (bs->io_limits_enabled) {

        ThrottleConfig cfg;

        throttle_group_get_config(bs, &cfg);

        info->bps     = cfg.buckets[THROTTLE_BPS_TOTAL].avg;

        info->bps_rd  = cfg.buckets[THROTTLE_BPS_READ].avg;

        info->bps_wr  = cfg.buckets[THROTTLE_BPS_WRITE].avg;

        info->iops    = cfg.buckets[THROTTLE_OPS_TOTAL].avg;

        info->iops_rd = cfg.buckets[THROTTLE_OPS_READ].avg;

        info->iops_wr = cfg.buckets[THROTTLE_OPS_WRITE].avg;

        info->has_bps_max     = cfg.buckets[THROTTLE_BPS_TOTAL].max;

        info->bps_max         = cfg.buckets[THROTTLE_BPS_TOTAL].max;

        info->has_bps_rd_max  = cfg.buckets[THROTTLE_BPS_READ].max;

        info->bps_rd_max      = cfg.buckets[THROTTLE_BPS_READ].max;

        info->has_bps_wr_max  = cfg.buckets[THROTTLE_BPS_WRITE].max;

        info->bps_wr_max      = cfg.buckets[THROTTLE_BPS_WRITE].max;

        info->has_iops_max    = cfg.buckets[THROTTLE_OPS_TOTAL].max;

        info->iops_max        = cfg.buckets[THROTTLE_OPS_TOTAL].max;

        info->has_iops_rd_max = cfg.buckets[THROTTLE_OPS_READ].max;

        info->iops_rd_max     = cfg.buckets[THROTTLE_OPS_READ].max;

        info->has_iops_wr_max = cfg.buckets[THROTTLE_OPS_WRITE].max;

        info->iops_wr_max     = cfg.buckets[THROTTLE_OPS_WRITE].max;

        info->has_iops_size = cfg.op_size;

        info->iops_size = cfg.op_size;

        info->has_group = true;

        info->group = g_strdup(throttle_group_get_name(bs));

    }

    info->write_threshold = bdrv_write_threshold_get(bs);

    bs0 = bs;

    p_image_info = &info->image;

    while (1) {

        Error *local_err = NULL;

        bdrv_query_image_info(bs0, p_image_info, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            qapi_free_BlockDeviceInfo(info);

            return NULL;

        }

        if (bs0->drv && bs0->backing) {

            bs0 = bs0->backing->bs;

            (*p_image_info)->has_backing_image = true;

            p_image_info = &((*p_image_info)->backing_image);

        } else {

            break;

        }

    }

    return info;

}


void tcg_set_frame(TCGContext *s, int reg, intptr_t start, intptr_t size)

{

    s->frame_start = start;

    s->frame_end = start + size;

    s->frame_reg = reg;

}


static int target_to_host_fcntl_cmd(int cmd)

{

    switch(cmd) {

	case TARGET_F_DUPFD:

	case TARGET_F_GETFD:

	case TARGET_F_SETFD:

	case TARGET_F_GETFL:

	case TARGET_F_SETFL:

            return cmd;

        case TARGET_F_GETLK:

	    return F_GETLK;

	case TARGET_F_SETLK:

	    return F_SETLK;

	case TARGET_F_SETLKW:

	    return F_SETLKW;

	case TARGET_F_GETOWN:

	    return F_GETOWN;

	case TARGET_F_SETOWN:

	    return F_SETOWN;

	case TARGET_F_GETSIG:

	    return F_GETSIG;

	case TARGET_F_SETSIG:

	    return F_SETSIG;

#if TARGET_ABI_BITS == 32

        case TARGET_F_GETLK64:

	    return F_GETLK64;

	case TARGET_F_SETLK64:

	    return F_SETLK64;

	case TARGET_F_SETLKW64:

	    return F_SETLKW64;

#endif

        case TARGET_F_SETLEASE:

            return F_SETLEASE;

        case TARGET_F_GETLEASE:

            return F_GETLEASE;

#ifdef F_DUPFD_CLOEXEC

        case TARGET_F_DUPFD_CLOEXEC:

            return F_DUPFD_CLOEXEC;

#endif

        case TARGET_F_NOTIFY:

            return F_NOTIFY;

#ifdef F_GETOWN_EX

	case TARGET_F_GETOWN_EX:

	    return F_GETOWN_EX;

#endif

#ifdef F_SETOWN_EX

	case TARGET_F_SETOWN_EX:

	    return F_SETOWN_EX;

#endif

	default:

            return -TARGET_EINVAL;

    }

    return -TARGET_EINVAL;

}


static void test_io_channel_ipv6(bool async)

{

    SocketAddress *listen_addr = g_new0(SocketAddress, 1);

    SocketAddress *connect_addr = g_new0(SocketAddress, 1);

    listen_addr->type = SOCKET_ADDRESS_KIND_INET;

    listen_addr->u.inet = g_new(InetSocketAddress, 1);

    *listen_addr->u.inet = (InetSocketAddress) {

        .host = g_strdup("::1"),

        .port = NULL, /* Auto-select */

    };

    connect_addr->type = SOCKET_ADDRESS_KIND_INET;

    connect_addr->u.inet = g_new(InetSocketAddress, 1);

    *connect_addr->u.inet = (InetSocketAddress) {

        .host = g_strdup("::1"),

        .port = NULL, /* Filled in later */

    };

    test_io_channel(async, listen_addr, connect_addr, false);

    qapi_free_SocketAddress(listen_addr);

    qapi_free_SocketAddress(connect_addr);

}


ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply)

{

    uint8_t buf[NBD_REPLY_SIZE];

    uint32_t magic;

    ssize_t ret;

    ret = read_sync(ioc, buf, sizeof(buf));

    if (ret <= 0) {

        return ret;

    }

    if (ret != sizeof(buf)) {

        LOG("read failed");

        return -EINVAL;

    }

    /* Reply

       [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)

       [ 4 ..  7]    error   (0 == no error)

       [ 7 .. 15]    handle

     */

    magic = ldl_be_p(buf);

    reply->error  = ldl_be_p(buf + 4);

    reply->handle = ldq_be_p(buf + 8);

    reply->error = nbd_errno_to_system_errno(reply->error);

    if (reply->error == ESHUTDOWN) {

        /* This works even on mingw which lacks a native ESHUTDOWN */

        LOG("server shutting down");

        return -EINVAL;

    }

    TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32

          ", handle = %" PRIu64" }",

          magic, reply->error, reply->handle);

    if (magic != NBD_REPLY_MAGIC) {

        LOG("invalid magic (got 0x%" PRIx32 ")", magic);

        return -EINVAL;

    }

    return 0;

}


void qemu_map_cache_init(void)

{

    unsigned long size;

    struct rlimit rlimit_as;

    mapcache = qemu_mallocz(sizeof (MapCache));

    QTAILQ_INIT(&mapcache->locked_entries);

    mapcache->last_address_index = -1;

    getrlimit(RLIMIT_AS, &rlimit_as);

    rlimit_as.rlim_cur = rlimit_as.rlim_max;

    setrlimit(RLIMIT_AS, &rlimit_as);

    mapcache->max_mcache_size = rlimit_as.rlim_max;

    mapcache->nr_buckets =

        (((mapcache->max_mcache_size >> XC_PAGE_SHIFT) +

          (1UL << (MCACHE_BUCKET_SHIFT - XC_PAGE_SHIFT)) - 1) >>

         (MCACHE_BUCKET_SHIFT - XC_PAGE_SHIFT));

    size = mapcache->nr_buckets * sizeof (MapCacheEntry);

    size = (size + XC_PAGE_SIZE - 1) & ~(XC_PAGE_SIZE - 1);

    DPRINTF("qemu_map_cache_init, nr_buckets = %lx size %lu\n", mapcache->nr_buckets, size);

    mapcache->entry = qemu_mallocz(size);

}


static inline void gen_op_fcmpes(int fccno, TCGv_i32 r_rs1, TCGv_i32 r_rs2)

{

    switch (fccno) {

    case 0:

        gen_helper_fcmpes(cpu_env, r_rs1, r_rs2);

        break;

    case 1:

        gen_helper_fcmpes_fcc1(cpu_env, r_rs1, r_rs2);

        break;

    case 2:

        gen_helper_fcmpes_fcc2(cpu_env, r_rs1, r_rs2);

        break;

    case 3:

        gen_helper_fcmpes_fcc3(cpu_env, r_rs1, r_rs2);

        break;

    }

}


static inline int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){

    int i, off;

    uint32_t c;

    const uint32_t* buf;

    uint32_t* obuf = (uint32_t*) out;

    /* FIXME: 64 bit platforms would be able to do 64 bits at a time.

     * I'm too lazy though, should be something like

     * for(i=0 ; i<bitamount/64 ; i++)

     *     (int64_t)out[i] = 0x37c511f237c511f2^av_be2ne64(int64_t)in[i]);

     * Buffer alignment needs to be checked. */

    off = (intptr_t)inbuffer & 3;

    buf = (const uint32_t*) (inbuffer - off);

    c = av_be2ne32((0x37c511f2 >> (off*8)) | (0x37c511f2 << (32-(off*8))));

    bytes += 3 + off;

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

        obuf[i] = c ^ buf[i];

    return off;

}


int net_init_socket(const Netdev *netdev, const char *name,

                    NetClientState *peer, Error **errp)

{

    /* FIXME error_setg(errp, ...) on failure */

    Error *err = NULL;

    const NetdevSocketOptions *sock;

    assert(netdev->type == NET_CLIENT_DRIVER_SOCKET);

    sock = &netdev->u.socket;

    if (sock->has_fd + sock->has_listen + sock->has_connect + sock->has_mcast +

        sock->has_udp != 1) {

        error_report("exactly one of fd=, listen=, connect=, mcast= or udp="

                     " is required");

        return -1;

    }

    if (sock->has_localaddr && !sock->has_mcast && !sock->has_udp) {

        error_report("localaddr= is only valid with mcast= or udp=");

        return -1;

    }

    if (sock->has_fd) {

        int fd;

        fd = monitor_fd_param(cur_mon, sock->fd, &err);

        if (fd == -1) {

            error_report_err(err);

            return -1;

        }

        qemu_set_nonblock(fd);

        if (!net_socket_fd_init(peer, "socket", name, fd, 1)) {

            return -1;

        }

        return 0;

    }

    if (sock->has_listen) {

        if (net_socket_listen_init(peer, "socket", name, sock->listen) == -1) {

            return -1;

        }

        return 0;

    }

    if (sock->has_connect) {

        if (net_socket_connect_init(peer, "socket", name, sock->connect) ==

            -1) {

            return -1;

        }

        return 0;

    }

    if (sock->has_mcast) {

        /* if sock->localaddr is missing, it has been initialized to "all bits

         * zero" */

        if (net_socket_mcast_init(peer, "socket", name, sock->mcast,

            sock->localaddr) == -1) {

            return -1;

        }

        return 0;

    }

    assert(sock->has_udp);

    if (!sock->has_localaddr) {

        error_report("localaddr= is mandatory with udp=");

        return -1;

    }

    if (net_socket_udp_init(peer, "socket", name, sock->udp, sock->localaddr) ==

        -1) {

        return -1;

    }

    return 0;

}


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

{

    ISADevice *isadev = ISA_DEVICE(dev);

    FDCtrlISABus *isa = ISA_FDC(dev);

    FDCtrl *fdctrl = &isa->state;

    Error *err = NULL;

    isa_register_portio_list(isadev, isa->iobase, fdc_portio_list, fdctrl,

                             "fdc");

    isa_init_irq(isadev, &fdctrl->irq, isa->irq);

    fdctrl->dma_chann = isa->dma;

    if (fdctrl->dma_chann != -1) {

        fdctrl->dma = isa_get_dma(isa_bus_from_device(isadev), isa->dma);

        assert(fdctrl->dma);

    }

    qdev_set_legacy_instance_id(dev, isa->iobase, 2);

    fdctrl_realize_common(fdctrl, &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

}


static void network_to_register(RDMARegister *reg)

{

    reg->key.current_addr = ntohll(reg->key.current_addr);

    reg->current_index = ntohl(reg->current_index);

    reg->chunks = ntohll(reg->chunks);

}


ogg_get_length (AVFormatContext * s)

{

    ogg_t *ogg = s->priv_data;

    int idx = -1, i;

    offset_t size, end;

    if(s->pb.is_streamed)

        return 0;

// already set

    if (s->duration != AV_NOPTS_VALUE)

        return 0;

    size = url_fsize(&s->pb);

    if(size < 0)

        return 0;

    end = size > MAX_PAGE_SIZE? size - MAX_PAGE_SIZE: size;

    ogg_save (s);

    url_fseek (&s->pb, end, SEEK_SET);

    while (!ogg_read_page (s, &i)){

        if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0)

            idx = i;

    }

    if (idx != -1){

        s->streams[idx]->duration =

            ogg_gptopts (s, idx, ogg->streams[idx].granule);

    }

    ogg->size = size;

    ogg_restore (s, 0);

    ogg_save (s);

    while (!ogg_read_page (s, &i)) {

        if (i == idx && ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0)

            break;

    }

    if (i == idx) {

        s->streams[idx]->start_time = ogg_gptopts (s, idx, ogg->streams[idx].granule);

        s->streams[idx]->duration -= s->streams[idx]->start_time;

    }

    ogg_restore (s, 0);

    return 0;

}


static void qemu_event_increment(void)

{

    SetEvent(qemu_event_handle);

}


static int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)

{

    if (!balloon_event_fn) {

        return 0;

    }

    trace_balloon_event(balloon_opaque, target);

    balloon_event_fn(balloon_opaque, target, cb, opaque);

    return 1;

}


void helper_wrmsr(void)

{

    uint64_t val;

    helper_svm_check_intercept_param(SVM_EXIT_MSR, 1);

    val = ((uint32_t)EAX) | ((uint64_t)((uint32_t)EDX) << 32);

    switch((uint32_t)ECX) {

    case MSR_IA32_SYSENTER_CS:

        env->sysenter_cs = val & 0xffff;

    case MSR_IA32_SYSENTER_ESP:

        env->sysenter_esp = val;

    case MSR_IA32_SYSENTER_EIP:

        env->sysenter_eip = val;

    case MSR_IA32_APICBASE:

        cpu_set_apic_base(env, val);

    case MSR_EFER:

        {

            uint64_t update_mask;

            update_mask = 0;

            if (env->cpuid_ext2_features & CPUID_EXT2_SYSCALL)

                update_mask |= MSR_EFER_SCE;

            if (env->cpuid_ext2_features & CPUID_EXT2_LM)

                update_mask |= MSR_EFER_LME;

            if (env->cpuid_ext2_features & CPUID_EXT2_FFXSR)

                update_mask |= MSR_EFER_FFXSR;

            if (env->cpuid_ext2_features & CPUID_EXT2_NX)

                update_mask |= MSR_EFER_NXE;

            if (env->cpuid_ext3_features & CPUID_EXT3_SVM)

                update_mask |= MSR_EFER_SVME;

            cpu_load_efer(env, (env->efer & ~update_mask) |

                          (val & update_mask));

        }

    case MSR_STAR:

        env->star = val;

    case MSR_PAT:

        env->pat = val;

    case MSR_VM_HSAVE_PA:

        env->vm_hsave = val;

#ifdef TARGET_X86_64

    case MSR_LSTAR:

        env->lstar = val;

    case MSR_CSTAR:

        env->cstar = val;

    case MSR_FMASK:

        env->fmask = val;

    case MSR_FSBASE:

        env->segs[R_FS].base = val;

    case MSR_GSBASE:

        env->segs[R_GS].base = val;

    case MSR_KERNELGSBASE:

        env->kernelgsbase = val;

#endif

    default:

        /* XXX: exception ? */

    }

}


static int rm_write_header(AVFormatContext *s)
{
    RMMuxContext *rm = s->priv_data;
    StreamInfo *stream;
    int n;
    AVCodecContext *codec;
    for(n=0;n<s->nb_streams;n++) {
        s->streams[n]->id = n;
        codec = s->streams[n]->codec;
        stream = &rm->streams[n];
        memset(stream, 0, sizeof(StreamInfo));
        stream->num = n;
        stream->bit_rate = codec->bit_rate;
        stream->enc = codec;
        switch(codec->codec_type) {
        case AVMEDIA_TYPE_AUDIO:
            rm->audio_stream = stream;
            stream->frame_rate = (float)codec->sample_rate / (float)codec->frame_size;
            /* XXX: dummy values */
            stream->packet_max_size = 1024;
            stream->nb_packets = 0;
            stream->total_frames = stream->nb_packets;
            break;
        case AVMEDIA_TYPE_VIDEO:
            rm->video_stream = stream;
            stream->frame_rate = (float)codec->time_base.den / (float)codec->time_base.num;
            /* XXX: dummy values */
            stream->packet_max_size = 4096;
            stream->nb_packets = 0;
            stream->total_frames = stream->nb_packets;
            break;
        default:
            return -1;
    if (rv10_write_header(s, 0, 0))
        return AVERROR_INVALIDDATA;
    avio_flush(s->pb);
    return 0;


static inline void mix_stereo_to_mono(AC3DecodeContext *ctx)

{

    int i;

    float (*output)[256] = ctx->audio_block.block_output;

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

        output[1][i] += output[2][i];

    memset(output[2], 0, sizeof(output[2]));

}


static int msmpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)

{

    int level, pred;

    if(s->msmpeg4_version<=2){

        if (n < 4) {

            level = get_vlc2(&s->gb, v2_dc_lum_vlc.table, DC_VLC_BITS, 3);

        } else {

            level = get_vlc2(&s->gb, v2_dc_chroma_vlc.table, DC_VLC_BITS, 3);

        }

        if (level < 0)

            return -1;

        level-=256;

    }else{  //FIXME optimize use unified tables & index

        if (n < 4) {

            level = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

        } else {

            level = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

        }

        if (level < 0){

            av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");

            return -1;

        }

        if (level == DC_MAX) {

            level = get_bits(&s->gb, 8);

            if (get_bits1(&s->gb))

                level = -level;

        } else if (level != 0) {

            if (get_bits1(&s->gb))

                level = -level;

        }

    }

    if(s->msmpeg4_version==1){

        int32_t *dc_val;

        pred = msmpeg4v1_pred_dc(s, n, &dc_val);

        level += pred;

        /* update predictor */

        *dc_val= level;

    }else{

        int16_t *dc_val;

        pred   = ff_msmpeg4_pred_dc(s, n, &dc_val, dir_ptr);

        level += pred;

        /* update predictor */

        if (n < 4) {

            *dc_val = level * s->y_dc_scale;

        } else {

            *dc_val = level * s->c_dc_scale;

        }

    }

    return level;

}


void ff_put_h264_qpel16_mc21_msa(uint8_t *dst, const uint8_t *src,

                                 ptrdiff_t stride)

{

    avc_luma_midv_qrt_16w_msa(src - (2 * stride) - 2,

                              stride, dst, stride, 16, 0);

}


av_cold int ff_ivi_init_tiles(IVIPlaneDesc *planes, int tile_width, int tile_height)

{

    int         p, b, x, y, x_tiles, y_tiles, t_width, t_height;

    IVIBandDesc *band;

    IVITile     *tile, *ref_tile;

    for (p = 0; p < 3; p++) {

        t_width  = !p ? tile_width  : (tile_width  + 3) >> 2;

        t_height = !p ? tile_height : (tile_height + 3) >> 2;

        if (!p && planes[0].num_bands == 4) {

            t_width  >>= 1;

            t_height >>= 1;

        }

        if(t_width<=0 || t_height<=0)

            return AVERROR(EINVAL);

        for (b = 0; b < planes[p].num_bands; b++) {

            band = &planes[p].bands[b];

            x_tiles = IVI_NUM_TILES(band->width, t_width);

            y_tiles = IVI_NUM_TILES(band->height, t_height);

            band->num_tiles = x_tiles * y_tiles;

            av_freep(&band->tiles);

            band->tiles = av_mallocz(band->num_tiles * sizeof(IVITile));

            if (!band->tiles)

                return AVERROR(ENOMEM);

            tile = band->tiles;

            /* use the first luma band as reference for motion vectors

             * and quant */

            ref_tile = planes[0].bands[0].tiles;

            for (y = 0; y < band->height; y += t_height) {

                for (x = 0; x < band->width; x += t_width) {

                    tile->xpos     = x;

                    tile->ypos     = y;

                    tile->mb_size  = band->mb_size;

                    tile->width    = FFMIN(band->width - x,  t_width);

                    tile->height   = FFMIN(band->height - y, t_height);

                    tile->is_empty = tile->data_size = 0;

                    /* calculate number of macroblocks */

                    tile->num_MBs  = IVI_MBs_PER_TILE(tile->width, tile->height,

                                                      band->mb_size);

                    av_freep(&tile->mbs);

                    tile->mbs = av_malloc(tile->num_MBs * sizeof(IVIMbInfo));

                    if (!tile->mbs)

                        return AVERROR(ENOMEM);

                    tile->ref_mbs = 0;

                    if (p || b) {

                        tile->ref_mbs = ref_tile->mbs;

                        ref_tile++;

                    }

                    tile++;

                }

            }

        }// for b

    }// for p

    return 0;

}


static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFContext *mxf = arg;

    switch (tag) {

    case 0x1901:

        mxf->packages_count = avio_rb32(pb);

        if (mxf->packages_count >= UINT_MAX / sizeof(UID))

            return -1;

        mxf->packages_refs = av_malloc(mxf->packages_count * sizeof(UID));

        if (!mxf->packages_refs)

            return -1;

        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */

        avio_read(pb, (uint8_t *)mxf->packages_refs, mxf->packages_count * sizeof(UID));

        break;

    }

    return 0;

}


int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)

{

    int64_t r = 0;

    av_assert2(c > 0);

    av_assert2(b >=0);

    av_assert2((unsigned)(rnd&~AV_ROUND_PASS_MINMAX)<=5 && (rnd&~AV_ROUND_PASS_MINMAX)!=4);

    if (c <= 0 || b < 0 || !((unsigned)(rnd&~AV_ROUND_PASS_MINMAX)<=5 && (rnd&~AV_ROUND_PASS_MINMAX)!=4))

        return INT64_MIN;

    if (rnd & AV_ROUND_PASS_MINMAX) {

        if (a == INT64_MIN || a == INT64_MAX)

            return a;

        rnd -= AV_ROUND_PASS_MINMAX;

    }

    if (a < 0)

        return -(uint64_t)av_rescale_rnd(-FFMAX(a, -INT64_MAX), b, c, rnd ^ ((rnd >> 1) & 1));

    if (rnd == AV_ROUND_NEAR_INF)

        r = c / 2;

    else if (rnd & 1)

        r = c - 1;

    if (b <= INT_MAX && c <= INT_MAX) {

        if (a <= INT_MAX)

            return (a * b + r) / c;

        else {

            int64_t ad = a / c;

            int64_t a2 = (a % c * b + r) / c;

            if (ad >= INT32_MAX && ad > (INT64_MAX - a2) / b)

                return INT64_MIN;

            return ad * b + a2;

        }

    } else {

#if 1

        uint64_t a0  = a & 0xFFFFFFFF;

        uint64_t a1  = a >> 32;

        uint64_t b0  = b & 0xFFFFFFFF;

        uint64_t b1  = b >> 32;

        uint64_t t1  = a0 * b1 + a1 * b0;

        uint64_t t1a = t1 << 32;

        int i;

        a0  = a0 * b0 + t1a;

        a1  = a1 * b1 + (t1 >> 32) + (a0 < t1a);

        a0 += r;

        a1 += a0 < r;

        for (i = 63; i >= 0; i--) {

            a1 += a1 + ((a0 >> i) & 1);

            t1 += t1;

            if (c <= a1) {

                a1 -= c;

                t1++;

            }

        }

        if (t1 > INT64_MAX)

            return INT64_MIN;

        return t1;

    }

#else

        AVInteger ai;

        ai = av_mul_i(av_int2i(a), av_int2i(b));

        ai = av_add_i(ai, av_int2i(r));

        return av_i2int(av_div_i(ai, av_int2i(c)));

    }

#endif

}


static void gen_check_cpenable(DisasContext *dc, unsigned cp)

{

    if (option_enabled(dc, XTENSA_OPTION_COPROCESSOR) &&

            !(dc->cpenable & (1 << cp))) {

        gen_exception_cause(dc, COPROCESSOR0_DISABLED + cp);

        dc->is_jmp = DISAS_UPDATE;

    }

}


static void gen_write_xer(TCGv src)

{

    tcg_gen_andi_tl(cpu_xer, src,

                    ~((1u << XER_SO) | (1u << XER_OV) | (1u << XER_CA)));

    tcg_gen_extract_tl(cpu_so, src, XER_SO, 1);

    tcg_gen_extract_tl(cpu_ov, src, XER_OV, 1);

    tcg_gen_extract_tl(cpu_ca, src, XER_CA, 1);

}


void decode_mvs(VP8Context *s, VP8Macroblock *mb,

                int mb_x, int mb_y, int layout)

{

    VP8Macroblock *mb_edge[3] = { 0      /* top */,

                                  mb - 1 /* left */,

                                  0      /* top-left */ };

    enum { CNT_ZERO, CNT_NEAREST, CNT_NEAR, CNT_SPLITMV };

    enum { VP8_EDGE_TOP, VP8_EDGE_LEFT, VP8_EDGE_TOPLEFT };

    int idx = CNT_ZERO;

    int cur_sign_bias = s->sign_bias[mb->ref_frame];

    int8_t *sign_bias = s->sign_bias;

    VP56mv near_mv[4];

    uint8_t cnt[4] = { 0 };

    VP56RangeCoder *c = &s->c;

    if (!layout) { // layout is inlined (s->mb_layout is not)

        mb_edge[0] = mb + 2;

        mb_edge[2] = mb + 1;

    } else {

        mb_edge[0] = mb - s->mb_width - 1;

        mb_edge[2] = mb - s->mb_width - 2;

    }

    AV_ZERO32(&near_mv[0]);

    AV_ZERO32(&near_mv[1]);

    AV_ZERO32(&near_mv[2]);

    /* Process MB on top, left and top-left */

#define MV_EDGE_CHECK(n)                                                      \

    {                                                                         \

        VP8Macroblock *edge = mb_edge[n];                                     \

        int edge_ref = edge->ref_frame;                                       \

        if (edge_ref != VP56_FRAME_CURRENT) {                                 \

            uint32_t mv = AV_RN32A(&edge->mv);                                \

            if (mv) {                                                         \

                if (cur_sign_bias != sign_bias[edge_ref]) {                   \

                    /* SWAR negate of the values in mv. */                    \

                    mv = ~mv;                                                 \

                    mv = ((mv & 0x7fff7fff) +                                 \

                          0x00010001) ^ (mv & 0x80008000);                    \

                }                                                             \

                if (!n || mv != AV_RN32A(&near_mv[idx]))                      \

                    AV_WN32A(&near_mv[++idx], mv);                            \

                cnt[idx] += 1 + (n != 2);                                     \

            } else                                                            \

                cnt[CNT_ZERO] += 1 + (n != 2);                                \

        }                                                                     \

    }

    MV_EDGE_CHECK(0)

    MV_EDGE_CHECK(1)

    MV_EDGE_CHECK(2)

    mb->partitioning = VP8_SPLITMVMODE_NONE;

    if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_ZERO]][0])) {

        mb->mode = VP8_MVMODE_MV;

        /* If we have three distinct MVs, merge first and last if they're the same */

        if (cnt[CNT_SPLITMV] &&

            AV_RN32A(&near_mv[1 + VP8_EDGE_TOP]) == AV_RN32A(&near_mv[1 + VP8_EDGE_TOPLEFT]))

            cnt[CNT_NEAREST] += 1;

        /* Swap near and nearest if necessary */

        if (cnt[CNT_NEAR] > cnt[CNT_NEAREST]) {

            FFSWAP(uint8_t,     cnt[CNT_NEAREST],     cnt[CNT_NEAR]);

            FFSWAP( VP56mv, near_mv[CNT_NEAREST], near_mv[CNT_NEAR]);

        }

        if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAREST]][1])) {

            if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAR]][2])) {

                /* Choose the best mv out of 0,0 and the nearest mv */

                clamp_mv(s, &mb->mv, &near_mv[CNT_ZERO + (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])]);

                cnt[CNT_SPLITMV] = ((mb_edge[VP8_EDGE_LEFT]->mode    == VP8_MVMODE_SPLIT) +

                                    (mb_edge[VP8_EDGE_TOP]->mode     == VP8_MVMODE_SPLIT)) * 2 +

                                    (mb_edge[VP8_EDGE_TOPLEFT]->mode == VP8_MVMODE_SPLIT);

                if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_SPLITMV]][3])) {

                    mb->mode = VP8_MVMODE_SPLIT;

                    mb->mv   = mb->bmv[decode_splitmvs(s, c, mb, layout) - 1];

                } else {

                    mb->mv.y  += read_mv_component(c, s->prob->mvc[0]);

                    mb->mv.x  += read_mv_component(c, s->prob->mvc[1]);

                    mb->bmv[0] = mb->mv;

                }

            } else {

                clamp_mv(s, &mb->mv, &near_mv[CNT_NEAR]);

                mb->bmv[0] = mb->mv;

            }

        } else {

            clamp_mv(s, &mb->mv, &near_mv[CNT_NEAREST]);

            mb->bmv[0] = mb->mv;

        }

    } else {

        mb->mode = VP8_MVMODE_ZERO;

        AV_ZERO32(&mb->mv);

        mb->bmv[0] = mb->mv;

    }

}


static void fw_cfg_initfn(Object *obj)

{

    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);

    FWCfgState *s = FW_CFG(obj);

    memory_region_init_io(&s->ctl_iomem, OBJECT(s), &fw_cfg_ctl_mem_ops, s,

                          "fwcfg.ctl", FW_CFG_SIZE);

    sysbus_init_mmio(sbd, &s->ctl_iomem);

    memory_region_init_io(&s->data_iomem, OBJECT(s), &fw_cfg_data_mem_ops, s,

                          "fwcfg.data", FW_CFG_DATA_SIZE);

    sysbus_init_mmio(sbd, &s->data_iomem);

    /* In case ctl and data overlap: */

    memory_region_init_io(&s->comb_iomem, OBJECT(s), &fw_cfg_comb_mem_ops, s,

                          "fwcfg", FW_CFG_SIZE);

}


int av_get_cpu_flags(void)

{

    int flags = cpu_flags;

    if (flags == -1) {

        flags = get_cpu_flags();

        cpu_flags = flags;

    }

    return flags;

}


static ExitStatus trans_fop_weww_0c(DisasContext *ctx, uint32_t insn,

                                    const DisasInsn *di)

{

    unsigned rt = extract32(insn, 0, 5);

    unsigned rb = extract32(insn, 16, 5);

    unsigned ra = extract32(insn, 21, 5);

    return do_fop_weww(ctx, rt, ra, rb, di->f_weww);

}


static int inc_refcounts(BlockDriverState *bs,

                         BdrvCheckResult *res,

                         void **refcount_table,

                         int64_t *refcount_table_size,

                         int64_t offset, int64_t size)

{

    BDRVQcow2State *s = bs->opaque;

    uint64_t start, last, cluster_offset, k, refcount;

    int ret;

    if (size <= 0) {

        return 0;

    }

    start = start_of_cluster(s, offset);

    last = start_of_cluster(s, offset + size - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size) {

        k = cluster_offset >> s->cluster_bits;

        if (k >= *refcount_table_size) {

            ret = realloc_refcount_array(s, refcount_table,

                                         refcount_table_size, k + 1);

            if (ret < 0) {

                res->check_errors++;

                return ret;

            }

        }

        refcount = s->get_refcount(*refcount_table, k);

        if (refcount == s->refcount_max) {

            fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64

                    "\n", cluster_offset);

            res->corruptions++;

            continue;

        }

        s->set_refcount(*refcount_table, k, refcount + 1);

    }

    return 0;

}


static int gdb_get_avr_reg(CPUState *env, uint8_t *mem_buf, int n)

{

    if (n < 32) {

#ifdef WORDS_BIGENDIAN

        stq_p(mem_buf, env->avr[n].u64[0]);

        stq_p(mem_buf+8, env->avr[n].u64[1]);

#else

        stq_p(mem_buf, env->avr[n].u64[1]);

        stq_p(mem_buf+8, env->avr[n].u64[0]);

#endif

        return 16;

    }

    if (n == 33) {

        stl_p(mem_buf, env->vscr);

        return 4;

    }

    if (n == 34) {

        stl_p(mem_buf, (uint32_t)env->spr[SPR_VRSAVE]);

        return 4;

    }

    return 0;

}


static void tpm_backend_worker_thread(gpointer data, gpointer user_data)

{

    TPMBackend *s = TPM_BACKEND(user_data);

    TPMBackendClass *k = TPM_BACKEND_GET_CLASS(s);

    assert(k->handle_request != NULL);

    k->handle_request(s, (TPMBackendCmd *)data);

    qemu_bh_schedule(s->bh);

}


static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,

                                         vorbis_floor_data *vfu, float *vec)

{

    vorbis_floor0 *vf = &vfu->t0;

    float *lsp = vf->lsp;

    uint_fast32_t amplitude;

    uint_fast32_t book_idx;

    uint_fast8_t blockflag = vc->modes[vc->mode_number].blockflag;

    amplitude = get_bits(&vc->gb, vf->amplitude_bits);

    if (amplitude > 0) {

        float last = 0;

        uint_fast16_t lsp_len = 0;

        uint_fast16_t idx;

        vorbis_codebook codebook;

        book_idx = get_bits(&vc->gb, ilog(vf->num_books));

        if (book_idx >= vf->num_books) {

            av_log(vc->avccontext, AV_LOG_ERROR,

                    "floor0 dec: booknumber too high!\n");

            book_idx =  0;

            //FIXME: look above

        }

        AV_DEBUG("floor0 dec: booknumber: %u\n", book_idx);

        codebook = vc->codebooks[vf->book_list[book_idx]];

        while (lsp_len<vf->order) {

            int vec_off;

            AV_DEBUG("floor0 dec: book dimension: %d\n", codebook.dimensions);

            AV_DEBUG("floor0 dec: maximum depth: %d\n", codebook.maxdepth);

            /* read temp vector */

            vec_off = get_vlc2(&vc->gb, codebook.vlc.table,

                               codebook.nb_bits, codebook.maxdepth)

                      * codebook.dimensions;

            AV_DEBUG("floor0 dec: vector offset: %d\n", vec_off);

            /* copy each vector component and add last to it */

            for (idx = 0; idx < codebook.dimensions; ++idx)

                lsp[lsp_len+idx] = codebook.codevectors[vec_off+idx] + last;

            last = lsp[lsp_len+idx-1]; /* set last to last vector component */

            lsp_len += codebook.dimensions;

        }

#ifdef V_DEBUG

        /* DEBUG: output lsp coeffs */

        {

            int idx;

            for (idx = 0; idx < lsp_len; ++idx)

                AV_DEBUG("floor0 dec: coeff at %d is %f\n", idx, lsp[idx]);

        }

#endif

        /* synthesize floor output vector */

        {

            int i;

            int order = vf->order;

            float wstep = M_PI / vf->bark_map_size;

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

                lsp[i] = 2.0f * cos(lsp[i]);

            AV_DEBUG("floor0 synth: map_size = %d; m = %d; wstep = %f\n",

                     vf->map_size, order, wstep);

            i = 0;

            while (i < vf->map_size[blockflag]) {

                int j, iter_cond = vf->map[blockflag][i];

                float p = 0.5f;

                float q = 0.5f;

                float two_cos_w = 2.0f * cos(wstep * iter_cond); // needed all times

                /* similar part for the q and p products */

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

                    q *= lsp[j]     - two_cos_w;

                    p *= lsp[j + 1] - two_cos_w;

                }

                if (j == order) { // even order

                    p *= p * (2.0f - two_cos_w);

                    q *= q * (2.0f + two_cos_w);

                } else { // odd order

                    q *= two_cos_w-lsp[j]; // one more time for q

                    /* final step and square */

                    p *= p * (4.f - two_cos_w * two_cos_w);

                    q *= q;

                }

                /* calculate linear floor value */

                {

                    q = exp((((amplitude*vf->amplitude_offset) /

                              (((1 << vf->amplitude_bits) - 1) * sqrt(p + q)))

                             - vf->amplitude_offset) * .11512925f);

                }

                /* fill vector */

                do {

                    vec[i] = q; ++i;

                } while (vf->map[blockflag][i] == iter_cond);

            }

        }

    } else {

        /* this channel is unused */

        return 1;

    }

    AV_DEBUG(" Floor0 decoded\n");

    return 0;

}


static void add_entry(TiffEncoderContext *s, enum TiffTags tag,

                      enum TiffTypes type, int count, const void *ptr_val)

{

    uint8_t *entries_ptr = s->entries + 12 * s->num_entries;

    assert(s->num_entries < TIFF_MAX_ENTRY);

    bytestream_put_le16(&entries_ptr, tag);

    bytestream_put_le16(&entries_ptr, type);

    bytestream_put_le32(&entries_ptr, count);

    if (type_sizes[type] * count <= 4) {

        tnput(&entries_ptr, count, ptr_val, type, 0);

    } else {

        bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);

        check_size(s, count * type_sizes2[type]);

        tnput(s->buf, count, ptr_val, type, 0);

    }

    s->num_entries++;

}


static int set_hwframe_ctx(AVCodecContext *ctx, AVBufferRef *hw_device_ctx)

{

    AVBufferRef *hw_frames_ref;

    AVHWFramesContext *frames_ctx = NULL;

    int err = 0;

    if (!(hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx))) {

        fprintf(stderr, "Failed to create VAAPI frame context.\n");

        return -1;

    }

    frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);

    frames_ctx->format    = AV_PIX_FMT_VAAPI;

    frames_ctx->sw_format = AV_PIX_FMT_NV12;

    frames_ctx->width     = width;

    frames_ctx->height    = height;

    frames_ctx->initial_pool_size = 20;

    if ((err = av_hwframe_ctx_init(hw_frames_ref)) < 0) {

        fprintf(stderr, "Failed to initialize VAAPI frame context."

                "Error code: %s\n",av_err2str(err));

        return err;

    }

    ctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);

    if (!ctx->hw_frames_ctx)

        err = AVERROR(ENOMEM);

    return err;

}


static int dnxhd_init_vlc(DNXHDContext *ctx, int cid)

{

    if (cid != ctx->cid) {

        int index;

        if ((index = ff_dnxhd_get_cid_table(cid)) < 0) {

            av_log(ctx->avctx, AV_LOG_ERROR, "unsupported cid %d\n", cid);

            return -1;

        }

        if (ff_dnxhd_cid_table[index].bit_depth != ctx->bit_depth) {

            av_log(ctx->avctx, AV_LOG_ERROR, "bit depth mismatches %d %d\n", ff_dnxhd_cid_table[index].bit_depth, ctx->bit_depth);

            return AVERROR_INVALIDDATA;

        }

        ctx->cid_table = &ff_dnxhd_cid_table[index];

        ff_free_vlc(&ctx->ac_vlc);

        ff_free_vlc(&ctx->dc_vlc);

        ff_free_vlc(&ctx->run_vlc);

        init_vlc(&ctx->ac_vlc, DNXHD_VLC_BITS, 257,

                 ctx->cid_table->ac_bits, 1, 1,

                 ctx->cid_table->ac_codes, 2, 2, 0);

        init_vlc(&ctx->dc_vlc, DNXHD_DC_VLC_BITS, ctx->bit_depth + 4,

                 ctx->cid_table->dc_bits, 1, 1,

                 ctx->cid_table->dc_codes, 1, 1, 0);

        init_vlc(&ctx->run_vlc, DNXHD_VLC_BITS, 62,

                 ctx->cid_table->run_bits, 1, 1,

                 ctx->cid_table->run_codes, 2, 2, 0);

        ff_init_scantable(ctx->dsp.idct_permutation, &ctx->scantable, ff_zigzag_direct);

        ctx->cid = cid;

    }

    return 0;

}


static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {

    AVCodecContext *vcodec = vstream->codec;

    switch(flv_codecid) {

        case FLV_CODECID_H263  : vcodec->codec_id = CODEC_ID_FLV1   ; break;

        case FLV_CODECID_REALH263: vcodec->codec_id = CODEC_ID_H263 ; break; // Really mean it this time

        case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;

        case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;

        case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;

        case FLV_CODECID_VP6A  :

            if(flv_codecid == FLV_CODECID_VP6A)

                vcodec->codec_id = CODEC_ID_VP6A;

            if(vcodec->extradata_size != 1) {

                vcodec->extradata_size = 1;

                vcodec->extradata = av_malloc(1);

            }

            vcodec->extradata[0] = avio_r8(s->pb);

            return 1; // 1 byte body size adjustment for flv_read_packet()

        case FLV_CODECID_H264:

            vcodec->codec_id = CODEC_ID_H264;

            return 3; // not 4, reading packet type will consume one byte

        case FLV_CODECID_MPEG4:

            vcodec->codec_id = CODEC_ID_MPEG4;

            return 3;

        default:

            av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);

            vcodec->codec_tag = flv_codecid;

    }

    return 0;

}


static void vc1_mspel_mc(uint8_t *dst, const uint8_t *src, int stride, int mode, int rnd)

{

    int i, j;

    uint8_t tmp[8*11], *tptr;

    int m, r;

    m = (mode & 3);

    r = rnd;

    src -= stride;

    tptr = tmp;

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

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

            tptr[i] = vc1_mspel_filter(src + i, 1, m, r);

        src += stride;

        tptr += 8;

    }

    r = 1 - rnd;

    m = (mode >> 2) & 3;

    tptr = tmp + 8;

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

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

            dst[i] = vc1_mspel_filter(tptr + i, 8, m, r);

        dst += stride;

        tptr += 8;

    }

}


static av_cold int bfi_decode_init(AVCodecContext *avctx)

{

    BFIContext *bfi = avctx->priv_data;

    avctx->pix_fmt  = AV_PIX_FMT_PAL8;

    bfi->dst        = av_mallocz(avctx->width * avctx->height);

    return 0;

}


static void vmxnet3_set_events(VMXNET3State *s, uint32_t val)

{

    uint32_t events;

    VMW_CBPRN("Setting events: 0x%x", val);

    events = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, ecr) | val;

    VMXNET3_WRITE_DRV_SHARED32(s->drv_shmem, ecr, events);

}


static int qemu_rbd_send_pipe(BDRVRBDState *s, RADOSCB *rcb)

{

    int ret = 0;

    while (1) {

        fd_set wfd;

        int fd = s->fds[RBD_FD_WRITE];

        /* send the op pointer to the qemu thread that is responsible

           for the aio/op completion. Must do it in a qemu thread context */

        ret = write(fd, (void *)&rcb, sizeof(rcb));

        if (ret >= 0) {

            break;

        }

        if (errno == EINTR) {

            continue;

        }

        if (errno != EAGAIN) {

            break;

        }

        FD_ZERO(&wfd);

        FD_SET(fd, &wfd);

        do {

            ret = select(fd + 1, NULL, &wfd, NULL, NULL);

        } while (ret < 0 && errno == EINTR);

    }

    return ret;

}


static void tcx_init(target_phys_addr_t addr, int vram_size, int width,

                     int height, int depth)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "SUNW,tcx");

    qdev_prop_set_taddr(dev, "addr", addr);

    qdev_prop_set_uint32(dev, "vram_size", vram_size);

    qdev_prop_set_uint16(dev, "width", width);

    qdev_prop_set_uint16(dev, "height", height);

    qdev_prop_set_uint16(dev, "depth", depth);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    /* 8-bit plane */

    sysbus_mmio_map(s, 0, addr + 0x00800000ULL);

    /* DAC */

    sysbus_mmio_map(s, 1, addr + 0x00200000ULL);

    /* TEC (dummy) */

    sysbus_mmio_map(s, 2, addr + 0x00700000ULL);

    /* THC 24 bit: NetBSD writes here even with 8-bit display: dummy */

    sysbus_mmio_map(s, 3, addr + 0x00301000ULL);

    if (depth == 24) {

        /* 24-bit plane */

        sysbus_mmio_map(s, 4, addr + 0x02000000ULL);

        /* Control plane */

        sysbus_mmio_map(s, 5, addr + 0x0a000000ULL);

    } else {

        /* THC 8 bit (dummy) */

        sysbus_mmio_map(s, 4, addr + 0x00300000ULL);

    }

}


int kvm_init_vcpu(CPUState *env)

{

    KVMState *s = kvm_state;

    long mmap_size;

    int ret;

    DPRINTF("kvm_init_vcpu\n");

    ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);

    if (ret < 0) {

        DPRINTF("kvm_create_vcpu failed\n");

        goto err;

    }

    env->kvm_fd = ret;

    env->kvm_state = s;

    mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);

    if (mmap_size < 0) {

        DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");

        goto err;

    }

    env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,

                        env->kvm_fd, 0);

    if (env->kvm_run == MAP_FAILED) {

        ret = -errno;

        DPRINTF("mmap'ing vcpu state failed\n");

        goto err;

    }

#ifdef KVM_CAP_COALESCED_MMIO

    if (s->coalesced_mmio && !s->coalesced_mmio_ring) {

        s->coalesced_mmio_ring =

            (void *)env->kvm_run + s->coalesced_mmio * PAGE_SIZE;

    }

#endif

    ret = kvm_arch_init_vcpu(env);

    if (ret == 0) {

        qemu_register_reset(kvm_reset_vcpu, env);

        kvm_arch_reset_vcpu(env);

    }

err:

    return ret;

}


static inline void RENAME(rgb24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, int width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    assert(src1==src2);

    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_RGB24);

#else

    int i;

    assert(src1==src2);

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

        int r= src1[3*i + 0];

        int g= src1[3*i + 1];

        int b= src1[3*i + 2];

        dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

        dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

    }

#endif

}


int net_init_tap(const NetClientOptions *opts, const char *name,

                 NetClientState *peer)

{

    const NetdevTapOptions *tap;

    int fd, vnet_hdr = 0, i = 0, queues;

    /* for the no-fd, no-helper case */

    const char *script = NULL; /* suppress wrong "uninit'd use" gcc warning */

    const char *downscript = NULL;

    const char *vhostfdname;

    char ifname[128];

    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP);

    tap = opts->tap;

    queues = tap->has_queues ? tap->queues : 1;

    vhostfdname = tap->has_vhostfd ? tap->vhostfd : NULL;

    /* QEMU vlans does not support multiqueue tap, in this case peer is set.

     * For -netdev, peer is always NULL. */

    if (peer && (tap->has_queues || tap->has_fds || tap->has_vhostfds)) {

        error_report("Multiqueue tap cannot be used with QEMU vlans");

        return -1;

    }

    if (tap->has_fd) {

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||

            tap->has_fds) {

            error_report("ifname=, script=, downscript=, vnet_hdr=, "

                         "helper=, queues=, and fds= are invalid with fd=");

            return -1;

        }

        fd = monitor_handle_fd_param(cur_mon, tap->fd);

        if (fd == -1) {

            return -1;

        }

        fcntl(fd, F_SETFL, O_NONBLOCK);

        vnet_hdr = tap_probe_vnet_hdr(fd);

        if (net_init_tap_one(tap, peer, "tap", name, NULL,

                             script, downscript,

                             vhostfdname, vnet_hdr, fd)) {

            return -1;

        }

    } else if (tap->has_fds) {

        char *fds[MAX_TAP_QUEUES];

        char *vhost_fds[MAX_TAP_QUEUES];

        int nfds, nvhosts;

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||

            tap->has_fd) {

            error_report("ifname=, script=, downscript=, vnet_hdr=, "

                         "helper=, queues=, and fd= are invalid with fds=");

            return -1;

        }

        nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES);

        if (tap->has_vhostfds) {

            nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES);

            if (nfds != nvhosts) {

                error_report("The number of fds passed does not match the "

                             "number of vhostfds passed");

                return -1;

            }

        }

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

            fd = monitor_handle_fd_param(cur_mon, fds[i]);

            if (fd == -1) {

                return -1;

            }

            fcntl(fd, F_SETFL, O_NONBLOCK);

            if (i == 0) {

                vnet_hdr = tap_probe_vnet_hdr(fd);

            } else if (vnet_hdr != tap_probe_vnet_hdr(fd)) {

                error_report("vnet_hdr not consistent across given tap fds");

                return -1;

            }

            if (net_init_tap_one(tap, peer, "tap", name, ifname,

                                 script, downscript,

                                 tap->has_vhostfds ? vhost_fds[i] : NULL,

                                 vnet_hdr, fd)) {

                return -1;

            }

        }

    } else if (tap->has_helper) {

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_queues || tap->has_fds) {

            error_report("ifname=, script=, downscript=, and vnet_hdr= "

                         "queues=, and fds= are invalid with helper=");

            return -1;

        }

        fd = net_bridge_run_helper(tap->helper, DEFAULT_BRIDGE_INTERFACE);

        if (fd == -1) {

            return -1;

        }

        fcntl(fd, F_SETFL, O_NONBLOCK);

        vnet_hdr = tap_probe_vnet_hdr(fd);

        if (net_init_tap_one(tap, peer, "bridge", name, ifname,

                             script, downscript, vhostfdname,

                             vnet_hdr, fd)) {

            return -1;

        }

    } else {

        script = tap->has_script ? tap->script : DEFAULT_NETWORK_SCRIPT;

        downscript = tap->has_downscript ? tap->downscript :

            DEFAULT_NETWORK_DOWN_SCRIPT;

        if (tap->has_ifname) {

            pstrcpy(ifname, sizeof ifname, tap->ifname);

        } else {

            ifname[0] = '\0';

        }

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

            fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script,

                              ifname, sizeof ifname, queues > 1);

            if (fd == -1) {

                return -1;

            }

            if (queues > 1 && i == 0 && !tap->has_ifname) {

                if (tap_fd_get_ifname(fd, ifname)) {

                    error_report("Fail to get ifname");

                    return -1;

                }

            }

            if (net_init_tap_one(tap, peer, "tap", name, ifname,

                                 i >= 1 ? "no" : script,

                                 i >= 1 ? "no" : downscript,

                                 vhostfdname, vnet_hdr, fd)) {

                return -1;

            }

        }

    }

    return 0;

}


static void spr_read_decr(DisasContext *ctx, int gprn, int sprn)

{

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_load_decr(cpu_gpr[gprn], cpu_env);

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static double get_scene_score(AVFilterContext *ctx, AVFilterBufferRef *picref)

{

    double ret = 0;

    SelectContext *select = ctx->priv;

    AVFilterBufferRef *prev_picref = select->prev_picref;

    if (prev_picref &&

        picref->video->h    == prev_picref->video->h &&

        picref->video->w    == prev_picref->video->w &&

        picref->linesize[0] == prev_picref->linesize[0]) {

        int x, y;

        int64_t sad = 0;

        double mafd, diff;

        uint8_t *p1 =      picref->data[0];

        uint8_t *p2 = prev_picref->data[0];

        const int linesize = picref->linesize[0];

        for (y = 0; y < picref->video->h; y += 8)

            for (x = 0; x < linesize; x += 8)

                sad += select->c.sad[1](select,

                                        p1 + y * linesize + x,

                                        p2 + y * linesize + x,

                                        linesize, 8);

        emms_c();

        mafd = sad / (picref->video->h * picref->video->w * 3);

        diff = fabs(mafd - select->prev_mafd);

        ret  = av_clipf(FFMIN(mafd, diff) / 100., 0, 1);

        select->prev_mafd = mafd;

        avfilter_unref_buffer(prev_picref);

    }

    select->prev_picref = avfilter_ref_buffer(picref, ~0);

    return ret;

}


static int do_req(int sockfd, AioContext *aio_context, SheepdogReq *hdr,

                  void *data, unsigned int *wlen, unsigned int *rlen)

{

    Coroutine *co;

    SheepdogReqCo srco = {

        .sockfd = sockfd,

        .aio_context = aio_context,

        .hdr = hdr,

        .data = data,

        .wlen = wlen,

        .rlen = rlen,

        .ret = 0,

        .finished = false,

    };

    if (qemu_in_coroutine()) {

        do_co_req(&srco);

    } else {

        co = qemu_coroutine_create(do_co_req);

        qemu_coroutine_enter(co, &srco);

        while (!srco.finished) {

            aio_poll(aio_context, true);

        }

    }

    return srco.ret;

}


static void gen_mtsrin(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    t0 = tcg_temp_new();

    tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 28);

    tcg_gen_andi_tl(t0, t0, 0xF);

    gen_helper_store_sr(cpu_env, t0, cpu_gpr[rD(ctx->opcode)]);

    tcg_temp_free(t0);

#endif

}


void s390_pci_iommu_enable(S390PCIBusDevice *pbdev)

{

    uint64_t size = pbdev->pal - pbdev->pba + 1;

    memory_region_init_iommu(&pbdev->iommu_mr, OBJECT(&pbdev->mr),

                             &s390_iommu_ops, "iommu-s390", size);

    memory_region_add_subregion(&pbdev->mr, pbdev->pba, &pbdev->iommu_mr);

    pbdev->iommu_enabled = true;

}


strdup(str)

	const char *str;

{

	char *bptr;

	bptr = (char *)malloc(strlen(str)+1);

	strcpy(bptr, str);

	return bptr;

}


static void gen_tlbli_6xx(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    gen_helper_6xx_tlbi(cpu_env, cpu_gpr[rB(ctx->opcode)]);

#endif

}


QemuOpts *qemu_opts_parse(QemuOptsList *list, const char *params,

                          int permit_abbrev)

{

    const char *firstname;

    char value[1024], *id = NULL;

    const char *p;

    QemuOpts *opts;

    assert(!permit_abbrev || list->implied_opt_name);

    firstname = permit_abbrev ? list->implied_opt_name : NULL;

    if (strncmp(params, "id=", 3) == 0) {

        get_opt_value(value, sizeof(value), params+3);

        id = qemu_strdup(value);

    } else if ((p = strstr(params, ",id=")) != NULL) {

        get_opt_value(value, sizeof(value), p+4);

        id = qemu_strdup(value);

    }

    opts = qemu_opts_create(list, id, 1);

    if (opts == NULL)

        return NULL;

    if (qemu_opts_do_parse(opts, params, firstname) != 0) {

        qemu_opts_del(opts);

        return NULL;

    }

    return opts;

}