uint64_t helper_sublv(CPUAlphaState *env, uint64_t op1, uint64_t op2)

{

    uint32_t res;

    res = op1 - op2;

    if (unlikely((op1 ^ op2) & (res ^ op1) & (1UL << 31))) {

        arith_excp(env, GETPC(), EXC_M_IOV, 0);

    }

    return res;

}


static int decode_mb_info(IVI45DecContext *ctx, IVIBandDesc *band,

                          IVITile *tile, AVCodecContext *avctx)

{

    int         x, y, mv_x, mv_y, mv_delta, offs, mb_offset,

                mv_scale, blks_per_mb;

    IVIMbInfo   *mb, *ref_mb;

    int         row_offset = band->mb_size * band->pitch;

    mb     = tile->mbs;

    ref_mb = tile->ref_mbs;

    offs   = tile->ypos * band->pitch + tile->xpos;

    if (!ref_mb &&

        ((band->qdelta_present && band->inherit_qdelta) || band->inherit_mv))

        return AVERROR_INVALIDDATA;

    if (tile->num_MBs != IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size)) {

        av_log(avctx, AV_LOG_ERROR, "Allocated tile size %d mismatches parameters %d\n",

               tile->num_MBs, IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size));

        return AVERROR_INVALIDDATA;

    }

    /* scale factor for motion vectors */

    mv_scale = (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3);

    mv_x = mv_y = 0;

    for (y = tile->ypos; y < (tile->ypos + tile->height); y += band->mb_size) {

        mb_offset = offs;

        for (x = tile->xpos; x < (tile->xpos + tile->width); x += band->mb_size) {

            mb->xpos     = x;

            mb->ypos     = y;

            mb->buf_offs = mb_offset;

            if (get_bits1(&ctx->gb)) {

                if (ctx->frame_type == FRAMETYPE_INTRA) {

                    av_log(avctx, AV_LOG_ERROR, "Empty macroblock in an INTRA picture!\n");

                    return -1;

                }

                mb->type = 1; /* empty macroblocks are always INTER */

                mb->cbp  = 0; /* all blocks are empty */

                mb->q_delta = 0;

                if (!band->plane && !band->band_num && (ctx->frame_flags & 8)) {

                    mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,

                                           IVI_VLC_BITS, 1);

                    mb->q_delta = IVI_TOSIGNED(mb->q_delta);

                }

                mb->mv_x = mb->mv_y = 0; /* no motion vector coded */

                if (band->inherit_mv){

                    /* motion vector inheritance */

                    if (mv_scale) {

                        mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);

                        mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);

                    } else {

                        mb->mv_x = ref_mb->mv_x;

                        mb->mv_y = ref_mb->mv_y;

                    }

                }

            } else {

                if (band->inherit_mv) {

                    mb->type = ref_mb->type; /* copy mb_type from corresponding reference mb */

                } else if (ctx->frame_type == FRAMETYPE_INTRA) {

                    mb->type = 0; /* mb_type is always INTRA for intra-frames */

                } else {

                    mb->type = get_bits1(&ctx->gb);

                }

                blks_per_mb = band->mb_size != band->blk_size ? 4 : 1;

                mb->cbp = get_bits(&ctx->gb, blks_per_mb);

                mb->q_delta = 0;

                if (band->qdelta_present) {

                    if (band->inherit_qdelta) {

                        if (ref_mb) mb->q_delta = ref_mb->q_delta;

                    } else if (mb->cbp || (!band->plane && !band->band_num &&

                                           (ctx->frame_flags & 8))) {

                        mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,

                                               IVI_VLC_BITS, 1);

                        mb->q_delta = IVI_TOSIGNED(mb->q_delta);

                    }

                }

                if (!mb->type) {

                    mb->mv_x = mb->mv_y = 0; /* there is no motion vector in intra-macroblocks */

                } else {

                    if (band->inherit_mv){

                        /* motion vector inheritance */

                        if (mv_scale) {

                            mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);

                            mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);

                        } else {

                            mb->mv_x = ref_mb->mv_x;

                            mb->mv_y = ref_mb->mv_y;

                        }

                    } else {

                        /* decode motion vector deltas */

                        mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,

                                            IVI_VLC_BITS, 1);

                        mv_y += IVI_TOSIGNED(mv_delta);

                        mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,

                                            IVI_VLC_BITS, 1);

                        mv_x += IVI_TOSIGNED(mv_delta);

                        mb->mv_x = mv_x;

                        mb->mv_y = mv_y;

                        if (mv_x < 0 || mv_y < 0) {

                            av_log(avctx, AV_LOG_ERROR, "Invalid MV %d %d\n",

                                   mv_x, mv_y);

                            mb->mv_x = mb->mv_y = 0;

                            return AVERROR_INVALIDDATA;

                        }

                    }

                }

            }

            mb++;

            if (ref_mb)

                ref_mb++;

            mb_offset += band->mb_size;

        }

        offs += row_offset;

    }

    align_get_bits(&ctx->gb);

    return 0;

}


static int huffman_decode(MPADecodeContext *s, GranuleDef *g,

                          int16_t *exponents, int end_pos)

{

    int s_index;

    int linbits, code, x, y, l, v, i, j, k, pos;

    int last_pos;

    VLC *vlc;

    /* low frequencies (called big values) */

    s_index = 0;

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

        j = g->region_size[i];

        if (j == 0)

            continue;

        /* select vlc table */

        k = g->table_select[i];

        l = mpa_huff_data[k][0];

        linbits = mpa_huff_data[k][1];

        vlc = &huff_vlc[l];

        if(!l){

            memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*j);

            s_index += 2*j;

            continue;

        }

        /* read huffcode and compute each couple */

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

            int exponent;

            if (get_bits_count(&s->gb) >= end_pos)

                break;

            y = get_vlc2(&s->gb, vlc->table, 7, 3);

            if(!y){

                g->sb_hybrid[s_index  ] =

                g->sb_hybrid[s_index+1] = 0;

                s_index += 2;

                continue;

            }

            x = y >> 4;

            y = y & 0x0f;

            exponent= exponents[s_index];

            dprintf("region=%d n=%d x=%d y=%d exp=%d\n",

                    i, g->region_size[i] - j, x, y, exponent);

            if (x) {

#if 0

                if (x == 15)

                    x += get_bitsz(&s->gb, linbits);

                v = l3_unscale(x, exponent);

#else

                if (x < 15){

                    v = expval_table[ exponent + 400 ][ x ];

//                      v = expval_table[ (exponent&3) + 400 ][ x ] >> FFMIN(0 - (exponent>>2), 31);

                }else{

                    x += get_bitsz(&s->gb, linbits);

                    v = l3_unscale(x, exponent);

                }

#endif

                if (get_bits1(&s->gb))

                    v = -v;

            } else {

                v = 0;

            }

            g->sb_hybrid[s_index++] = v;

            if (y) {

#if 0

                if (y == 15)

                    y += get_bitsz(&s->gb, linbits);

                v = l3_unscale(y, exponent);

#else

                if (y < 15){

                    v = expval_table[ exponent + 400 ][ y ];

                }else{

                    y += get_bitsz(&s->gb, linbits);

                    v = l3_unscale(y, exponent);

                }

#endif

                if (get_bits1(&s->gb))

                    v = -v;

            } else {

                v = 0;

            }

            g->sb_hybrid[s_index++] = v;

        }

    }

    /* high frequencies */

    vlc = &huff_quad_vlc[g->count1table_select];

    last_pos=0;

    while (s_index <= 572) {

        pos = get_bits_count(&s->gb);

        if (pos >= end_pos) {

            if (pos > end_pos && last_pos){

                /* some encoders generate an incorrect size for this

                   part. We must go back into the data */

                s_index -= 4;

                init_get_bits(&s->gb, s->gb.buffer + 4*(last_pos>>5), s->gb.size_in_bits - (last_pos&(~31)));

                skip_bits(&s->gb, last_pos&31);

            }

            break;

        }

        last_pos= pos;

        code = get_vlc2(&s->gb, vlc->table, vlc->bits, 1);

        dprintf("t=%d code=%d\n", g->count1table_select, code);

        g->sb_hybrid[s_index+0]=

        g->sb_hybrid[s_index+1]=

        g->sb_hybrid[s_index+2]=

        g->sb_hybrid[s_index+3]= 0;

        while(code){

            const static int idxtab[16]={3,3,2,2,1,1,1,1,0,0,0,0,0,0,0,0};

            int pos= s_index+idxtab[code];

            code ^= 8>>idxtab[code];

            v = exp_table[ exponents[pos] + 400];

            if(get_bits1(&s->gb))

                v = -v;

            g->sb_hybrid[pos] = v;

        }

        s_index+=4;

    }

    memset(&g->sb_hybrid[s_index], 0, sizeof(*g->sb_hybrid)*(576 - s_index));

    return 0;

}


static int vma_add_mapping(struct mm_struct *mm, abi_ulong start,

    abi_ulong end, abi_ulong flags)

{

    struct vm_area_struct *vma;

    if ((vma = qemu_mallocz(sizeof (*vma))) == NULL)

        return (-1);

    vma->vma_start = start;

    vma->vma_end = end;

    vma->vma_flags = flags;

    TAILQ_INSERT_TAIL(&mm->mm_mmap, vma, vma_link);

    mm->mm_count++;

    return (0);

}


static inline abi_long target_to_host_sockaddr(int fd, struct sockaddr *addr,

                                               abi_ulong target_addr,

                                               socklen_t len)

{

    const socklen_t unix_maxlen = sizeof (struct sockaddr_un);

    sa_family_t sa_family;

    struct target_sockaddr *target_saddr;

    if (fd_trans_target_to_host_addr(fd)) {

        return fd_trans_target_to_host_addr(fd)(addr, target_addr, len);

    }

    target_saddr = lock_user(VERIFY_READ, target_addr, len, 1);

    if (!target_saddr)

        return -TARGET_EFAULT;

    sa_family = tswap16(target_saddr->sa_family);

    /* Oops. The caller might send a incomplete sun_path; sun_path

     * must be terminated by \0 (see the manual page), but

     * unfortunately it is quite common to specify sockaddr_un

     * length as "strlen(x->sun_path)" while it should be

     * "strlen(...) + 1". We'll fix that here if needed.

     * Linux kernel has a similar feature.

     */

    if (sa_family == AF_UNIX) {

        if (len < unix_maxlen && len > 0) {

            char *cp = (char*)target_saddr;

            if ( cp[len-1] && !cp[len] )

                len++;

        }

        if (len > unix_maxlen)

            len = unix_maxlen;

    }

    memcpy(addr, target_saddr, len);

    addr->sa_family = sa_family;

    if (sa_family == AF_PACKET) {

	struct target_sockaddr_ll *lladdr;

	lladdr = (struct target_sockaddr_ll *)addr;

	lladdr->sll_ifindex = tswap32(lladdr->sll_ifindex);

	lladdr->sll_hatype = tswap16(lladdr->sll_hatype);

    }

    unlock_user(target_saddr, target_addr, 0);

    return 0;

}


int kvm_arch_put_registers(CPUState *cpu, int level)

{

    X86CPU *x86_cpu = X86_CPU(cpu);

    int ret;

    assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));

    if (level >= KVM_PUT_RESET_STATE) {

        ret = kvm_put_msr_feature_control(x86_cpu);

        if (ret < 0) {

            return ret;

        }

    }

    if (level == KVM_PUT_FULL_STATE) {

        /* We don't check for kvm_arch_set_tsc_khz() errors here,

         * because TSC frequency mismatch shouldn't abort migration,

         * unless the user explicitly asked for a more strict TSC

         * setting (e.g. using an explicit "tsc-freq" option).

         */

        kvm_arch_set_tsc_khz(cpu);

    }

    ret = kvm_getput_regs(x86_cpu, 1);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_xsave(x86_cpu);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_xcrs(x86_cpu);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_sregs(x86_cpu);

    if (ret < 0) {

        return ret;

    }

    /* must be before kvm_put_msrs */

    ret = kvm_inject_mce_oldstyle(x86_cpu);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_msrs(x86_cpu, level);

    if (ret < 0) {

        return ret;

    }

    if (level >= KVM_PUT_RESET_STATE) {

        ret = kvm_put_mp_state(x86_cpu);

        if (ret < 0) {

            return ret;

        }

    }

    ret = kvm_put_tscdeadline_msr(x86_cpu);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_vcpu_events(x86_cpu, level);

    if (ret < 0) {

        return ret;

    }

    ret = kvm_put_debugregs(x86_cpu);

    if (ret < 0) {

        return ret;

    }

    /* must be last */

    ret = kvm_guest_debug_workarounds(x86_cpu);

    if (ret < 0) {

        return ret;

    }

    return 0;

}


void ff_proresdsp_x86_init(ProresDSPContext *dsp)

{

#if ARCH_X86_64 && HAVE_YASM

    int flags = av_get_cpu_flags();

    if (flags & AV_CPU_FLAG_SSE2) {

        dsp->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

        dsp->idct_put = ff_prores_idct_put_10_sse2;

    }

    if (flags & AV_CPU_FLAG_SSE4) {

        dsp->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

        dsp->idct_put = ff_prores_idct_put_10_sse4;

    }

#if HAVE_AVX

    if (flags & AV_CPU_FLAG_AVX) {

        dsp->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

        dsp->idct_put = ff_prores_idct_put_10_avx;

    }

#endif /* HAVE_AVX */

#endif /* ARCH_X86_64 && HAVE_YASM */

}


void virtio_scsi_set_iothread(VirtIOSCSI *s, IOThread *iothread)

{

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    assert(!s->ctx);

    s->ctx = iothread_get_aio_context(vs->conf.iothread);

    /* Don't try if transport does not support notifiers. */

    if (!k->set_guest_notifiers || !k->ioeventfd_assign) {

        fprintf(stderr, "virtio-scsi: Failed to set iothread "

                   "(transport does not support notifiers)");

        exit(1);

    }

}


void OPPROTO op_decl_ECX(void)

{

    ECX = (uint32_t)(ECX - 1);

}


static void qapi_dealloc_type_str(Visitor *v, char **obj, const char *name,

                                  Error **errp)

{

    g_free(*obj);

}


static inline void pxa2xx_rtc_int_update(PXA2xxState *s)

{

    qemu_set_irq(s->pic[PXA2XX_PIC_RTCALARM], !!(s->rtsr & 0x2553));

}


static void kvm_s390_enable_cmma(KVMState *s)

{

    int rc;

    struct kvm_device_attr attr = {

        .group = KVM_S390_VM_MEM_CTRL,

        .attr = KVM_S390_VM_MEM_ENABLE_CMMA,

    };

    if (kvm_s390_check_enable_cmma(s) || kvm_s390_check_clear_cmma(s)) {

        return;

    }

    rc = kvm_vm_ioctl(s, KVM_SET_DEVICE_ATTR, &attr);

    if (!rc) {

        qemu_register_reset(kvm_s390_clear_cmma_callback, s);

    }

    trace_kvm_enable_cmma(rc);

}


int kvm_arch_init_vcpu(CPUX86State *env)

{

    struct {

        struct kvm_cpuid2 cpuid;

        struct kvm_cpuid_entry2 entries[100];

    } QEMU_PACKED cpuid_data;

    KVMState *s = env->kvm_state;

    uint32_t limit, i, j, cpuid_i;

    uint32_t unused;

    struct kvm_cpuid_entry2 *c;

    uint32_t signature[3];

    int r;

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

    j = env->cpuid_ext_features & CPUID_EXT_TSC_DEADLINE_TIMER;

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

    if (j && kvm_irqchip_in_kernel() &&

        kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {

        env->cpuid_ext_features |= CPUID_EXT_TSC_DEADLINE_TIMER;

    }

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

                                                             0, R_EDX);

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

                                                             0, R_ECX);

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

                                                             0, R_EDX);

    cpuid_i = 0;

    /* Paravirtualization CPUIDs */

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

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

    c->function = KVM_CPUID_SIGNATURE;

    if (!hyperv_enabled()) {

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

        c->eax = 0;

    } else {

        memcpy(signature, "Microsoft Hv", 12);

        c->eax = HYPERV_CPUID_MIN;

    }

    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(s, KVM_CPUID_FEATURES, 0, R_EAX);

    if (hyperv_enabled()) {

        memcpy(signature, "Hv#1\0\0\0\0\0\0\0\0", 12);

        c->eax = signature[0];

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

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

        c->function = HYPERV_CPUID_VERSION;

        c->eax = 0x00001bbc;

        c->ebx = 0x00060001;

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

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

        c->function = HYPERV_CPUID_FEATURES;

        if (hyperv_relaxed_timing_enabled()) {

            c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;

        }

        if (hyperv_vapic_recommended()) {

            c->eax |= HV_X64_MSR_HYPERCALL_AVAILABLE;

            c->eax |= HV_X64_MSR_APIC_ACCESS_AVAILABLE;

        }

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

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

        c->function = HYPERV_CPUID_ENLIGHTMENT_INFO;

        if (hyperv_relaxed_timing_enabled()) {

            c->eax |= HV_X64_RELAXED_TIMING_RECOMMENDED;

        }

        if (hyperv_vapic_recommended()) {

            c->eax |= HV_X64_APIC_ACCESS_RECOMMENDED;

        }

        c->ebx = hyperv_get_spinlock_retries();

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

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

        c->function = HYPERV_CPUID_IMPLEMENT_LIMITS;

        c->eax = 0x40;

        c->ebx = 0x40;

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

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

        c->function = KVM_CPUID_SIGNATURE_NEXT;

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

        c->eax = 0;

        c->ebx = signature[0];

        c->ecx = signature[1];

        c->edx = signature[2];

    }

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

    has_msr_pv_eoi_en = c->eax & (1 << KVM_FEATURE_PV_EOI);

    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++) {

                if (i == 0xd && j == 64) {

                    break;

                }

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

                    continue;

                }

                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(s, 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);

    cpuid_data.cpuid.padding = 0;

    r = kvm_vcpu_ioctl(env, KVM_SET_CPUID2, &cpuid_data);

    if (r) {

        return r;

    }

    r = kvm_check_extension(env->kvm_state, KVM_CAP_TSC_CONTROL);

    if (r && env->tsc_khz) {

        r = kvm_vcpu_ioctl(env, KVM_SET_TSC_KHZ, env->tsc_khz);

        if (r < 0) {

            fprintf(stderr, "KVM_SET_TSC_KHZ failed\n");

            return r;

        }

    }

    if (kvm_has_xsave()) {

        env->kvm_xsave_buf = qemu_memalign(4096, sizeof(struct kvm_xsave));

    }

    return 0;

}


void qmp_blockdev_snapshot(const char *node, const char *overlay,

                           Error **errp)

{

    BlockdevSnapshot snapshot_data = {

        .node = (char *) node,

        .overlay = (char *) overlay

    };

    TransactionAction action = {

        .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,

        .u.blockdev_snapshot = &snapshot_data,

    };

    blockdev_do_action(&action, errp);

}


CPUX86State *cpu_x86_init_user(const char *cpu_model)

{

    Error *error = NULL;

    X86CPU *cpu;

    cpu = cpu_x86_create(cpu_model, NULL, &error);

    if (error) {

        goto out;

    }

    object_property_set_bool(OBJECT(cpu), true, "realized", &error);

out:

    if (error) {

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

        error_free(error);

        if (cpu != NULL) {

            object_unref(OBJECT(cpu));

        }

        return NULL;

    }

    return &cpu->env;

}


static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,

                                 Error **errp)

{

    uint32_t flags;

    bool fixedNewstyle = false;

    bool no_zeroes = false;

    /* Client sends:

        [ 0 ..   3]   client flags

       Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   NBD option

        [12 ..  15]   Data length

        ...           Rest of request

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   Second NBD option

        [12 ..  15]   Data length

        ...           Rest of request

    */

    if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {

        error_prepend(errp, "read failed: ");

        return -EIO;

    }

    be32_to_cpus(&flags);

    trace_nbd_negotiate_options_flags(flags);

    if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {

        fixedNewstyle = true;

        flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;

    }

    if (flags & NBD_FLAG_C_NO_ZEROES) {

        no_zeroes = true;

        flags &= ~NBD_FLAG_C_NO_ZEROES;

    }

    if (flags != 0) {

        error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);

        return -EINVAL;

    }

    while (1) {

        int ret;

        uint32_t option, length;

        uint64_t magic;

        if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        magic = be64_to_cpu(magic);

        trace_nbd_negotiate_options_check_magic(magic);

        if (magic != NBD_OPTS_MAGIC) {

            error_setg(errp, "Bad magic received");

            return -EINVAL;

        }

        if (nbd_read(client->ioc, &option,

                     sizeof(option), errp) < 0) {

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        option = be32_to_cpu(option);

        if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        length = be32_to_cpu(length);

        trace_nbd_negotiate_options_check_option(option,

                                                 nbd_opt_lookup(option));

        if (client->tlscreds &&

            client->ioc == (QIOChannel *)client->sioc) {

            QIOChannel *tioc;

            if (!fixedNewstyle) {

                error_setg(errp, "Unsupported option 0x%" PRIx32, option);

                return -EINVAL;

            }

            switch (option) {

            case NBD_OPT_STARTTLS:

                tioc = nbd_negotiate_handle_starttls(client, length, errp);

                if (!tioc) {

                    return -EIO;

                }

                object_unref(OBJECT(client->ioc));

                client->ioc = QIO_CHANNEL(tioc);

                break;

            case NBD_OPT_EXPORT_NAME:

                /* No way to return an error to client, so drop connection */

                error_setg(errp, "Option 0x%x not permitted before TLS",

                           option);

                return -EINVAL;

            default:

                if (nbd_drop(client->ioc, length, errp) < 0) {

                    return -EIO;

                }

                ret = nbd_negotiate_send_rep_err(client->ioc,

                                                 NBD_REP_ERR_TLS_REQD,

                                                 option, errp,

                                                 "Option 0x%" PRIx32

                                                 "not permitted before TLS",

                                                 option);

                if (ret < 0) {

                    return ret;

                }

                /* Let the client keep trying, unless they asked to

                 * quit. In this mode, we've already sent an error, so

                 * we can't ack the abort.  */

                if (option == NBD_OPT_ABORT) {

                    return 1;

                }

                break;

            }

        } else if (fixedNewstyle) {

            switch (option) {

            case NBD_OPT_LIST:

                ret = nbd_negotiate_handle_list(client, length, errp);

                if (ret < 0) {

                    return ret;

                }

                break;

            case NBD_OPT_ABORT:

                /* NBD spec says we must try to reply before

                 * disconnecting, but that we must also tolerate

                 * guests that don't wait for our reply. */

                nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, option, NULL);

                return 1;

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client, length,

                                                        myflags, no_zeroes,

                                                        errp);

            case NBD_OPT_INFO:

            case NBD_OPT_GO:

                ret = nbd_negotiate_handle_info(client, length, option,

                                                myflags, errp);

                if (ret == 1) {

                    assert(option == NBD_OPT_GO);

                    return 0;

                }

                if (ret) {

                    return ret;

                }

                break;

            case NBD_OPT_STARTTLS:

                if (nbd_drop(client->ioc, length, errp) < 0) {

                    return -EIO;

                }

                if (client->tlscreds) {

                    ret = nbd_negotiate_send_rep_err(client->ioc,

                                                     NBD_REP_ERR_INVALID,

                                                     option, errp,

                                                     "TLS already enabled");

                } else {

                    ret = nbd_negotiate_send_rep_err(client->ioc,

                                                     NBD_REP_ERR_POLICY,

                                                     option, errp,

                                                     "TLS not configured");

                }

                if (ret < 0) {

                    return ret;

                }

                break;

            default:

                if (nbd_drop(client->ioc, length, errp) < 0) {

                    return -EIO;

                }

                ret = nbd_negotiate_send_rep_err(client->ioc,

                                                 NBD_REP_ERR_UNSUP,

                                                 option, errp,

                                                 "Unsupported option 0x%"

                                                 PRIx32 " (%s)", option,

                                                 nbd_opt_lookup(option));

                if (ret < 0) {

                    return ret;

                }

                break;

            }

        } else {

            /*

             * If broken new-style we should drop the connection

             * for anything except NBD_OPT_EXPORT_NAME

             */

            switch (option) {

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client, length,

                                                        myflags, no_zeroes,

                                                        errp);

            default:

                error_setg(errp, "Unsupported option 0x%" PRIx32 " (%s)",

                           option, nbd_opt_lookup(option));

                return -EINVAL;

            }

        }

    }

}


static void print_all_libs_info(int flags, int level)

{

    PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);

    PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);

    PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);

    PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);

    PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);

    PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);

    PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);

    PRINT_LIB_INFO(swresample,SWRESAMPLE,  flags, level);

#if CONFIG_POSTPROC

    PRINT_LIB_INFO(postproc, POSTPROC, flags, level);

#endif

}


static uint32_t sd_wpbits(SDState *sd, uint64_t addr)

{

    uint32_t i, wpnum;

    uint32_t ret = 0;

    wpnum = addr >> (HWBLOCK_SHIFT + SECTOR_SHIFT + WPGROUP_SHIFT);

    for (i = 0; i < 32; i ++, wpnum ++, addr += WPGROUP_SIZE)

        if (addr < sd->size && sd->wp_groups[wpnum])

            ret |= (1 << i);

    return ret;

}


static TileExcp decode_x0(DisasContext *dc, tilegx_bundle_bits bundle)

{

    unsigned opc = get_Opcode_X0(bundle);

    unsigned dest = get_Dest_X0(bundle);

    unsigned srca = get_SrcA_X0(bundle);

    unsigned ext, srcb, bfs, bfe;

    int imm;

    switch (opc) {

    case RRR_0_OPCODE_X0:

        ext = get_RRROpcodeExtension_X0(bundle);

        if (ext == UNARY_RRR_0_OPCODE_X0) {

            ext = get_UnaryOpcodeExtension_X0(bundle);

            return gen_rr_opcode(dc, OE(opc, ext, X0), dest, srca);

        }

        srcb = get_SrcB_X0(bundle);

        return gen_rrr_opcode(dc, OE(opc, ext, X0), dest, srca, srcb);

    case SHIFT_OPCODE_X0:

        ext = get_ShiftOpcodeExtension_X0(bundle);

        imm = get_ShAmt_X0(bundle);

        return gen_rri_opcode(dc, OE(opc, ext, X0), dest, srca, imm);

    case IMM8_OPCODE_X0:

        ext = get_Imm8OpcodeExtension_X0(bundle);

        imm = (int8_t)get_Imm8_X0(bundle);

        return gen_rri_opcode(dc, OE(opc, ext, X0), dest, srca, imm);

    case BF_OPCODE_X0:

        ext = get_BFOpcodeExtension_X0(bundle);

        bfs = get_BFStart_X0(bundle);

        bfe = get_BFEnd_X0(bundle);

        return gen_bf_opcode_x0(dc, ext, dest, srca, bfs, bfe);

    case ADDLI_OPCODE_X0:

    case SHL16INSLI_OPCODE_X0:

    case ADDXLI_OPCODE_X0:

        imm = (int16_t)get_Imm16_X0(bundle);

        return gen_rri_opcode(dc, OE(opc, 0, X0), dest, srca, imm);

    default:

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    }

}


static int alloc_f(int argc, char **argv)

{

    int64_t offset;

    int nb_sectors, remaining;

    char s1[64];

    int num, sum_alloc;

    int ret;

    offset = cvtnum(argv[1]);

    if (offset & 0x1ff) {

        printf("offset %" PRId64 " is not sector aligned\n",

               offset);

        return 0;

    }

    if (argc == 3) {

        nb_sectors = cvtnum(argv[2]);

    } else {

        nb_sectors = 1;

    }

    remaining = nb_sectors;

    sum_alloc = 0;

    while (remaining) {

        ret = bdrv_is_allocated(bs, offset >> 9, nb_sectors, &num);

        remaining -= num;

        if (ret) {

            sum_alloc += num;

        }

    }

    cvtstr(offset, s1, sizeof(s1));

    printf("%d/%d sectors allocated at offset %s\n",

           sum_alloc, nb_sectors, s1);

    return 0;

}


static void scsi_dma_complete_noio(SCSIDiskReq *r, int ret)

{

    assert(r->req.aiocb == NULL);

    if (r->req.io_canceled) {

        scsi_req_cancel_complete(&r->req);

        goto done;

    }

    if (ret < 0) {

        if (scsi_handle_rw_error(r, -ret, false)) {

            goto done;

        }

    }

    r->sector += r->sector_count;

    r->sector_count = 0;

    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {

        scsi_write_do_fua(r);

        return;

    } else {

        scsi_req_complete(&r->req, GOOD);

    }

done:

    scsi_req_unref(&r->req);

}


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

{

    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);

    uc->init           = usb_keyboard_initfn;

    uc->product_desc   = "QEMU USB Keyboard";

    uc->usb_desc       = &desc_keyboard;

    uc->handle_packet  = usb_generic_handle_packet;

    uc->handle_reset   = usb_hid_handle_reset;

    uc->handle_control = usb_hid_handle_control;

    uc->handle_data    = usb_hid_handle_data;

    uc->handle_destroy = usb_hid_handle_destroy;

}


static void omap_sti_fifo_write(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

    struct omap_sti_s *s = (struct omap_sti_s *) opaque;

    int offset = addr - s->channel_base;

    int ch = offset >> 6;

    uint8_t byte = value;

    if (ch == STI_TRACE_CONTROL_CHANNEL) {

        /* Flush channel value.  */

        qemu_chr_write(s->chr, "\r", 1);

    } else if (ch == STI_TRACE_CONSOLE_CHANNEL || 1) {

        if (value == 0xc0 || value == 0xc3) {

            /* Open channel ch.  */

        } else if (value == 0x00)

            qemu_chr_write(s->chr, "\n", 1);

        else

            qemu_chr_write(s->chr, &byte, 1);

    }

}


static void tgen_andi(TCGContext *s, TCGType type, TCGReg dest, uint64_t val)

{

    static const S390Opcode ni_insns[4] = {

        RI_NILL, RI_NILH, RI_NIHL, RI_NIHH

    };

    static const S390Opcode nif_insns[2] = {

        RIL_NILF, RIL_NIHF

    };

    uint64_t valid = (type == TCG_TYPE_I32 ? 0xffffffffull : -1ull);

    int i;

    /* Look for the zero-extensions.  */

    if ((val & valid) == 0xffffffff) {

        tgen_ext32u(s, dest, dest);

        return;

    }

    if (facilities & FACILITY_EXT_IMM) {

        if ((val & valid) == 0xff) {

            tgen_ext8u(s, TCG_TYPE_I64, dest, dest);

            return;

        }

        if ((val & valid) == 0xffff) {

            tgen_ext16u(s, TCG_TYPE_I64, dest, dest);

            return;

        }

    }

    /* Try all 32-bit insns that can perform it in one go.  */

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

        tcg_target_ulong mask = ~(0xffffull << i*16);

        if (((val | ~valid) & mask) == mask) {

            tcg_out_insn_RI(s, ni_insns[i], dest, val >> i*16);

            return;

        }

    }

    /* Try all 48-bit insns that can perform it in one go.  */

    if (facilities & FACILITY_EXT_IMM) {

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

            tcg_target_ulong mask = ~(0xffffffffull << i*32);

            if (((val | ~valid) & mask) == mask) {

                tcg_out_insn_RIL(s, nif_insns[i], dest, val >> i*32);

                return;

            }

        }

    }

    if ((facilities & FACILITY_GEN_INST_EXT) && risbg_mask(val)) {

        tgen_andi_risbg(s, dest, dest, val);

        return;

    }

    /* Fall back to loading the constant.  */

    tcg_out_movi(s, type, TCG_TMP0, val);

    if (type == TCG_TYPE_I32) {

        tcg_out_insn(s, RR, NR, dest, TCG_TMP0);

    } else {

        tcg_out_insn(s, RRE, NGR, dest, TCG_TMP0);

    }

}


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

{

    int pagesize;

    NANDFlashState *s = NAND(dev);

    s->buswidth = nand_flash_ids[s->chip_id].width >> 3;

    s->size = nand_flash_ids[s->chip_id].size << 20;

    if (nand_flash_ids[s->chip_id].options & NAND_SAMSUNG_LP) {

        s->page_shift = 11;

        s->erase_shift = 6;

    } else {

        s->page_shift = nand_flash_ids[s->chip_id].page_shift;

        s->erase_shift = nand_flash_ids[s->chip_id].erase_shift;

    }

    switch (1 << s->page_shift) {

    case 256:

        nand_init_256(s);

        break;

    case 512:

        nand_init_512(s);

        break;

    case 2048:

        nand_init_2048(s);

        break;

    default:

        error_setg(errp, "Unsupported NAND block size %#x\n",

                   1 << s->page_shift);

        return;

    }

    pagesize = 1 << s->oob_shift;

    s->mem_oob = 1;

    if (s->bdrv) {

        if (bdrv_is_read_only(s->bdrv)) {

            error_setg(errp, "Can't use a read-only drive");

            return;

        }

        if (bdrv_getlength(s->bdrv) >=

                (s->pages << s->page_shift) + (s->pages << s->oob_shift)) {

            pagesize = 0;

            s->mem_oob = 0;

        }

    } else {

        pagesize += 1 << s->page_shift;

    }

    if (pagesize) {

        s->storage = (uint8_t *) memset(g_malloc(s->pages * pagesize),

                        0xff, s->pages * pagesize);

    }

    /* Give s->ioaddr a sane value in case we save state before it is used. */

    s->ioaddr = s->io;

}


static inline void gen_intermediate_code_internal(ARMCPU *cpu,

                                                  TranslationBlock *tb,

                                                  bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUARMState *env = &cpu->env;

    DisasContext dc1, *dc = &dc1;

    CPUBreakpoint *bp;

    int j, lj;

    target_ulong pc_start;

    target_ulong next_page_start;

    int num_insns;

    int max_insns;

    /* generate intermediate code */

    /* The A64 decoder has its own top level loop, because it doesn't need

     * the A32/T32 complexity to do with conditional execution/IT blocks/etc.

     */

    if (ARM_TBFLAG_AARCH64_STATE(tb->flags)) {

        gen_intermediate_code_internal_a64(cpu, tb, search_pc);

        return;

    }

    pc_start = tb->pc;

    dc->tb = tb;

    dc->is_jmp = DISAS_NEXT;

    dc->pc = pc_start;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->condjmp = 0;

    dc->aarch64 = 0;

    dc->el3_is_aa64 = arm_el_is_aa64(env, 3);

    dc->thumb = ARM_TBFLAG_THUMB(tb->flags);

    dc->bswap_code = ARM_TBFLAG_BSWAP_CODE(tb->flags);

    dc->condexec_mask = (ARM_TBFLAG_CONDEXEC(tb->flags) & 0xf) << 1;

    dc->condexec_cond = ARM_TBFLAG_CONDEXEC(tb->flags) >> 4;

    dc->mmu_idx = ARM_TBFLAG_MMUIDX(tb->flags);

    dc->current_el = arm_mmu_idx_to_el(dc->mmu_idx);

#if !defined(CONFIG_USER_ONLY)

    dc->user = (dc->current_el == 0);

#endif

    dc->ns = ARM_TBFLAG_NS(tb->flags);

    dc->cpacr_fpen = ARM_TBFLAG_CPACR_FPEN(tb->flags);

    dc->vfp_enabled = ARM_TBFLAG_VFPEN(tb->flags);

    dc->vec_len = ARM_TBFLAG_VECLEN(tb->flags);

    dc->vec_stride = ARM_TBFLAG_VECSTRIDE(tb->flags);

    dc->c15_cpar = ARM_TBFLAG_XSCALE_CPAR(tb->flags);

    dc->cp_regs = cpu->cp_regs;

    dc->features = env->features;

    /* Single step state. The code-generation logic here is:

     *  SS_ACTIVE == 0:

     *   generate code with no special handling for single-stepping (except

     *   that anything that can make us go to SS_ACTIVE == 1 must end the TB;

     *   this happens anyway because those changes are all system register or

     *   PSTATE writes).

     *  SS_ACTIVE == 1, PSTATE.SS == 1: (active-not-pending)

     *   emit code for one insn

     *   emit code to clear PSTATE.SS

     *   emit code to generate software step exception for completed step

     *   end TB (as usual for having generated an exception)

     *  SS_ACTIVE == 1, PSTATE.SS == 0: (active-pending)

     *   emit code to generate a software step exception

     *   end the TB

     */

    dc->ss_active = ARM_TBFLAG_SS_ACTIVE(tb->flags);

    dc->pstate_ss = ARM_TBFLAG_PSTATE_SS(tb->flags);

    dc->is_ldex = false;

    dc->ss_same_el = false; /* Can't be true since EL_d must be AArch64 */

    cpu_F0s = tcg_temp_new_i32();

    cpu_F1s = tcg_temp_new_i32();

    cpu_F0d = tcg_temp_new_i64();

    cpu_F1d = tcg_temp_new_i64();

    cpu_V0 = cpu_F0d;

    cpu_V1 = cpu_F1d;

    /* FIXME: cpu_M0 can probably be the same as cpu_V0.  */

    cpu_M0 = tcg_temp_new_i64();

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    lj = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_tb_start(tb);

    tcg_clear_temp_count();

    /* A note on handling of the condexec (IT) bits:

     *

     * We want to avoid the overhead of having to write the updated condexec

     * bits back to the CPUARMState for every instruction in an IT block. So:

     * (1) if the condexec bits are not already zero then we write

     * zero back into the CPUARMState now. This avoids complications trying

     * to do it at the end of the block. (For example if we don't do this

     * it's hard to identify whether we can safely skip writing condexec

     * at the end of the TB, which we definitely want to do for the case

     * where a TB doesn't do anything with the IT state at all.)

     * (2) if we are going to leave the TB then we call gen_set_condexec()

     * which will write the correct value into CPUARMState if zero is wrong.

     * This is done both for leaving the TB at the end, and for leaving

     * it because of an exception we know will happen, which is done in

     * gen_exception_insn(). The latter is necessary because we need to

     * leave the TB with the PC/IT state just prior to execution of the

     * instruction which caused the exception.

     * (3) if we leave the TB unexpectedly (eg a data abort on a load)

     * then the CPUARMState will be wrong and we need to reset it.

     * This is handled in the same way as restoration of the

     * PC in these situations: we will be called again with search_pc=1

     * and generate a mapping of the condexec bits for each PC in

     * gen_opc_condexec_bits[]. restore_state_to_opc() then uses

     * this to restore the condexec bits.

     *

     * Note that there are no instructions which can read the condexec

     * bits, and none which can write non-static values to them, so

     * we don't need to care about whether CPUARMState is correct in the

     * middle of a TB.

     */

    /* Reset the conditional execution bits immediately. This avoids

       complications trying to do it at the end of the block.  */

    if (dc->condexec_mask || dc->condexec_cond)

      {

        TCGv_i32 tmp = tcg_temp_new_i32();

        tcg_gen_movi_i32(tmp, 0);

        store_cpu_field(tmp, condexec_bits);

      }

    do {

#ifdef CONFIG_USER_ONLY

        /* Intercept jump to the magic kernel page.  */

        if (dc->pc >= 0xffff0000) {

            /* We always get here via a jump, so know we are not in a

               conditional execution block.  */

            gen_exception_internal(EXCP_KERNEL_TRAP);

            dc->is_jmp = DISAS_UPDATE;

            break;

        }

#else

        if (dc->pc >= 0xfffffff0 && arm_dc_feature(dc, ARM_FEATURE_M)) {

            /* We always get here via a jump, so know we are not in a

               conditional execution block.  */

            gen_exception_internal(EXCP_EXCEPTION_EXIT);

            dc->is_jmp = DISAS_UPDATE;

            break;

        }

#endif

        if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) {

            QTAILQ_FOREACH(bp, &cs->breakpoints, entry) {

                if (bp->pc == dc->pc) {

                    gen_exception_internal_insn(dc, 0, EXCP_DEBUG);

                    /* Advance PC so that clearing the breakpoint will

                       invalidate this TB.  */

                    dc->pc += 2;

                    goto done_generating;

                }

            }

        }

        if (search_pc) {

            j = tcg_op_buf_count();

            if (lj < j) {

                lj++;

                while (lj < j)

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

            }

            tcg_ctx.gen_opc_pc[lj] = dc->pc;

            gen_opc_condexec_bits[lj] = (dc->condexec_cond << 4) | (dc->condexec_mask >> 1);

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = num_insns;

        }

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))

            gen_io_start();

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

            tcg_gen_debug_insn_start(dc->pc);

        }

        if (dc->ss_active && !dc->pstate_ss) {

            /* Singlestep state is Active-pending.

             * If we're in this state at the start of a TB then either

             *  a) we just took an exception to an EL which is being debugged

             *     and this is the first insn in the exception handler

             *  b) debug exceptions were masked and we just unmasked them

             *     without changing EL (eg by clearing PSTATE.D)

             * In either case we're going to take a swstep exception in the

             * "did not step an insn" case, and so the syndrome ISV and EX

             * bits should be zero.

             */

            assert(num_insns == 0);

            gen_exception(EXCP_UDEF, syn_swstep(dc->ss_same_el, 0, 0),

                          default_exception_el(dc));

            goto done_generating;

        }

        if (dc->thumb) {

            disas_thumb_insn(env, dc);

            if (dc->condexec_mask) {

                dc->condexec_cond = (dc->condexec_cond & 0xe)

                                   | ((dc->condexec_mask >> 4) & 1);

                dc->condexec_mask = (dc->condexec_mask << 1) & 0x1f;

                if (dc->condexec_mask == 0) {

                    dc->condexec_cond = 0;

                }

            }

        } else {

            unsigned int insn = arm_ldl_code(env, dc->pc, dc->bswap_code);

            dc->pc += 4;

            disas_arm_insn(dc, insn);

        }

        if (dc->condjmp && !dc->is_jmp) {

            gen_set_label(dc->condlabel);

            dc->condjmp = 0;

        }

        if (tcg_check_temp_count()) {

            fprintf(stderr, "TCG temporary leak before "TARGET_FMT_lx"\n",

                    dc->pc);

        }

        /* Translation stops when a conditional branch is encountered.

         * Otherwise the subsequent code could get translated several times.

         * Also stop translation when a page boundary is reached.  This

         * ensures prefetch aborts occur at the right place.  */

        num_insns ++;

    } while (!dc->is_jmp && !tcg_op_buf_full() &&

             !cs->singlestep_enabled &&

             !singlestep &&

             !dc->ss_active &&

             dc->pc < next_page_start &&

             num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        if (dc->condjmp) {

            /* FIXME:  This can theoretically happen with self-modifying

               code.  */

            cpu_abort(cs, "IO on conditional branch instruction");

        }

        gen_io_end();

    }

    /* At this stage dc->condjmp will only be set when the skipped

       instruction was a conditional branch or trap, and the PC has

       already been written.  */

    if (unlikely(cs->singlestep_enabled || dc->ss_active)) {

        /* Make sure the pc is updated, and raise a debug exception.  */

        if (dc->condjmp) {

            gen_set_condexec(dc);

            if (dc->is_jmp == DISAS_SWI) {

                gen_ss_advance(dc);

                gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                              default_exception_el(dc));

            } else if (dc->is_jmp == DISAS_HVC) {

                gen_ss_advance(dc);

                gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            } else if (dc->is_jmp == DISAS_SMC) {

                gen_ss_advance(dc);

                gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            } else if (dc->ss_active) {

                gen_step_complete_exception(dc);

            } else {

                gen_exception_internal(EXCP_DEBUG);

            }

            gen_set_label(dc->condlabel);

        }

        if (dc->condjmp || !dc->is_jmp) {

            gen_set_pc_im(dc, dc->pc);

            dc->condjmp = 0;

        }

        gen_set_condexec(dc);

        if (dc->is_jmp == DISAS_SWI && !dc->condjmp) {

            gen_ss_advance(dc);

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

        } else if (dc->is_jmp == DISAS_HVC && !dc->condjmp) {

            gen_ss_advance(dc);

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

        } else if (dc->is_jmp == DISAS_SMC && !dc->condjmp) {

            gen_ss_advance(dc);

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

        } else if (dc->ss_active) {

            gen_step_complete_exception(dc);

        } else {

            /* FIXME: Single stepping a WFI insn will not halt

               the CPU.  */

            gen_exception_internal(EXCP_DEBUG);

        }

    } else {

        /* While branches must always occur at the end of an IT block,

           there are a few other things that can cause us to terminate

           the TB in the middle of an IT block:

            - Exception generating instructions (bkpt, swi, undefined).

            - Page boundaries.

            - Hardware watchpoints.

           Hardware breakpoints have already been handled and skip this code.

         */

        gen_set_condexec(dc);

        switch(dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, dc->pc);

            break;

        default:

        case DISAS_JUMP:

        case DISAS_UPDATE:

            /* indicate that the hash table must be used to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        case DISAS_WFI:

            gen_helper_wfi(cpu_env);

            break;

        case DISAS_WFE:

            gen_helper_wfe(cpu_env);

            break;

        case DISAS_SWI:

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

            break;

        case DISAS_HVC:

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            break;

        case DISAS_SMC:

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            break;

        }

        if (dc->condjmp) {

            gen_set_label(dc->condlabel);

            gen_set_condexec(dc);

            gen_goto_tb(dc, 1, dc->pc);

            dc->condjmp = 0;

        }

    }

done_generating:

    gen_tb_end(tb, num_insns);

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("----------------\n");

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(env, pc_start, dc->pc - pc_start,

                         dc->thumb | (dc->bswap_code << 1));

        qemu_log("\n");

    }

#endif

    if (search_pc) {

        j = tcg_op_buf_count();

        lj++;

        while (lj <= j)

            tcg_ctx.gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = dc->pc - pc_start;

        tb->icount = num_insns;

    }

}


av_cold int ff_msmpeg4_decode_init(AVCodecContext *avctx)

{

    MpegEncContext *s = avctx->priv_data;

    static int done = 0;

    int i;

    MVTable *mv;

    ff_h263_decode_init(avctx);

    common_init(s);

    if (!done) {

        done = 1;

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

            init_rl(&rl_table[i], static_rl_table_store[i]);

        }

        INIT_VLC_RL(rl_table[0], 642);

        INIT_VLC_RL(rl_table[1], 1104);

        INIT_VLC_RL(rl_table[2], 554);

        INIT_VLC_RL(rl_table[3], 940);

        INIT_VLC_RL(rl_table[4], 962);

        INIT_VLC_RL(rl_table[5], 554);

        mv = &mv_tables[0];

        INIT_VLC_STATIC(&mv->vlc, MV_VLC_BITS, mv->n + 1,

                    mv->table_mv_bits, 1, 1,

                    mv->table_mv_code, 2, 2, 3714);

        mv = &mv_tables[1];

        INIT_VLC_STATIC(&mv->vlc, MV_VLC_BITS, mv->n + 1,

                    mv->table_mv_bits, 1, 1,

                    mv->table_mv_code, 2, 2, 2694);

        INIT_VLC_STATIC(&ff_msmp4_dc_luma_vlc[0], DC_VLC_BITS, 120,

                 &ff_table0_dc_lum[0][1], 8, 4,

                 &ff_table0_dc_lum[0][0], 8, 4, 1158);

        INIT_VLC_STATIC(&ff_msmp4_dc_chroma_vlc[0], DC_VLC_BITS, 120,

                 &ff_table0_dc_chroma[0][1], 8, 4,

                 &ff_table0_dc_chroma[0][0], 8, 4, 1118);

        INIT_VLC_STATIC(&ff_msmp4_dc_luma_vlc[1], DC_VLC_BITS, 120,

                 &ff_table1_dc_lum[0][1], 8, 4,

                 &ff_table1_dc_lum[0][0], 8, 4, 1476);

        INIT_VLC_STATIC(&ff_msmp4_dc_chroma_vlc[1], DC_VLC_BITS, 120,

                 &ff_table1_dc_chroma[0][1], 8, 4,

                 &ff_table1_dc_chroma[0][0], 8, 4, 1216);

        INIT_VLC_STATIC(&v2_dc_lum_vlc, DC_VLC_BITS, 512,

                 &v2_dc_lum_table[0][1], 8, 4,

                 &v2_dc_lum_table[0][0], 8, 4, 1472);

        INIT_VLC_STATIC(&v2_dc_chroma_vlc, DC_VLC_BITS, 512,

                 &v2_dc_chroma_table[0][1], 8, 4,

                 &v2_dc_chroma_table[0][0], 8, 4, 1506);

        INIT_VLC_STATIC(&v2_intra_cbpc_vlc, V2_INTRA_CBPC_VLC_BITS, 4,

                 &v2_intra_cbpc[0][1], 2, 1,

                 &v2_intra_cbpc[0][0], 2, 1, 8);

        INIT_VLC_STATIC(&v2_mb_type_vlc, V2_MB_TYPE_VLC_BITS, 8,

                 &v2_mb_type[0][1], 2, 1,

                 &v2_mb_type[0][0], 2, 1, 128);

        INIT_VLC_STATIC(&v2_mv_vlc, V2_MV_VLC_BITS, 33,

                 &mvtab[0][1], 2, 1,

                 &mvtab[0][0], 2, 1, 538);

        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[0], MB_NON_INTRA_VLC_BITS, 128,

                     &wmv2_inter_table[0][0][1], 8, 4,

                     &wmv2_inter_table[0][0][0], 8, 4, 1636);

        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[1], MB_NON_INTRA_VLC_BITS, 128,

                     &wmv2_inter_table[1][0][1], 8, 4,

                     &wmv2_inter_table[1][0][0], 8, 4, 2648);

        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[2], MB_NON_INTRA_VLC_BITS, 128,

                     &wmv2_inter_table[2][0][1], 8, 4,

                     &wmv2_inter_table[2][0][0], 8, 4, 1532);

        INIT_VLC_STATIC(&ff_mb_non_intra_vlc[3], MB_NON_INTRA_VLC_BITS, 128,

                     &wmv2_inter_table[3][0][1], 8, 4,

                     &wmv2_inter_table[3][0][0], 8, 4, 2488);

        INIT_VLC_STATIC(&ff_msmp4_mb_i_vlc, MB_INTRA_VLC_BITS, 64,

                 &ff_msmp4_mb_i_table[0][1], 4, 2,

                 &ff_msmp4_mb_i_table[0][0], 4, 2, 536);

        INIT_VLC_STATIC(&ff_inter_intra_vlc, INTER_INTRA_VLC_BITS, 4,

                 &table_inter_intra[0][1], 2, 1,

                 &table_inter_intra[0][0], 2, 1, 8);

    }

    switch(s->msmpeg4_version){

    case 1:

    case 2:

        s->decode_mb= msmpeg4v12_decode_mb;

        break;

    case 3:

    case 4:

        s->decode_mb= msmpeg4v34_decode_mb;

        break;

    case 5:

        if (CONFIG_WMV2_DECODER)

            s->decode_mb= ff_wmv2_decode_mb;

    case 6:

        //FIXME + TODO VC1 decode mb

        break;

    }

    s->slice_height= s->mb_height; //to avoid 1/0 if the first frame is not a keyframe

    return 0;

}


PCIBus *pci_grackle_init(uint32_t base, qemu_irq *pic,

                         MemoryRegion *address_space_mem,

                         MemoryRegion *address_space_io)

{

    DeviceState *dev;

    SysBusDevice *s;

    PCIHostState *phb;

    GrackleState *d;

    dev = qdev_create(NULL, TYPE_GRACKLE_PCI_HOST_BRIDGE);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    phb = PCI_HOST_BRIDGE(dev);

    d = GRACKLE_PCI_HOST_BRIDGE(dev);

    memory_region_init(&d->pci_mmio, OBJECT(s), "pci-mmio", 0x100000000ULL);

    memory_region_init_alias(&d->pci_hole, OBJECT(s), "pci-hole", &d->pci_mmio,

                             0x80000000ULL, 0x7e000000ULL);

    memory_region_add_subregion(address_space_mem, 0x80000000ULL,

                                &d->pci_hole);

    phb->bus = pci_register_bus(dev, "pci",

                                pci_grackle_set_irq,

                                pci_grackle_map_irq,

                                pic,

                                &d->pci_mmio,

                                address_space_io,

                                0, 4, TYPE_PCI_BUS);

    pci_create_simple(phb->bus, 0, "grackle");

    sysbus_mmio_map(s, 0, base);

    sysbus_mmio_map(s, 1, base + 0x00200000);

    return phb->bus;

}


CPUAlphaState * cpu_alpha_init (const char *cpu_model)

{

    CPUAlphaState *env;

    int implver, amask, i, max;

    env = qemu_mallocz(sizeof(CPUAlphaState));

    cpu_exec_init(env);

    alpha_translate_init();

    tlb_flush(env, 1);

    /* Default to ev67; no reason not to emulate insns by default.  */

    implver = IMPLVER_21264;

    amask = (AMASK_BWX | AMASK_FIX | AMASK_CIX | AMASK_MVI

	     | AMASK_TRAP | AMASK_PREFETCH);

    max = ARRAY_SIZE(cpu_defs);

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

        if (strcmp (cpu_model, cpu_defs[i].name) == 0) {

            implver = cpu_defs[i].implver;

            amask = cpu_defs[i].amask;

            break;

        }

    }

    env->implver = implver;

    env->amask = amask;

    env->ps = 0x1F00;

#if defined (CONFIG_USER_ONLY)

    env->ps |= 1 << 3;

    cpu_alpha_store_fpcr(env, (FPCR_INVD | FPCR_DZED | FPCR_OVFD

                               | FPCR_UNFD | FPCR_INED | FPCR_DNOD));

#endif

    pal_init(env);

    /* Initialize IPR */

#if defined (CONFIG_USER_ONLY)

    env->ipr[IPR_EXC_ADDR] = 0;

    env->ipr[IPR_EXC_SUM] = 0;

    env->ipr[IPR_EXC_MASK] = 0;

#else

    {

        uint64_t hwpcb;

        hwpcb = env->ipr[IPR_PCBB];

        env->ipr[IPR_ASN] = 0;

        env->ipr[IPR_ASTEN] = 0;

        env->ipr[IPR_ASTSR] = 0;

        env->ipr[IPR_DATFX] = 0;

        /* XXX: fix this */

        //    env->ipr[IPR_ESP] = ldq_raw(hwpcb + 8);

        //    env->ipr[IPR_KSP] = ldq_raw(hwpcb + 0);

        //    env->ipr[IPR_SSP] = ldq_raw(hwpcb + 16);

        //    env->ipr[IPR_USP] = ldq_raw(hwpcb + 24);

        env->ipr[IPR_FEN] = 0;

        env->ipr[IPR_IPL] = 31;

        env->ipr[IPR_MCES] = 0;

        env->ipr[IPR_PERFMON] = 0; /* Implementation specific */

        //    env->ipr[IPR_PTBR] = ldq_raw(hwpcb + 32);

        env->ipr[IPR_SISR] = 0;

        env->ipr[IPR_VIRBND] = -1ULL;

    }

#endif

    qemu_init_vcpu(env);

    return env;

}


static int match_group_separator(const OptionGroupDef *groups, const char *opt)

{

    const OptionGroupDef *p = groups;

    while (p->name) {

        if (p->sep && !strcmp(p->sep, opt))

            return p - groups;

        p++;

    }

    return -1;

}


void ppm_save(const char *filename, struct DisplaySurface *ds, Error **errp)

{

    int width = pixman_image_get_width(ds->image);

    int height = pixman_image_get_height(ds->image);

    FILE *f;

    int y;

    int ret;

    pixman_image_t *linebuf;

    trace_ppm_save(filename, ds);

    f = fopen(filename, "wb");

    if (!f) {

        error_setg(errp, "failed to open file '%s': %s", filename,

                   strerror(errno));

        return;

    }

    ret = fprintf(f, "P6\n%d %d\n%d\n", width, height, 255);

    if (ret < 0) {

        linebuf = NULL;

        goto write_err;

    }

    linebuf = qemu_pixman_linebuf_create(PIXMAN_BE_r8g8b8, width);

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

        qemu_pixman_linebuf_fill(linebuf, ds->image, width, 0, y);

        clearerr(f);

        ret = fwrite(pixman_image_get_data(linebuf), 1,

                     pixman_image_get_stride(linebuf), f);

        (void)ret;

        if (ferror(f)) {

            goto write_err;

        }

    }

out:

    qemu_pixman_image_unref(linebuf);

    fclose(f);

    return;

write_err:

    error_setg(errp, "failed to write to file '%s': %s", filename,

               strerror(errno));

    unlink(filename);

    goto out;

}


static TranslationBlock *tb_find_physical(CPUState *cpu,

                                          target_ulong pc,

                                          target_ulong cs_base,

                                          uint32_t flags)

{

    CPUArchState *env = (CPUArchState *)cpu->env_ptr;

    TranslationBlock *tb, **tb_hash_head, **ptb1;

    unsigned int h;

    tb_page_addr_t phys_pc, phys_page1;

    tcg_ctx.tb_ctx.tb_invalidated_flag = 0;

    /* find translated block using physical mappings */

    phys_pc = get_page_addr_code(env, pc);

    phys_page1 = phys_pc & TARGET_PAGE_MASK;

    h = tb_phys_hash_func(phys_pc);

    /* Start at head of the hash entry */

    ptb1 = tb_hash_head = &tcg_ctx.tb_ctx.tb_phys_hash[h];

    tb = *ptb1;

    while (tb) {

        if (tb->pc == pc &&

            tb->page_addr[0] == phys_page1 &&

            tb->cs_base == cs_base &&

            tb->flags == flags) {

            if (tb->page_addr[1] == -1) {

                /* done, we have a match */

                break;

            } else {

                /* check next page if needed */

                target_ulong virt_page2 = (pc & TARGET_PAGE_MASK) +

                                          TARGET_PAGE_SIZE;

                tb_page_addr_t phys_page2 = get_page_addr_code(env, virt_page2);

                if (tb->page_addr[1] == phys_page2) {

                    break;

                }

            }

        }

        ptb1 = &tb->phys_hash_next;

        tb = *ptb1;

    }

    if (tb) {

        /* Move the TB to the head of the list */

        *ptb1 = tb->phys_hash_next;

        tb->phys_hash_next = *tb_hash_head;

        *tb_hash_head = tb;

    }

    return tb;

}


static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments)

{

    int i, j, nb_segments = 0;

    MXFIndexTableSegment **unsorted_segments;

    int last_body_sid = -1, last_index_sid = -1, last_index_start = -1;

    /* count number of segments, allocate arrays and copy unsorted segments */

    for (i = 0; i < mxf->metadata_sets_count; i++)

        if (mxf->metadata_sets[i]->type == IndexTableSegment)

            nb_segments++;

    if (!nb_segments)

        return AVERROR_INVALIDDATA;

    *sorted_segments  = av_mallocz(nb_segments * sizeof(**sorted_segments));

    unsorted_segments = av_mallocz(nb_segments * sizeof(*unsorted_segments));

    if (!sorted_segments || !unsorted_segments) {

        av_freep(sorted_segments);

        av_free(unsorted_segments);

        return AVERROR(ENOMEM);

    }

    for (i = j = 0; i < mxf->metadata_sets_count; i++)

        if (mxf->metadata_sets[i]->type == IndexTableSegment)

            unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i];

    *nb_sorted_segments = 0;

    /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */

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

        int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1;

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

            MXFIndexTableSegment *s = unsorted_segments[j];

            /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates.

             * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around.

             */

            if ((i == 0     || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) &&

                (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start)) {

                best             = j;

                best_body_sid    = s->body_sid;

                best_index_sid   = s->index_sid;

                best_index_start = s->index_start_position;

            }

        }

        /* no suitable entry found -> we're done */

        if (best == -1)

            break;

        (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best];

        last_body_sid    = best_body_sid;

        last_index_sid   = best_index_sid;

        last_index_start = best_index_start;

    }

    av_free(unsorted_segments);

    return 0;

}


static uint32_t slavio_led_mem_reads(void *opaque, target_phys_addr_t addr)

{

    MiscState *s = opaque;

    uint32_t ret = 0, saddr;

    saddr = addr & LED_MAXADDR;

    switch (saddr) {

    case 0:

        ret = s->leds;

        break;

    default:

        break;

    }

    MISC_DPRINTF("Read diagnostic LED reg 0x" TARGET_FMT_plx " = %x\n", addr,

                 ret);

    return ret;

}


static int proxy_init(FsContext *ctx)

{

    V9fsProxy *proxy = g_malloc(sizeof(V9fsProxy));

    int sock_id;

    if (ctx->export_flags & V9FS_PROXY_SOCK_NAME) {

        sock_id = connect_namedsocket(ctx->fs_root);

    } else {

        sock_id = atoi(ctx->fs_root);

        if (sock_id < 0) {

            fprintf(stderr, "socket descriptor not initialized\n");

        }

    }

    if (sock_id < 0) {

        g_free(proxy);

        return -1;

    }

    g_free(ctx->fs_root);

    ctx->fs_root = NULL;

    proxy->in_iovec.iov_base  = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);

    proxy->in_iovec.iov_len   = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;

    proxy->out_iovec.iov_base = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);

    proxy->out_iovec.iov_len  = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;

    ctx->private = proxy;

    proxy->sockfd = sock_id;

    qemu_mutex_init(&proxy->mutex);

    ctx->export_flags |= V9FS_PATHNAME_FSCONTEXT;

    ctx->exops.get_st_gen = proxy_ioc_getversion;

    return 0;

}


static void scsi_flush_complete(void * opaque, int ret)

{

    SCSIDiskReq *r = (SCSIDiskReq *)opaque;

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    if (r->req.aiocb != NULL) {

        r->req.aiocb = NULL;

        bdrv_acct_done(s->qdev.conf.bs, &r->acct);

    }

    if (ret < 0) {

        if (scsi_handle_rw_error(r, -ret)) {

            goto done;

        }

    }

    scsi_req_complete(&r->req, GOOD);

done:

    if (!r->req.io_canceled) {

        scsi_req_unref(&r->req);

    }

}


void fork_end(int child)

{

    mmap_fork_end(child);

    if (child) {

        CPUState *cpu, *next_cpu;

        /* Child processes created by fork() only have a single thread.

           Discard information about the parent threads.  */

        CPU_FOREACH_SAFE(cpu, next_cpu) {

            if (cpu != thread_cpu) {

                QTAILQ_REMOVE(&cpus, thread_cpu, node);

            }

        }

        pending_cpus = 0;

        pthread_mutex_init(&exclusive_lock, NULL);

        pthread_mutex_init(&cpu_list_mutex, NULL);

        pthread_cond_init(&exclusive_cond, NULL);

        pthread_cond_init(&exclusive_resume, NULL);

        pthread_mutex_init(&tcg_ctx.tb_ctx.tb_lock, NULL);

        gdbserver_fork(thread_cpu);

    } else {

        pthread_mutex_unlock(&exclusive_lock);

        pthread_mutex_unlock(&tcg_ctx.tb_ctx.tb_lock);

    }

}


static uint32_t rtas_set_allocation_state(uint32_t idx, uint32_t state)

{

    sPAPRDRConnector *drc = spapr_drc_by_index(idx);

    sPAPRDRConnectorClass *drck;

    if (!drc) {

        return RTAS_OUT_PARAM_ERROR;

    }

    drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    return drck->set_allocation_state(drc, state);

}


static void nic_save(QEMUFile * f, void *opaque)

{

    EEPRO100State *s = opaque;

    int i;

    pci_device_save(&s->dev, f);

    qemu_put_8s(f, &s->rxcr);

    qemu_put_8s(f, &s->cmd);

    qemu_put_be32s(f, &s->start);

    qemu_put_be32s(f, &s->stop);

    qemu_put_8s(f, &s->boundary);

    qemu_put_8s(f, &s->tsr);

    qemu_put_8s(f, &s->tpsr);

    qemu_put_be16s(f, &s->tcnt);

    qemu_put_be16s(f, &s->rcnt);

    qemu_put_be32s(f, &s->rsar);

    qemu_put_8s(f, &s->rsr);

    qemu_put_8s(f, &s->isr);

    qemu_put_8s(f, &s->dcfg);

    qemu_put_8s(f, &s->imr);

    qemu_put_buffer(f, s->phys, 6);

    qemu_put_8s(f, &s->curpag);

    qemu_put_buffer(f, s->mult, 8);

    qemu_put_buffer(f, s->mem, sizeof(s->mem));

    /* Save all members of struct between scv_stat and mem. */

    qemu_put_8s(f, &s->scb_stat);

    qemu_put_8s(f, &s->int_stat);

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

        qemu_put_be32s(f, &s->region[i]);

    }

    qemu_put_buffer(f, s->macaddr, 6);

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

        qemu_put_be32s(f, &s->statcounter[i]);

    }

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

        qemu_put_be16s(f, &s->mdimem[i]);

    }

    /* The eeprom should be saved and restored by its own routines. */

    qemu_put_be32s(f, &s->device);

    qemu_put_be32s(f, &s->pointer);

    qemu_put_be32s(f, &s->cu_base);

    qemu_put_be32s(f, &s->cu_offset);

    qemu_put_be32s(f, &s->ru_base);

    qemu_put_be32s(f, &s->ru_offset);

    qemu_put_be32s(f, &s->statsaddr);

    /* Save epro100_stats_t statistics. */

    qemu_put_be32s(f, &s->statistics.tx_good_frames);

    qemu_put_be32s(f, &s->statistics.tx_max_collisions);

    qemu_put_be32s(f, &s->statistics.tx_late_collisions);

    qemu_put_be32s(f, &s->statistics.tx_underruns);

    qemu_put_be32s(f, &s->statistics.tx_lost_crs);

    qemu_put_be32s(f, &s->statistics.tx_deferred);

    qemu_put_be32s(f, &s->statistics.tx_single_collisions);

    qemu_put_be32s(f, &s->statistics.tx_multiple_collisions);

    qemu_put_be32s(f, &s->statistics.tx_total_collisions);

    qemu_put_be32s(f, &s->statistics.rx_good_frames);

    qemu_put_be32s(f, &s->statistics.rx_crc_errors);

    qemu_put_be32s(f, &s->statistics.rx_alignment_errors);

    qemu_put_be32s(f, &s->statistics.rx_resource_errors);

    qemu_put_be32s(f, &s->statistics.rx_overrun_errors);

    qemu_put_be32s(f, &s->statistics.rx_cdt_errors);

    qemu_put_be32s(f, &s->statistics.rx_short_frame_errors);

    qemu_put_be32s(f, &s->statistics.fc_xmt_pause);

    qemu_put_be32s(f, &s->statistics.fc_rcv_pause);

    qemu_put_be32s(f, &s->statistics.fc_rcv_unsupported);

    qemu_put_be16s(f, &s->statistics.xmt_tco_frames);

    qemu_put_be16s(f, &s->statistics.rcv_tco_frames);

    qemu_put_be32s(f, &s->statistics.complete);

#if 0

    qemu_put_be16s(f, &s->status);

#endif

    /* Configuration bytes. */

    qemu_put_buffer(f, s->configuration, sizeof(s->configuration));

}


static void terrier_init(int ram_size, int vga_ram_size, int boot_device,

                DisplayState *ds, const char **fd_filename, int snapshot,

                const char *kernel_filename, const char *kernel_cmdline,

                const char *initrd_filename, const char *cpu_model)

{

    spitz_common_init(ram_size, vga_ram_size, ds, kernel_filename,

                kernel_cmdline, initrd_filename, terrier, 0x33f);

}


int qed_write_l2_table_sync(BDRVQEDState *s, QEDRequest *request,

                            unsigned int index, unsigned int n, bool flush)

{

    int ret = -EINPROGRESS;

    qed_write_l2_table(s, request, index, n, flush, qed_sync_cb, &ret);

    while (ret == -EINPROGRESS) {

        aio_poll(bdrv_get_aio_context(s->bs), true);

    }

    return ret;

}