static inline void gen_intermediate_code_internal(CPUX86State *env,

                                                  TranslationBlock *tb,

                                                  int search_pc)

{

    DisasContext dc1, *dc = &dc1;

    target_ulong pc_ptr;

    uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int j, lj;

    uint64_t flags;

    target_ulong pc_start;

    target_ulong cs_base;

    int num_insns;

    int max_insns;

    /* generate intermediate code */

    pc_start = tb->pc;

    cs_base = tb->cs_base;

    flags = tb->flags;

    dc->pe = (flags >> HF_PE_SHIFT) & 1;

    dc->code32 = (flags >> HF_CS32_SHIFT) & 1;

    dc->ss32 = (flags >> HF_SS32_SHIFT) & 1;

    dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1;

    dc->f_st = 0;

    dc->vm86 = (flags >> VM_SHIFT) & 1;

    dc->cpl = (flags >> HF_CPL_SHIFT) & 3;

    dc->iopl = (flags >> IOPL_SHIFT) & 3;

    dc->tf = (flags >> TF_SHIFT) & 1;

    dc->singlestep_enabled = env->singlestep_enabled;

    dc->cc_op = CC_OP_DYNAMIC;

    dc->cs_base = cs_base;

    dc->tb = tb;

    dc->popl_esp_hack = 0;

    /* select memory access functions */

    dc->mem_index = 0;

    if (flags & HF_SOFTMMU_MASK) {

        if (dc->cpl == 3)

            dc->mem_index = 2 * 4;

        else

            dc->mem_index = 1 * 4;

    }

    dc->cpuid_features = env->cpuid_features;

    dc->cpuid_ext_features = env->cpuid_ext_features;

    dc->cpuid_ext2_features = env->cpuid_ext2_features;

    dc->cpuid_ext3_features = env->cpuid_ext3_features;

#ifdef TARGET_X86_64

    dc->lma = (flags >> HF_LMA_SHIFT) & 1;

    dc->code64 = (flags >> HF_CS64_SHIFT) & 1;

#endif

    dc->flags = flags;

    dc->jmp_opt = !(dc->tf || env->singlestep_enabled ||

                    (flags & HF_INHIBIT_IRQ_MASK)

#ifndef CONFIG_SOFTMMU

                    || (flags & HF_SOFTMMU_MASK)

#endif

                    );

#if 0

    /* check addseg logic */

    if (!dc->addseg && (dc->vm86 || !dc->pe || !dc->code32))

        printf("ERROR addseg\n");

#endif

    cpu_T[0] = tcg_temp_new();

    cpu_T[1] = tcg_temp_new();

    cpu_A0 = tcg_temp_new();

    cpu_T3 = tcg_temp_new();

    cpu_tmp0 = tcg_temp_new();

    cpu_tmp1_i64 = tcg_temp_new_i64();

    cpu_tmp2_i32 = tcg_temp_new_i32();

    cpu_tmp3_i32 = tcg_temp_new_i32();

    cpu_tmp4 = tcg_temp_new();

    cpu_tmp5 = tcg_temp_new();

    cpu_ptr0 = tcg_temp_new_ptr();

    cpu_ptr1 = tcg_temp_new_ptr();

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    dc->is_jmp = DISAS_NEXT;

    pc_ptr = pc_start;

    lj = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_icount_start();

    for(;;) {

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

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

                if (bp->pc == pc_ptr &&

                    !((bp->flags & BP_CPU) && (tb->flags & HF_RF_MASK))) {

                    gen_debug(dc, pc_ptr - dc->cs_base);

                    break;

                }

            }

        }

        if (search_pc) {

            j = gen_opc_ptr - gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    gen_opc_instr_start[lj++] = 0;

            }

            gen_opc_pc[lj] = pc_ptr;

            gen_opc_cc_op[lj] = dc->cc_op;

            gen_opc_instr_start[lj] = 1;

            gen_opc_icount[lj] = num_insns;

        }

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

            gen_io_start();

        pc_ptr = disas_insn(dc, pc_ptr);

        num_insns++;

        /* stop translation if indicated */

        if (dc->is_jmp)

            break;

        /* if single step mode, we generate only one instruction and

           generate an exception */

        /* if irq were inhibited with HF_INHIBIT_IRQ_MASK, we clear

           the flag and abort the translation to give the irqs a

           change to be happen */

        if (dc->tf || dc->singlestep_enabled ||

            (flags & HF_INHIBIT_IRQ_MASK)) {

            gen_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

        /* if too long translation, stop generation too */

        if (gen_opc_ptr >= gen_opc_end ||

            (pc_ptr - pc_start) >= (TARGET_PAGE_SIZE - 32) ||

            num_insns >= max_insns) {

            gen_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

        if (singlestep) {

            gen_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    gen_icount_end(tb, num_insns);

    *gen_opc_ptr = INDEX_op_end;

    /* we don't forget to fill the last values */

    if (search_pc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

    }

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        int disas_flags;

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

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

#ifdef TARGET_X86_64

        if (dc->code64)

            disas_flags = 2;

        else

#endif

            disas_flags = !dc->code32;

        log_target_disas(pc_start, pc_ptr - pc_start, disas_flags);

        qemu_log("\n");

    }

#endif

    if (!search_pc) {

        tb->size = pc_ptr - pc_start;

        tb->icount = num_insns;

    }

}


static void vfio_probe_nvidia_bar5_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIONvidiaBAR5Quirk *bar5;

    VFIOConfigWindowQuirk *window;

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||

        !vdev->has_vga || nr != 5) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    quirk->mem = g_new0(MemoryRegion, 4);

    quirk->nr_mem = 4;

    bar5 = quirk->data = g_malloc0(sizeof(*bar5) +

                                   (sizeof(VFIOConfigWindowMatch) * 2));

    window = &bar5->window;

    window->vdev = vdev;

    window->address_offset = 0x8;

    window->data_offset = 0xc;

    window->nr_matches = 2;

    window->matches[0].match = 0x1800;

    window->matches[0].mask = PCI_CONFIG_SPACE_SIZE - 1;

    window->matches[1].match = 0x88000;

    window->matches[1].mask = PCIE_CONFIG_SPACE_SIZE - 1;

    window->bar = nr;

    window->addr_mem = bar5->addr_mem = &quirk->mem[0];

    window->data_mem = bar5->data_mem = &quirk->mem[1];

    memory_region_init_io(window->addr_mem, OBJECT(vdev),

                          &vfio_generic_window_address_quirk, window,

                          "vfio-nvidia-bar5-window-address-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->address_offset,

                                        window->addr_mem, 1);

    memory_region_set_enabled(window->addr_mem, false);

    memory_region_init_io(window->data_mem, OBJECT(vdev),

                          &vfio_generic_window_data_quirk, window,

                          "vfio-nvidia-bar5-window-data-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->data_offset,

                                        window->data_mem, 1);

    memory_region_set_enabled(window->data_mem, false);

    memory_region_init_io(&quirk->mem[2], OBJECT(vdev),

                          &vfio_nvidia_bar5_quirk_master, bar5,

                          "vfio-nvidia-bar5-master-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        0, &quirk->mem[2], 1);

    memory_region_init_io(&quirk->mem[3], OBJECT(vdev),

                          &vfio_nvidia_bar5_quirk_enable, bar5,

                          "vfio-nvidia-bar5-enable-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        4, &quirk->mem[3], 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    trace_vfio_quirk_nvidia_bar5_probe(vdev->vbasedev.name);

}


static void RENAME(lumRangeToJpeg)(int16_t *dst, int width)

{

    int i;

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

        dst[i] = (FFMIN(dst[i],30189)*19077 - 39057361)>>14;

}


Coroutine *qemu_coroutine_create(CoroutineEntry *entry)

{

    Coroutine *co;

    co = QSLIST_FIRST(&pool);

    if (co) {

        QSLIST_REMOVE_HEAD(&pool, pool_next);

        pool_size--;

    } else {

        co = qemu_coroutine_new();

    }

    co->entry = entry;

    return co;

}


static size_t write_to_port(VirtIOSerialPort *port,

                            const uint8_t *buf, size_t size)

{

    VirtQueueElement elem;

    VirtQueue *vq;

    size_t offset = 0;

    size_t len = 0;

    vq = port->ivq;

    if (!virtio_queue_ready(vq)) {

        return 0;

    }

    if (!size) {

        return 0;

    }

    while (offset < size) {

        int i;

        if (!virtqueue_pop(vq, &elem)) {

            break;

        }

        for (i = 0; offset < size && i < elem.in_num; i++) {

            len = MIN(elem.in_sg[i].iov_len, size - offset);

            memcpy(elem.in_sg[i].iov_base, buf + offset, len);

            offset += len;

        }

        virtqueue_push(vq, &elem, len);

    }

    virtio_notify(&port->vser->vdev, vq);

    return offset;

}


static char *tcg_get_arg_str_idx(TCGContext *s, char *buf, int buf_size,

                                 int idx)

{

    TCGTemp *ts;

    assert(idx >= 0 && idx < s->nb_temps);

    ts = &s->temps[idx];

    assert(ts);

    if (idx < s->nb_globals) {

        pstrcpy(buf, buf_size, ts->name);

    } else {

        if (ts->temp_local)

            snprintf(buf, buf_size, "loc%d", idx - s->nb_globals);

        else

            snprintf(buf, buf_size, "tmp%d", idx - s->nb_globals);

    }

    return buf;

}


static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)

{

    BDRVQcow2State *s = bs->opaque;

    ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);

    *spec_info = (ImageInfoSpecific){

        .kind  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,

        {

            .qcow2 = g_new(ImageInfoSpecificQCow2, 1),

        },

    };

    if (s->qcow_version == 2) {

        *spec_info->qcow2 = (ImageInfoSpecificQCow2){

            .compat             = g_strdup("0.10"),

            .refcount_bits      = s->refcount_bits,

        };

    } else if (s->qcow_version == 3) {

        *spec_info->qcow2 = (ImageInfoSpecificQCow2){

            .compat             = g_strdup("1.1"),

            .lazy_refcounts     = s->compatible_features &

                                  QCOW2_COMPAT_LAZY_REFCOUNTS,

            .has_lazy_refcounts = true,

            .corrupt            = s->incompatible_features &

                                  QCOW2_INCOMPAT_CORRUPT,

            .has_corrupt        = true,

            .refcount_bits      = s->refcount_bits,

        };

    }

    return spec_info;

}


static void kvm_cpu_fill_host(x86_def_t *x86_cpu_def)

{

    uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;

    assert(kvm_enabled());

    x86_cpu_def->name = "host";

    host_cpuid(0x0, 0, &eax, &ebx, &ecx, &edx);

    x86_cpu_def->level = eax;

    x86_cpu_def->vendor1 = ebx;

    x86_cpu_def->vendor2 = edx;

    x86_cpu_def->vendor3 = ecx;

    host_cpuid(0x1, 0, &eax, &ebx, &ecx, &edx);

    x86_cpu_def->family = ((eax >> 8) & 0x0F) + ((eax >> 20) & 0xFF);

    x86_cpu_def->model = ((eax >> 4) & 0x0F) | ((eax & 0xF0000) >> 12);

    x86_cpu_def->stepping = eax & 0x0F;

    x86_cpu_def->ext_features = ecx;

    x86_cpu_def->features = edx;

    if (x86_cpu_def->level >= 7) {

        x86_cpu_def->cpuid_7_0_ebx_features = kvm_arch_get_supported_cpuid(kvm_state, 0x7, 0, R_EBX);

    } else {

        x86_cpu_def->cpuid_7_0_ebx_features = 0;

    }

    host_cpuid(0x80000000, 0, &eax, &ebx, &ecx, &edx);

    x86_cpu_def->xlevel = eax;

    host_cpuid(0x80000001, 0, &eax, &ebx, &ecx, &edx);

    x86_cpu_def->ext2_features = edx;

    x86_cpu_def->ext3_features = ecx;

    cpu_x86_fill_model_id(x86_cpu_def->model_id);

    x86_cpu_def->vendor_override = 0;

    /* Call Centaur's CPUID instruction. */

    if (x86_cpu_def->vendor1 == CPUID_VENDOR_VIA_1 &&

        x86_cpu_def->vendor2 == CPUID_VENDOR_VIA_2 &&

        x86_cpu_def->vendor3 == CPUID_VENDOR_VIA_3) {

        host_cpuid(0xC0000000, 0, &eax, &ebx, &ecx, &edx);

        if (eax >= 0xC0000001) {

            /* Support VIA max extended level */

            x86_cpu_def->xlevel2 = eax;

            host_cpuid(0xC0000001, 0, &eax, &ebx, &ecx, &edx);

            x86_cpu_def->ext4_features = edx;

        }

    }

    /*

     * Every SVM feature requires emulation support in KVM - so we can't just

     * read the host features here. KVM might even support SVM features not

     * available on the host hardware. Just set all bits and mask out the

     * unsupported ones later.

     */

    x86_cpu_def->svm_features = -1;

}


static uint32_t scsi_init_iovec(SCSIDiskReq *r, size_t size)

{

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

    if (!r->iov.iov_base) {

        r->buflen = size;

        r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);

    }

    r->iov.iov_len = MIN(r->sector_count * 512, r->buflen);

    qemu_iovec_init_external(&r->qiov, &r->iov, 1);

    return r->qiov.size / 512;

}


static void hax_process_section(MemoryRegionSection *section, uint8_t flags)

{

    MemoryRegion *mr = section->mr;

    hwaddr start_pa = section->offset_within_address_space;

    ram_addr_t size = int128_get64(section->size);

    unsigned int delta;

    uint64_t host_va;

    /* We only care about RAM and ROM regions */

    if (!memory_region_is_ram(mr)) {

        if (memory_region_is_romd(mr)) {

            /* HAXM kernel module does not support ROMD yet  */

            fprintf(stderr, "%s: Warning: Ignoring ROMD region 0x%016" PRIx64

                    "->0x%016" PRIx64 "\n", __func__, start_pa,

                    start_pa + size);

        }

        return;

    }

    /* Adjust start_pa and size so that they are page-aligned. (Cf

     * kvm_set_phys_mem() in kvm-all.c).

     */

    delta = qemu_real_host_page_size - (start_pa & ~qemu_real_host_page_mask);

    delta &= ~qemu_real_host_page_mask;

    if (delta > size) {

        return;

    }

    start_pa += delta;

    size -= delta;

    size &= qemu_real_host_page_mask;

    if (!size || (start_pa & ~qemu_real_host_page_mask)) {

        return;

    }

    host_va = (uintptr_t)memory_region_get_ram_ptr(mr)

            + section->offset_within_region + delta;

    if (memory_region_is_rom(section->mr)) {

        flags |= HAX_RAM_INFO_ROM;

    }

    /* the kernel module interface uses 32-bit sizes (but we could split...) */

    g_assert(size <= UINT32_MAX);

    hax_update_mapping(start_pa, size, host_va, flags);

}


void avcodec_get_context_defaults(AVCodecContext *s){

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

    s->av_class= &av_codec_context_class;

    s->bit_rate= 800*1000;

    s->bit_rate_tolerance= s->bit_rate*10;

    s->qmin= 2;

    s->qmax= 31;

    s->mb_qmin= 2;

    s->mb_qmax= 31;

    s->rc_eq= "tex^qComp";

    s->qcompress= 0.5;

    s->max_qdiff= 3;

    s->b_quant_factor=1.25;

    s->b_quant_offset=1.25;

    s->i_quant_factor=-0.8;

    s->i_quant_offset=0.0;

    s->error_concealment= 3;

    s->error_resilience= 1;

    s->workaround_bugs= FF_BUG_AUTODETECT;

    s->frame_rate_base= 1;

    s->frame_rate = 25;

    s->gop_size= 50;

    s->me_method= ME_EPZS;

    s->get_buffer= avcodec_default_get_buffer;

    s->release_buffer= avcodec_default_release_buffer;

    s->get_format= avcodec_default_get_format;

    s->execute= avcodec_default_execute;

    s->thread_count=1;

    s->me_subpel_quality=8;

    s->lmin= FF_QP2LAMBDA * s->qmin;

    s->lmax= FF_QP2LAMBDA * s->qmax;

    s->sample_aspect_ratio= (AVRational){0,1};

    s->ildct_cmp= FF_CMP_VSAD;

    s->profile= FF_PROFILE_UNKNOWN;

    s->level= FF_LEVEL_UNKNOWN;

    s->intra_quant_bias= FF_DEFAULT_QUANT_BIAS;

    s->inter_quant_bias= FF_DEFAULT_QUANT_BIAS;

    s->palctrl = NULL;

    s->reget_buffer= avcodec_default_reget_buffer;

}


static void gen_sraiq(DisasContext *ctx)

{

    int sh = SH(ctx->opcode);

    int l1 = gen_new_label();

    TCGv t0 = tcg_temp_new();

    TCGv t1 = tcg_temp_new();

    tcg_gen_shri_tl(t0, cpu_gpr[rS(ctx->opcode)], sh);

    tcg_gen_shli_tl(t1, cpu_gpr[rS(ctx->opcode)], 32 - sh);

    tcg_gen_or_tl(t0, t0, t1);

    gen_store_spr(SPR_MQ, t0);

    tcg_gen_movi_tl(cpu_ca, 0);

    tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

    tcg_gen_brcondi_tl(TCG_COND_GE, cpu_gpr[rS(ctx->opcode)], 0, l1);

    tcg_gen_movi_tl(cpu_ca, 1);

    gen_set_label(l1);

    tcg_gen_sari_tl(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)], sh);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);

}


static const mon_cmd_t *monitor_parse_command(Monitor *mon,

                                              const char *cmdline,

                                              int start,

                                              mon_cmd_t *table,

                                              QDict *qdict)

{

    const char *p, *typestr;

    int c;

    const mon_cmd_t *cmd;

    char cmdname[256];

    char buf[1024];

    char *key;

    /* extract the command name */

    p = get_command_name(cmdline + start, cmdname, sizeof(cmdname));

    if (!p)

        return NULL;

    cmd = search_dispatch_table(table, cmdname);

    if (!cmd) {

        monitor_printf(mon, "unknown command: '%.*s'\n",

                       (int)(p - cmdline), cmdline);

        return NULL;

    }

    /* filter out following useless space */

    while (qemu_isspace(*p)) {

        p++;

    }

    /* search sub command */

    if (cmd->sub_table != NULL) {

        /* check if user set additional command */

        if (*p == '\0') {

            return cmd;

        }

        return monitor_parse_command(mon, cmdline, p - cmdline,

                                     cmd->sub_table, qdict);

    }

    /* parse the parameters */

    typestr = cmd->args_type;

    for(;;) {

        typestr = key_get_info(typestr, &key);

        if (!typestr)

            break;

        c = *typestr;

        typestr++;

        switch(c) {

        case 'F':

        case 'B':

        case 's':

            {

                int ret;

                while (qemu_isspace(*p))

                    p++;

                if (*typestr == '?') {

                    typestr++;

                    if (*p == '\0') {

                        /* no optional string: NULL argument */

                        break;

                    }

                }

                ret = get_str(buf, sizeof(buf), &p);

                if (ret < 0) {

                    switch(c) {

                    case 'F':

                        monitor_printf(mon, "%s: filename expected\n",

                                       cmdname);

                        break;

                    case 'B':

                        monitor_printf(mon, "%s: block device name expected\n",

                                       cmdname);

                        break;

                    default:

                        monitor_printf(mon, "%s: string expected\n", cmdname);

                        break;

                    }

                    goto fail;

                }

                qdict_put(qdict, key, qstring_from_str(buf));

            }

            break;

        case 'O':

            {

                QemuOptsList *opts_list;

                QemuOpts *opts;

                opts_list = qemu_find_opts(key);

                if (!opts_list || opts_list->desc->name) {

                    goto bad_type;

                }

                while (qemu_isspace(*p)) {

                    p++;

                }

                if (!*p)

                    break;

                if (get_str(buf, sizeof(buf), &p) < 0) {

                    goto fail;

                }

                opts = qemu_opts_parse(opts_list, buf, 1);

                if (!opts) {

                    goto fail;

                }

                qemu_opts_to_qdict(opts, qdict);

                qemu_opts_del(opts);

            }

            break;

        case '/':

            {

                int count, format, size;

                while (qemu_isspace(*p))

                    p++;

                if (*p == '/') {

                    /* format found */

                    p++;

                    count = 1;

                    if (qemu_isdigit(*p)) {

                        count = 0;

                        while (qemu_isdigit(*p)) {

                            count = count * 10 + (*p - '0');

                            p++;

                        }

                    }

                    size = -1;

                    format = -1;

                    for(;;) {

                        switch(*p) {

                        case 'o':

                        case 'd':

                        case 'u':

                        case 'x':

                        case 'i':

                        case 'c':

                            format = *p++;

                            break;

                        case 'b':

                            size = 1;

                            p++;

                            break;

                        case 'h':

                            size = 2;

                            p++;

                            break;

                        case 'w':

                            size = 4;

                            p++;

                            break;

                        case 'g':

                        case 'L':

                            size = 8;

                            p++;

                            break;

                        default:

                            goto next;

                        }

                    }

                next:

                    if (*p != '\0' && !qemu_isspace(*p)) {

                        monitor_printf(mon, "invalid char in format: '%c'\n",

                                       *p);

                        goto fail;

                    }

                    if (format < 0)

                        format = default_fmt_format;

                    if (format != 'i') {

                        /* for 'i', not specifying a size gives -1 as size */

                        if (size < 0)

                            size = default_fmt_size;

                        default_fmt_size = size;

                    }

                    default_fmt_format = format;

                } else {

                    count = 1;

                    format = default_fmt_format;

                    if (format != 'i') {

                        size = default_fmt_size;

                    } else {

                        size = -1;

                    }

                }

                qdict_put(qdict, "count", qint_from_int(count));

                qdict_put(qdict, "format", qint_from_int(format));

                qdict_put(qdict, "size", qint_from_int(size));

            }

            break;

        case 'i':

        case 'l':

        case 'M':

            {

                int64_t val;

                while (qemu_isspace(*p))

                    p++;

                if (*typestr == '?' || *typestr == '.') {

                    if (*typestr == '?') {

                        if (*p == '\0') {

                            typestr++;

                            break;

                        }

                    } else {

                        if (*p == '.') {

                            p++;

                            while (qemu_isspace(*p))

                                p++;

                        } else {

                            typestr++;

                            break;

                        }

                    }

                    typestr++;

                }

                if (get_expr(mon, &val, &p))

                    goto fail;

                /* Check if 'i' is greater than 32-bit */

                if ((c == 'i') && ((val >> 32) & 0xffffffff)) {

                    monitor_printf(mon, "\'%s\' has failed: ", cmdname);

                    monitor_printf(mon, "integer is for 32-bit values\n");

                    goto fail;

                } else if (c == 'M') {

                    if (val < 0) {

                        monitor_printf(mon, "enter a positive value\n");

                        goto fail;

                    }

                    val <<= 20;

                }

                qdict_put(qdict, key, qint_from_int(val));

            }

            break;

        case 'o':

            {

                int64_t val;

                char *end;

                while (qemu_isspace(*p)) {

                    p++;

                }

                if (*typestr == '?') {

                    typestr++;

                    if (*p == '\0') {

                        break;

                    }

                }

                val = strtosz(p, &end);

                if (val < 0) {

                    monitor_printf(mon, "invalid size\n");

                    goto fail;

                }

                qdict_put(qdict, key, qint_from_int(val));

                p = end;

            }

            break;

        case 'T':

            {

                double val;

                while (qemu_isspace(*p))

                    p++;

                if (*typestr == '?') {

                    typestr++;

                    if (*p == '\0') {

                        break;

                    }

                }

                if (get_double(mon, &val, &p) < 0) {

                    goto fail;

                }

                if (p[0] && p[1] == 's') {

                    switch (*p) {

                    case 'm':

                        val /= 1e3; p += 2; break;

                    case 'u':

                        val /= 1e6; p += 2; break;

                    case 'n':

                        val /= 1e9; p += 2; break;

                    }

                }

                if (*p && !qemu_isspace(*p)) {

                    monitor_printf(mon, "Unknown unit suffix\n");

                    goto fail;

                }

                qdict_put(qdict, key, qfloat_from_double(val));

            }

            break;

        case 'b':

            {

                const char *beg;

                bool val;

                while (qemu_isspace(*p)) {

                    p++;

                }

                beg = p;

                while (qemu_isgraph(*p)) {

                    p++;

                }

                if (p - beg == 2 && !memcmp(beg, "on", p - beg)) {

                    val = true;

                } else if (p - beg == 3 && !memcmp(beg, "off", p - beg)) {

                    val = false;

                } else {

                    monitor_printf(mon, "Expected 'on' or 'off'\n");

                    goto fail;

                }

                qdict_put(qdict, key, qbool_from_bool(val));

            }

            break;

        case '-':

            {

                const char *tmp = p;

                int skip_key = 0;

                /* option */

                c = *typestr++;

                if (c == '\0')

                    goto bad_type;

                while (qemu_isspace(*p))

                    p++;

                if (*p == '-') {

                    p++;

                    if(c != *p) {

                        if(!is_valid_option(p, typestr)) {

                            monitor_printf(mon, "%s: unsupported option -%c\n",

                                           cmdname, *p);

                            goto fail;

                        } else {

                            skip_key = 1;

                        }

                    }

                    if(skip_key) {

                        p = tmp;

                    } else {

                        /* has option */

                        p++;

                        qdict_put(qdict, key, qbool_from_bool(true));

                    }

                }

            }

            break;

        case 'S':

            {

                /* package all remaining string */

                int len;

                while (qemu_isspace(*p)) {

                    p++;

                }

                if (*typestr == '?') {

                    typestr++;

                    if (*p == '\0') {

                        /* no remaining string: NULL argument */

                        break;

                    }

                }

                len = strlen(p);

                if (len <= 0) {

                    monitor_printf(mon, "%s: string expected\n",

                                   cmdname);

                    break;

                }

                qdict_put(qdict, key, qstring_from_str(p));

                p += len;

            }

            break;

        default:

        bad_type:

            monitor_printf(mon, "%s: unknown type '%c'\n", cmdname, c);

            goto fail;

        }

        g_free(key);

        key = NULL;

    }

    /* check that all arguments were parsed */

    while (qemu_isspace(*p))

        p++;

    if (*p != '\0') {

        monitor_printf(mon, "%s: extraneous characters at the end of line\n",

                       cmdname);

        goto fail;

    }

    return cmd;

fail:

    g_free(key);

    return NULL;

}


opts_start_struct(Visitor *v, void **obj, const char *kind,

                  const char *name, size_t size, Error **errp)

{

    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);

    const QemuOpt *opt;

    *obj = g_malloc0(size > 0 ? size : 1);

    if (ov->depth++ > 0) {

        return;

    }

    ov->unprocessed_opts = g_hash_table_new_full(&g_str_hash, &g_str_equal,

                                                 NULL, &destroy_list);

    QTAILQ_FOREACH(opt, &ov->opts_root->head, next) {

        /* ensured by qemu-option.c::opts_do_parse() */

        assert(strcmp(opt->name, "id") != 0);

        opts_visitor_insert(ov->unprocessed_opts, opt);

    }

    if (ov->opts_root->id != NULL) {

        ov->fake_id_opt = g_malloc0(sizeof *ov->fake_id_opt);

        ov->fake_id_opt->name = "id";

        ov->fake_id_opt->str = ov->opts_root->id;

        opts_visitor_insert(ov->unprocessed_opts, ov->fake_id_opt);

    }

}


static UserDefTwo *nested_struct_create(void)

{

    UserDefTwo *udnp = g_malloc0(sizeof(*udnp));

    udnp->string0 = strdup("test_string0");

    udnp->dict1 = g_malloc0(sizeof(*udnp->dict1));

    udnp->dict1->string1 = strdup("test_string1");

    udnp->dict1->dict2 = g_malloc0(sizeof(*udnp->dict1->dict2));

    udnp->dict1->dict2->userdef = g_new0(UserDefOne, 1);

    udnp->dict1->dict2->userdef->base = g_new0(UserDefZero, 1);

    udnp->dict1->dict2->userdef->base->integer = 42;

    udnp->dict1->dict2->userdef->string = strdup("test_string");

    udnp->dict1->dict2->string = strdup("test_string2");

    udnp->dict1->dict3 = g_malloc0(sizeof(*udnp->dict1->dict3));

    udnp->dict1->has_dict3 = true;

    udnp->dict1->dict3->userdef = g_new0(UserDefOne, 1);

    udnp->dict1->dict3->userdef->base = g_new0(UserDefZero, 1);

    udnp->dict1->dict3->userdef->base->integer = 43;

    udnp->dict1->dict3->userdef->string = strdup("test_string");

    udnp->dict1->dict3->string = strdup("test_string3");

    return udnp;

}


static void gem_write(void *opaque, hwaddr offset, uint64_t val,

        unsigned size)

{

    GemState *s = (GemState *)opaque;

    uint32_t readonly;

    DB_PRINT("offset: 0x%04x write: 0x%08x ", (unsigned)offset, (unsigned)val);

    offset >>= 2;

    /* Squash bits which are read only in write value */

    val &= ~(s->regs_ro[offset]);

    /* Preserve (only) bits which are read only and wtc in register */

    readonly = s->regs[offset] & (s->regs_ro[offset] | s->regs_w1c[offset]);

    /* Copy register write to backing store */

    s->regs[offset] = (val & ~s->regs_w1c[offset]) | readonly;

    /* do w1c */

    s->regs[offset] &= ~(s->regs_w1c[offset] & val);

    /* Handle register write side effects */

    switch (offset) {

    case GEM_NWCTRL:

        if (val & GEM_NWCTRL_RXENA) {

            gem_get_rx_desc(s);

        }

        if (val & GEM_NWCTRL_TXSTART) {

            gem_transmit(s);

        }

        if (!(val & GEM_NWCTRL_TXENA)) {

            /* Reset to start of Q when transmit disabled. */

            s->tx_desc_addr = s->regs[GEM_TXQBASE];

        }

        if (val & GEM_NWCTRL_RXENA) {

            qemu_flush_queued_packets(qemu_get_queue(s->nic));

        }

        break;

    case GEM_TXSTATUS:

        gem_update_int_status(s);

        break;

    case GEM_RXQBASE:

        s->rx_desc_addr = val;

        break;

    case GEM_TXQBASE:

        s->tx_desc_addr = val;

        break;

    case GEM_RXSTATUS:

        gem_update_int_status(s);

        break;

    case GEM_IER:

        s->regs[GEM_IMR] &= ~val;

        gem_update_int_status(s);

        break;

    case GEM_IDR:

        s->regs[GEM_IMR] |= val;

        gem_update_int_status(s);

        break;

    case GEM_SPADDR1LO:

    case GEM_SPADDR2LO:

    case GEM_SPADDR3LO:

    case GEM_SPADDR4LO:

        s->sar_active[(offset - GEM_SPADDR1LO) / 2] = false;

        break;

    case GEM_SPADDR1HI:

    case GEM_SPADDR2HI:

    case GEM_SPADDR3HI:

    case GEM_SPADDR4HI:

        s->sar_active[(offset - GEM_SPADDR1HI) / 2] = true;

        break;

    case GEM_PHYMNTNC:

        if (val & GEM_PHYMNTNC_OP_W) {

            uint32_t phy_addr, reg_num;

            phy_addr = (val & GEM_PHYMNTNC_ADDR) >> GEM_PHYMNTNC_ADDR_SHFT;

            if (phy_addr == BOARD_PHY_ADDRESS) {

                reg_num = (val & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT;

                gem_phy_write(s, reg_num, val);

            }

        }

        break;

    }

    DB_PRINT("newval: 0x%08x\n", s->regs[offset]);

}


uint32_t cpu_ppc_load_decr (CPUState *env)

{

    ppc_tb_t *tb_env = env->tb_env;

    uint32_t decr;

    decr = muldiv64(tb_env->decr_next - qemu_get_clock(vm_clock),

                    tb_env->tb_freq, ticks_per_sec);

#if defined(DEBUG_TB)

    printf("%s: 0x%08x\n", __func__, decr);

#endif

    return decr;

}


static int wm8750_event(I2CSlave *i2c, enum i2c_event event)

{

    WM8750State *s = WM8750(i2c);

    switch (event) {

    case I2C_START_SEND:

        s->i2c_len = 0;

        break;

    case I2C_FINISH:

#ifdef VERBOSE

        if (s->i2c_len < 2)

            printf("%s: message too short (%i bytes)\n",

                            __FUNCTION__, s->i2c_len);

#endif

        break;

    default:

        break;

    }

    return 0;

}


static int amr_wb_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                               const AVFrame *frame, int *got_packet_ptr)

{

    AMRWBContext *s = avctx->priv_data;

    const int16_t *samples = (const int16_t *)frame->data[0];

    int size, ret;

    if ((ret = ff_alloc_packet2(avctx, avpkt, MAX_PACKET_SIZE)))

        return ret;

    if (s->last_bitrate != avctx->bit_rate) {

        s->mode         = get_wb_bitrate_mode(avctx->bit_rate, avctx);

        s->last_bitrate = avctx->bit_rate;

    }

    size = E_IF_encode(s->state, s->mode, samples, avpkt->data, s->allow_dtx);

    if (size <= 0 || size > MAX_PACKET_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "Error encoding frame\n");

        return AVERROR(EINVAL);

    }

    if (frame->pts != AV_NOPTS_VALUE)

        avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->delay);

    avpkt->size = size;

    *got_packet_ptr = 1;

    return 0;

}


static int decode_2(SANMVideoContext *ctx)

{

    int cx, cy, ret;

    for (cy = 0; cy != ctx->aligned_height; cy += 8) {

        for (cx = 0; cx != ctx->aligned_width; cx += 8) {

            if (ret = codec2subblock(ctx, cx, cy, 8))

                return ret;

        }

    }

    return 0;

}


static bool cmd_write_pio(IDEState *s, uint8_t cmd)

{

    bool lba48 = (cmd == WIN_WRITE_EXT);

    if (!s->bs) {

        ide_abort_command(s);

        return true;

    }

    ide_cmd_lba48_transform(s, lba48);

    s->req_nb_sectors = 1;

    s->status = SEEK_STAT | READY_STAT;

    ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);

    s->media_changed = 1;

    return false;

}


static uint64_t cirrus_mmio_read(void *opaque, target_phys_addr_t addr,

                                 unsigned size)

{

    CirrusVGAState *s = opaque;

    if (addr >= 0x100) {

        return cirrus_mmio_blt_read(s, addr - 0x100);

    } else {

        return cirrus_vga_ioport_read(s, addr + 0x3c0);

    }

}


static int ffv1_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                        const AVFrame *pict, int *got_packet)

{

    FFV1Context *f      = avctx->priv_data;

    RangeCoder *const c = &f->slice_context[0]->c;

    int used_count      = 0;

    uint8_t keystate    = 128;

    uint8_t *buf_p;

    int i, ret;

    f->frame = pict;

    if ((ret = ff_alloc_packet(pkt, avctx->width * avctx->height *

                             ((8 * 2 + 1 + 1) * 4) / 8 +

                             AV_INPUT_BUFFER_MIN_SIZE)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");

        return ret;

    }

    ff_init_range_encoder(c, pkt->data, pkt->size);

    ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);

    if (avctx->gop_size == 0 || f->picture_number % avctx->gop_size == 0) {

        put_rac(c, &keystate, 1);

        f->key_frame = 1;

        f->gob_count++;

        write_header(f);

    } else {

        put_rac(c, &keystate, 0);

        f->key_frame = 0;

    }

    if (f->ac > 1) {

        int i;

        for (i = 1; i < 256; i++) {

            c->one_state[i]        = f->state_transition[i];

            c->zero_state[256 - i] = 256 - c->one_state[i];

        }

    }

    for (i = 1; i < f->slice_count; i++) {

        FFV1Context *fs = f->slice_context[i];

        uint8_t *start  = pkt->data +

                          (pkt->size - used_count) * (int64_t)i / f->slice_count;

        int len = pkt->size / f->slice_count;

        ff_init_range_encoder(&fs->c, start, len);

    }

    avctx->execute(avctx, encode_slice, &f->slice_context[0], NULL,

                   f->slice_count, sizeof(void *));

    buf_p = pkt->data;

    for (i = 0; i < f->slice_count; i++) {

        FFV1Context *fs = f->slice_context[i];

        int bytes;

        if (fs->ac) {

            uint8_t state = 129;

            put_rac(&fs->c, &state, 0);

            bytes = ff_rac_terminate(&fs->c);

        } else {

            flush_put_bits(&fs->pb); // FIXME: nicer padding

            bytes = fs->ac_byte_count + (put_bits_count(&fs->pb) + 7) / 8;

        }

        if (i > 0 || f->version > 2) {

            av_assert0(bytes < pkt->size / f->slice_count);

            memmove(buf_p, fs->c.bytestream_start, bytes);

            av_assert0(bytes < (1 << 24));

            AV_WB24(buf_p + bytes, bytes);

            bytes += 3;

        }

        if (f->ec) {

            unsigned v;

            buf_p[bytes++] = 0;

            v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, buf_p, bytes);

            AV_WL32(buf_p + bytes, v);

            bytes += 4;

        }

        buf_p += bytes;

    }

    if ((avctx->flags & AV_CODEC_FLAG_PASS1) && (f->picture_number & 31) == 0) {

        int j, k, m;

        char *p   = avctx->stats_out;

        char *end = p + STATS_OUT_SIZE;

        memset(f->rc_stat, 0, sizeof(f->rc_stat));

        for (i = 0; i < f->quant_table_count; i++)

            memset(f->rc_stat2[i], 0, f->context_count[i] * sizeof(*f->rc_stat2[i]));

        for (j = 0; j < f->slice_count; j++) {

            FFV1Context *fs = f->slice_context[j];

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

                f->rc_stat[i][0] += fs->rc_stat[i][0];

                f->rc_stat[i][1] += fs->rc_stat[i][1];

            }

            for (i = 0; i < f->quant_table_count; i++) {

                for (k = 0; k < f->context_count[i]; k++)

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

                        f->rc_stat2[i][k][m][0] += fs->rc_stat2[i][k][m][0];

                        f->rc_stat2[i][k][m][1] += fs->rc_stat2[i][k][m][1];

                    }

            }

        }

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

            snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",

                     f->rc_stat[j][0], f->rc_stat[j][1]);

            p += strlen(p);

        }

        snprintf(p, end - p, "\n");

        for (i = 0; i < f->quant_table_count; i++) {

            for (j = 0; j < f->context_count[i]; j++)

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

                    snprintf(p, end - p, "%" PRIu64 " %" PRIu64 " ",

                             f->rc_stat2[i][j][m][0], f->rc_stat2[i][j][m][1]);

                    p += strlen(p);

                }

        }

        snprintf(p, end - p, "%d\n", f->gob_count);

    } else if (avctx->flags & AV_CODEC_FLAG_PASS1)

        avctx->stats_out[0] = '\0';

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->key_frame = f->key_frame;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    f->picture_number++;

    pkt->size   = buf_p - pkt->data;

    pkt->flags |= AV_PKT_FLAG_KEY * f->key_frame;

    *got_packet = 1;

    return 0;

}


static void setup_frame(int usig, struct emulated_sigaction *ka,

			target_sigset_t *set, CPUState *regs)

{

	struct sigframe *frame;

	abi_ulong frame_addr = get_sigframe(ka, regs, sizeof(*frame));

	int i, err = 0;

	if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0))

		return;

	err |= setup_sigcontext(&frame->sc, /*&frame->fpstate,*/ regs, set->sig[0]);

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

            if (__put_user(set->sig[i], &frame->extramask[i - 1]))

                goto end;

	}

	if (err == 0)

            err = setup_return(regs, ka, &frame->retcode, frame, usig);

end:

	unlock_user_struct(frame, frame_addr, 1);

        //	return err;

}


int qemu_uuid_parse(const char *str, uint8_t *uuid)

{

    int ret;

    if(strlen(str) != 36)

        return -1;

    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],

            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],

            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);

    if(ret != 16)

        return -1;

#ifdef TARGET_I386

    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);

#endif

    return 0;

}


QError *qerror_from_info(const char *file, int linenr, const char *func,

                         const char *fmt, va_list *va)

{

    QError *qerr;

    qerr = qerror_new();

    loc_save(&qerr->loc);

    qerr->linenr = linenr;

    qerr->file = file;

    qerr->func = func;

    if (!fmt) {

        qerror_abort(qerr, "QDict not specified");

    }

    qerror_set_data(qerr, fmt, va);

    qerror_set_desc(qerr, fmt);

    return qerr;

}


fork_exec(struct socket *so, const char *ex, int do_pty)

{

	int s;

	struct sockaddr_in addr;

	int addrlen = sizeof(addr);

	int opt;

        int master = -1;

	char *argv[256];

#if 0

	char buff[256];

#endif

	/* don't want to clobber the original */

	char *bptr;

	const char *curarg;

	int c, i, ret;

	DEBUG_CALL("fork_exec");

	DEBUG_ARG("so = %lx", (long)so);

	DEBUG_ARG("ex = %lx", (long)ex);

	DEBUG_ARG("do_pty = %lx", (long)do_pty);

	if (do_pty == 2) {

#if 0

		if (slirp_openpty(&master, &s) == -1) {

			lprint("Error: openpty failed: %s\n", strerror(errno));

			return 0;

		}

#else

                return 0;

#endif

	} else {

		addr.sin_family = AF_INET;

		addr.sin_port = 0;

		addr.sin_addr.s_addr = INADDR_ANY;

		if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0 ||

		    bind(s, (struct sockaddr *)&addr, addrlen) < 0 ||

		    listen(s, 1) < 0) {

			lprint("Error: inet socket: %s\n", strerror(errno));

			closesocket(s);

			return 0;

		}

	}

	switch(fork()) {

	 case -1:

		lprint("Error: fork failed: %s\n", strerror(errno));

		close(s);

		if (do_pty == 2)

		   close(master);

		return 0;

	 case 0:

		/* Set the DISPLAY */

		if (do_pty == 2) {

			(void) close(master);

#ifdef TIOCSCTTY /* XXXXX */

			(void) setsid();

			ioctl(s, TIOCSCTTY, (char *)NULL);

#endif

		} else {

			getsockname(s, (struct sockaddr *)&addr, &addrlen);

			close(s);

			/*

			 * Connect to the socket

			 * XXX If any of these fail, we're in trouble!

	 		 */

			s = socket(AF_INET, SOCK_STREAM, 0);

			addr.sin_addr = loopback_addr;

                        do {

                            ret = connect(s, (struct sockaddr *)&addr, addrlen);

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

		}

#if 0

		if (x_port >= 0) {

#ifdef HAVE_SETENV

			sprintf(buff, "%s:%d.%d", inet_ntoa(our_addr), x_port, x_screen);

			setenv("DISPLAY", buff, 1);

#else

			sprintf(buff, "DISPLAY=%s:%d.%d", inet_ntoa(our_addr), x_port, x_screen);

			putenv(buff);

#endif

		}

#endif

		dup2(s, 0);

		dup2(s, 1);

		dup2(s, 2);

		for (s = getdtablesize() - 1; s >= 3; s--)

		   close(s);

		i = 0;

		bptr = strdup(ex); /* No need to free() this */

		if (do_pty == 1) {

			/* Setup "slirp.telnetd -x" */

			argv[i++] = "slirp.telnetd";

			argv[i++] = "-x";

			argv[i++] = bptr;

		} else

		   do {

			/* Change the string into argv[] */

			curarg = bptr;

			while (*bptr != ' ' && *bptr != (char)0)

			   bptr++;

			c = *bptr;

			*bptr++ = (char)0;

			argv[i++] = strdup(curarg);

		   } while (c);

		argv[i] = 0;

		execvp(argv[0], argv);

		/* Ooops, failed, let's tell the user why */

		  {

			  char buff[256];

			  sprintf(buff, "Error: execvp of %s failed: %s\n",

				  argv[0], strerror(errno));

			  write(2, buff, strlen(buff)+1);

		  }

		close(0); close(1); close(2); /* XXX */

		exit(1);

	 default:

		if (do_pty == 2) {

			close(s);

			so->s = master;

		} else {

			/*

			 * XXX this could block us...

			 * XXX Should set a timer here, and if accept() doesn't

		 	 * return after X seconds, declare it a failure

		 	 * The only reason this will block forever is if socket()

		 	 * of connect() fail in the child process

		 	 */

                        do {

                            so->s = accept(s, (struct sockaddr *)&addr, &addrlen);

                        } while (so->s < 0 && errno == EINTR);

                        closesocket(s);

			opt = 1;

			setsockopt(so->s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int));

			opt = 1;

			setsockopt(so->s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));

		}

		fd_nonblock(so->s);

		/* Append the telnet options now */

		if (so->so_m != 0 && do_pty == 1)  {

			sbappend(so, so->so_m);

			so->so_m = 0;

		}

		return 1;

	}

}


static int bmdma_prepare_buf(IDEDMA *dma, int is_write)

{

    BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);

    IDEState *s = bmdma_active_if(bm);

    struct {

        uint32_t addr;

        uint32_t size;

    } prd;

    int l, len;

    qemu_sglist_init(&s->sg, s->nsector / (BMDMA_PAGE_SIZE / 512) + 1);

    s->io_buffer_size = 0;

    for(;;) {

        if (bm->cur_prd_len == 0) {

            /* end of table (with a fail safe of one page) */

            if (bm->cur_prd_last ||

                (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE)

                return s->io_buffer_size != 0;

            cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);

            bm->cur_addr += 8;

            prd.addr = le32_to_cpu(prd.addr);

            prd.size = le32_to_cpu(prd.size);

            len = prd.size & 0xfffe;

            if (len == 0)

                len = 0x10000;

            bm->cur_prd_len = len;

            bm->cur_prd_addr = prd.addr;

            bm->cur_prd_last = (prd.size & 0x80000000);

        }

        l = bm->cur_prd_len;

        if (l > 0) {

            qemu_sglist_add(&s->sg, bm->cur_prd_addr, l);

            bm->cur_prd_addr += l;

            bm->cur_prd_len -= l;

            s->io_buffer_size += l;

        }

    }

    return 1;

}


void timer_mod(QEMUTimer *ts, int64_t expire_time)

{

    timer_mod_ns(ts, expire_time * ts->scale);

}


ram_addr_t qemu_ram_alloc_from_ptr(DeviceState *dev, const char *name,

                        ram_addr_t size, void *host)

{

    RAMBlock *new_block, *block;

    size = TARGET_PAGE_ALIGN(size);

    new_block = qemu_mallocz(sizeof(*new_block));

    if (dev && dev->parent_bus && dev->parent_bus->info->get_dev_path) {

        char *id = dev->parent_bus->info->get_dev_path(dev);

        if (id) {

            snprintf(new_block->idstr, sizeof(new_block->idstr), "%s/", id);

            qemu_free(id);

        }

    }

    pstrcat(new_block->idstr, sizeof(new_block->idstr), name);

    QLIST_FOREACH(block, &ram_list.blocks, next) {

        if (!strcmp(block->idstr, new_block->idstr)) {

            fprintf(stderr, "RAMBlock \"%s\" already registered, abort!\n",

                    new_block->idstr);

            abort();

        }

    }

    new_block->host = host;

    new_block->offset = find_ram_offset(size);

    new_block->length = size;

    QLIST_INSERT_HEAD(&ram_list.blocks, new_block, next);

    ram_list.phys_dirty = qemu_realloc(ram_list.phys_dirty,

                                       last_ram_offset() >> TARGET_PAGE_BITS);

    memset(ram_list.phys_dirty + (new_block->offset >> TARGET_PAGE_BITS),

           0xff, size >> TARGET_PAGE_BITS);

    if (kvm_enabled())

        kvm_setup_guest_memory(new_block->host, size);

    return new_block->offset;

}


static bool qemu_opt_get_bool_helper(QemuOpts *opts, const char *name,

                                     bool defval, bool del)

{

    QemuOpt *opt = qemu_opt_find(opts, name);

    bool ret = defval;

    if (opt == NULL) {

        const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);

        if (desc && desc->def_value_str) {

            parse_option_bool(name, desc->def_value_str, &ret, &error_abort);

        }

        return ret;

    }

    assert(opt->desc && opt->desc->type == QEMU_OPT_BOOL);

    ret = opt->value.boolean;

    if (del) {

        qemu_opt_del_all(opts, name);

    }

    return ret;

}


static void tcg_out_reloc(TCGContext *s, tcg_insn_unit *code_ptr, int type,

                          int label_index, intptr_t addend)

{

    TCGLabel *l;

    TCGRelocation *r;

    l = &s->labels[label_index];

    if (l->has_value) {

        /* FIXME: This may break relocations on RISC targets that

           modify instruction fields in place.  The caller may not have

           written the initial value.  */

        patch_reloc(code_ptr, type, l->u.value, addend);

    } else {

        /* add a new relocation entry */

        r = tcg_malloc(sizeof(TCGRelocation));

        r->type = type;

        r->ptr = code_ptr;

        r->addend = addend;

        r->next = l->u.first_reloc;

        l->u.first_reloc = r;

    }

}


static int mov_write_packet(AVFormatContext *s, int stream_index,

                            const uint8_t *buf, int size, int64_t pts)

{

    MOVContext *mov = s->priv_data;

    ByteIOContext *pb = &s->pb;

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

    MOVTrack* trk = &mov->tracks[stream_index];

    int cl, id;

    unsigned int samplesInChunk = 0;

    if (url_is_streamed(&s->pb)) return 0; /* Can't handle that */

    if (!size) return 0; /* Discard 0 sized packets */

    if (enc->codec_type == CODEC_TYPE_VIDEO ) {

        samplesInChunk = 1;

    }

    else if (enc->codec_type == CODEC_TYPE_AUDIO ) {

        if( enc->codec_id == CODEC_ID_AMR_NB) {

            /* We must find out how many AMR blocks there are in one packet */

            static uint16_t packed_size[16] =

                {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};

            int len = 0;

            while (len < size && samplesInChunk < 100) {

                len += packed_size[(buf[len] >> 3) & 0x0F];

                samplesInChunk++;

            }

        }

        else if(enc->codec_id == CODEC_ID_PCM_ALAW) {

            samplesInChunk = size/enc->channels;

        }

        else {

            samplesInChunk = 1;

        }

    }

    if ((enc->codec_id == CODEC_ID_MPEG4 || enc->codec_id == CODEC_ID_AAC)

        && trk->vosLen == 0) {

        assert(enc->extradata_size);

        trk->vosLen = enc->extradata_size;

        trk->vosData = av_malloc(trk->vosLen);

        memcpy(trk->vosData, enc->extradata, trk->vosLen);

    }

    cl = trk->entry / MOV_INDEX_CLUSTER_SIZE;

    id = trk->entry % MOV_INDEX_CLUSTER_SIZE;

    if (trk->ents_allocated <= trk->entry) {

        trk->cluster = av_realloc(trk->cluster, (cl+1)*sizeof(void*));

        if (!trk->cluster)

            return -1;

        trk->cluster[cl] = av_malloc(MOV_INDEX_CLUSTER_SIZE*sizeof(MOVIentry));

        if (!trk->cluster[cl])

            return -1;

        trk->ents_allocated += MOV_INDEX_CLUSTER_SIZE;

    }

    if (mov->mdat_written == 0) {

        mov_write_mdat_tag(pb, mov);

        mov->mdat_written = 1;

        mov->time = Timestamp();

    }

    trk->cluster[cl][id].pos = url_ftell(pb) - mov->movi_list;

    trk->cluster[cl][id].samplesInChunk = samplesInChunk;

    trk->cluster[cl][id].size = size;

    trk->cluster[cl][id].entries = samplesInChunk;

    if(enc->codec_type == CODEC_TYPE_VIDEO) {

        trk->cluster[cl][id].key_frame = enc->coded_frame->key_frame;

        if(enc->coded_frame->pict_type == FF_I_TYPE)

            trk->hasKeyframes = 1;

    }

    trk->enc = enc;

    trk->entry++;

    trk->sampleCount += samplesInChunk;

    trk->mdat_size += size;

    put_buffer(pb, buf, size);

    put_flush_packet(pb);

    return 0;

}


static uint32_t nvdimm_get_max_xfer_label_size(void)

{

    uint32_t max_get_size, max_set_size, dsm_memory_size = 4096;

    /*

     * the max data ACPI can read one time which is transferred by

     * the response of 'Get Namespace Label Data' function.

     */

    max_get_size = dsm_memory_size - sizeof(NvdimmFuncGetLabelDataOut);

    /*

     * the max data ACPI can write one time which is transferred by

     * 'Set Namespace Label Data' function.

     */

    max_set_size = dsm_memory_size - offsetof(NvdimmDsmIn, arg3) -

                   sizeof(NvdimmFuncSetLabelDataIn);

    return MIN(max_get_size, max_set_size);

}


static void imx_fec_write(void *opaque, hwaddr addr,

                          uint64_t value, unsigned size)

{

    IMXFECState *s = IMX_FEC(opaque);

    FEC_PRINTF("writing 0x%08x @ 0x%" HWADDR_PRIx "\n", (int)value, addr);

    switch (addr & 0x3ff) {

    case 0x004: /* EIR */

        s->eir &= ~value;

        break;

    case 0x008: /* EIMR */

        s->eimr = value;

        break;

    case 0x010: /* RDAR */

        if ((s->ecr & FEC_EN) && !s->rx_enabled) {

            imx_fec_enable_rx(s);

        }

        break;

    case 0x014: /* TDAR */

        if (s->ecr & FEC_EN) {

            imx_fec_do_tx(s);

        }

        break;

    case 0x024: /* ECR */

        s->ecr = value;

        if (value & FEC_RESET) {

            imx_fec_reset(DEVICE(s));

        }

        if ((s->ecr & FEC_EN) == 0) {

            s->rx_enabled = 0;

        }

        break;

    case 0x040: /* MMFR */

        /* store the value */

        s->mmfr = value;

        if (extract32(value, 28, 1)) {

            do_phy_write(s, extract32(value, 18, 9), extract32(value, 0, 16));

        } else {

            s->mmfr = do_phy_read(s, extract32(value, 18, 9));

        }

        /* raise the interrupt as the PHY operation is done */

        s->eir |= FEC_INT_MII;

        break;

    case 0x044: /* MSCR */

        s->mscr = value & 0xfe;

        break;

    case 0x064: /* MIBC */

        /* TODO: Implement MIB.  */

        s->mibc = (value & 0x80000000) ? 0xc0000000 : 0;

        break;

    case 0x084: /* RCR */

        s->rcr = value & 0x07ff003f;

        /* TODO: Implement LOOP mode.  */

        break;

    case 0x0c4: /* TCR */

        /* We transmit immediately, so raise GRA immediately.  */

        s->tcr = value;

        if (value & 1) {

            s->eir |= FEC_INT_GRA;

        }

        break;

    case 0x0e4: /* PALR */

        s->conf.macaddr.a[0] = value >> 24;

        s->conf.macaddr.a[1] = value >> 16;

        s->conf.macaddr.a[2] = value >> 8;

        s->conf.macaddr.a[3] = value;

        break;

    case 0x0e8: /* PAUR */

        s->conf.macaddr.a[4] = value >> 24;

        s->conf.macaddr.a[5] = value >> 16;

        break;

    case 0x0ec: /* OPDR */

        break;

    case 0x118: /* IAUR */

    case 0x11c: /* IALR */

    case 0x120: /* GAUR */

    case 0x124: /* GALR */

        /* TODO: implement MAC hash filtering.  */

        break;

    case 0x144: /* TFWR */

        s->tfwr = value & 3;

        break;

    case 0x14c: /* FRBR */

        /* FRBR writes ignored.  */

        break;

    case 0x150: /* FRSR */

        s->frsr = (value & 0x3fc) | 0x400;

        break;

    case 0x180: /* ERDSR */

        s->erdsr = value & ~3;

        s->rx_descriptor = s->erdsr;

        break;

    case 0x184: /* ETDSR */

        s->etdsr = value & ~3;

        s->tx_descriptor = s->etdsr;

        break;

    case 0x188: /* EMRBR */

        s->emrbr = value & 0x7f0;

        break;

    case 0x300: /* MIIGSK_CFGR */

        s->miigsk_cfgr = value & 0x53;

        break;

    case 0x308: /* MIIGSK_ENR */

        s->miigsk_enr = (value & 0x2) ? 0x6 : 0;

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR, "[%s]%s: Bad address at offset 0x%"

                      HWADDR_PRIx "\n", TYPE_IMX_FEC, __func__, addr);

        break;

    }

    imx_fec_update(s);

}


static void replay_enable(const char *fname, int mode)

{

    const char *fmode = NULL;

    assert(!replay_file);

    switch (mode) {

    case REPLAY_MODE_RECORD:

        fmode = "wb";

        break;

    case REPLAY_MODE_PLAY:

        fmode = "rb";

        break;

    default:

        fprintf(stderr, "Replay: internal error: invalid replay mode\n");

        exit(1);

    }

    atexit(replay_finish);

    replay_mutex_init();

    replay_file = fopen(fname, fmode);

    if (replay_file == NULL) {

        fprintf(stderr, "Replay: open %s: %s\n", fname, strerror(errno));

        exit(1);

    }

    replay_filename = g_strdup(fname);

    replay_mode = mode;

    replay_data_kind = -1;

    replay_state.instructions_count = 0;

    replay_state.current_step = 0;

    /* skip file header for RECORD and check it for PLAY */

    if (replay_mode == REPLAY_MODE_RECORD) {

        fseek(replay_file, HEADER_SIZE, SEEK_SET);

    } else if (replay_mode == REPLAY_MODE_PLAY) {

        unsigned int version = replay_get_dword();

        if (version != REPLAY_VERSION) {

            fprintf(stderr, "Replay: invalid input log file version\n");

            exit(1);

        }

        /* go to the beginning */

        fseek(replay_file, HEADER_SIZE, SEEK_SET);

        replay_fetch_data_kind();

    }

    replay_init_events();

}


static bool raw_is_inserted(BlockDriverState *bs)

{

    return bdrv_is_inserted(bs->file->bs);

}


static int block_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)

{

    int ret;

    DPRINTF("Enter save live stage %d submitted %d transferred %d\n",

            stage, block_mig_state.submitted, block_mig_state.transferred);

    if (stage < 0) {

        blk_mig_cleanup(mon);

        return 0;

    }

    if (block_mig_state.blk_enable != 1) {

        /* no need to migrate storage */

        qemu_put_be64(f, BLK_MIG_FLAG_EOS);

        return 1;

    }

    if (stage == 1) {

        init_blk_migration(mon, f);

        /* start track dirty blocks */

        set_dirty_tracking(1);

    }

    flush_blks(f);

    ret = qemu_file_get_error(f);

    if (ret) {

        blk_mig_cleanup(mon);

        return ret;

    }

    blk_mig_reset_dirty_cursor();

    if (stage == 2) {

        /* control the rate of transfer */

        while ((block_mig_state.submitted +

                block_mig_state.read_done) * BLOCK_SIZE <

               qemu_file_get_rate_limit(f)) {

            if (block_mig_state.bulk_completed == 0) {

                /* first finish the bulk phase */

                if (blk_mig_save_bulked_block(mon, f) == 0) {

                    /* finished saving bulk on all devices */

                    block_mig_state.bulk_completed = 1;

                }

            } else {

                if (blk_mig_save_dirty_block(mon, f, 1) == 0) {

                    /* no more dirty blocks */

                    break;

                }

            }

        }

        flush_blks(f);

        ret = qemu_file_get_error(f);

        if (ret) {

            blk_mig_cleanup(mon);

            return ret;

        }

    }

    if (stage == 3) {

        /* we know for sure that save bulk is completed and

           all async read completed */

        assert(block_mig_state.submitted == 0);

        while (blk_mig_save_dirty_block(mon, f, 0) != 0);

        blk_mig_cleanup(mon);

        /* report completion */

        qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);

        ret = qemu_file_get_error(f);

        if (ret) {

            return ret;

        }

        monitor_printf(mon, "Block migration completed\n");

    }

    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

    return ((stage == 2) && is_stage2_completed());

}


int qemu_config_parse(FILE *fp, QemuOptsList **lists, const char *fname)

{

    char line[1024], group[64], id[64], arg[64], value[1024];

    Location loc;

    QemuOptsList *list = NULL;

    Error *local_err = NULL;

    QemuOpts *opts = NULL;

    int res = -1, lno = 0;

    loc_push_none(&loc);

    while (fgets(line, sizeof(line), fp) != NULL) {

        loc_set_file(fname, ++lno);

        if (line[0] == '\n') {

            /* skip empty lines */

            continue;

        }

        if (line[0] == '#') {

            /* comment */

            continue;

        }

        if (sscanf(line, "[%63s \"%63[^\"]\"]", group, id) == 2) {

            /* group with id */

            list = find_list(lists, group, &local_err);

            if (local_err) {

                error_report_err(local_err);

                goto out;

            }

            opts = qemu_opts_create(list, id, 1, NULL);

            continue;

        }

        if (sscanf(line, "[%63[^]]]", group) == 1) {

            /* group without id */

            list = find_list(lists, group, &local_err);

            if (local_err) {

                error_report_err(local_err);

                goto out;

            }

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

            continue;

        }

        value[0] = '\0';

        if (sscanf(line, " %63s = \"%1023[^\"]\"", arg, value) == 2 ||

            sscanf(line, " %63s = \"\"", arg) == 1) {

            /* arg = value */

            if (opts == NULL) {

                error_report("no group defined");

                goto out;

            }

            qemu_opt_set(opts, arg, value, &local_err);

            if (local_err) {

                error_report_err(local_err);

                goto out;

            }

            continue;

        }

        error_report("parse error");

        goto out;

    }

    if (ferror(fp)) {

        error_report("error reading file");

        goto out;

    }

    res = 0;

out:

    loc_pop(&loc);

    return res;

}


static void qmp_input_check_struct(Visitor *v, Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

    StackObject *tos = &qiv->stack[qiv->nb_stack - 1];

    assert(qiv->nb_stack > 0);

    if (qiv->strict) {

        GHashTable *const top_ht = tos->h;

        if (top_ht) {

            GHashTableIter iter;

            const char *key;

            g_hash_table_iter_init(&iter, top_ht);

            if (g_hash_table_iter_next(&iter, (void **)&key, NULL)) {

                error_setg(errp, QERR_QMP_EXTRA_MEMBER, key);

            }

        }

    }

}


int ff_get_line(AVIOContext *s, char *buf, int maxlen)

{

    int i = 0;

    char c;

    do {

        c = avio_r8(s);

        if (c && i < maxlen-1)

            buf[i++] = c;

    } while (c != '\n' && c != '\r' && c);

    if (c == '\r' && avio_r8(s) != '\n')

        avio_skip(s, -1);

    buf[i] = 0;

    return i;

}


e1000e_intrmgr_delay_tx_causes(E1000ECore *core, uint32_t *causes)

{

    static const uint32_t delayable_causes = E1000_ICR_TXQ0 |

                                             E1000_ICR_TXQ1 |

                                             E1000_ICR_TXQE |

                                             E1000_ICR_TXDW;

    if (msix_enabled(core->owner)) {

        return false;

    }

    /* Clean up all causes that may be delayed */

    core->delayed_causes |= *causes & delayable_causes;

    *causes &= ~delayable_causes;

    /* If there are causes that cannot be delayed */

    if (causes != 0) {

        return false;

    }

    /* All causes delayed */

    e1000e_intrmgr_rearm_timer(&core->tidv);

    if (!core->tadv.running && (core->mac[TADV] != 0)) {

        e1000e_intrmgr_rearm_timer(&core->tadv);

    }

    return true;

}


static int qcow2_make_empty(BlockDriverState *bs)

{

    BDRVQcow2State *s = bs->opaque;

    uint64_t start_sector;

    int sector_step = INT_MAX / BDRV_SECTOR_SIZE;

    int l1_clusters, ret = 0;

    l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));

    if (s->qcow_version >= 3 && !s->snapshots &&

        3 + l1_clusters <= s->refcount_block_size) {

        /* The following function only works for qcow2 v3 images (it requires

         * the dirty flag) and only as long as there are no snapshots (because

         * it completely empties the image). Furthermore, the L1 table and three

         * additional clusters (image header, refcount table, one refcount

         * block) have to fit inside one refcount block. */

        return make_completely_empty(bs);

    }

    /* This fallback code simply discards every active cluster; this is slow,

     * but works in all cases */

    for (start_sector = 0; start_sector < bs->total_sectors;

         start_sector += sector_step)

    {

        /* As this function is generally used after committing an external

         * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the

         * default action for this kind of discard is to pass the discard,

         * which will ideally result in an actually smaller image file, as

         * is probably desired. */

        ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,

                                     MIN(sector_step,

                                         bs->total_sectors - start_sector),

                                     QCOW2_DISCARD_SNAPSHOT, true);

        if (ret < 0) {

            break;

        }

    }

    return ret;

}


static void s390_cpu_full_reset(CPUState *s)

{

    S390CPU *cpu = S390_CPU(s);

    S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);

    CPUS390XState *env = &cpu->env;

    int i;

    scc->parent_reset(s);

    cpu->env.sigp_order = 0;

    s390_cpu_set_state(CPU_STATE_STOPPED, cpu);

    memset(env, 0, offsetof(CPUS390XState, end_reset_fields));

    /* architectured initial values for CR 0 and 14 */

    env->cregs[0] = CR0_RESET;

    env->cregs[14] = CR14_RESET;

    /* architectured initial value for Breaking-Event-Address register */

    env->gbea = 1;

    env->pfault_token = -1UL;

    env->ext_index = -1;

    for (i = 0; i < ARRAY_SIZE(env->io_index); i++) {

        env->io_index[i] = -1;

    }

    env->mchk_index = -1;

    /* tininess for underflow is detected before rounding */

    set_float_detect_tininess(float_tininess_before_rounding,

                              &env->fpu_status);

    /* Reset state inside the kernel that we cannot access yet from QEMU. */

    if (kvm_enabled()) {

        kvm_s390_reset_vcpu(cpu);

    }

}


static bool ufd_version_check(int ufd)

{

    struct uffdio_api api_struct;

    uint64_t ioctl_mask;

    api_struct.api = UFFD_API;

    api_struct.features = 0;

    if (ioctl(ufd, UFFDIO_API, &api_struct)) {

        error_report("postcopy_ram_supported_by_host: UFFDIO_API failed: %s",

                     strerror(errno));

        return false;

    }

    ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |

                 (__u64)1 << _UFFDIO_UNREGISTER;

    if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {

        error_report("Missing userfault features: %" PRIx64,

                     (uint64_t)(~api_struct.ioctls & ioctl_mask));

        return false;

    }

    if (getpagesize() != ram_pagesize_summary()) {

        bool have_hp = false;

        /* We've got a huge page */

#ifdef UFFD_FEATURE_MISSING_HUGETLBFS

        have_hp = api_struct.features & UFFD_FEATURE_MISSING_HUGETLBFS;

#endif

        if (!have_hp) {

            error_report("Userfault on this host does not support huge pages");

            return false;

        }

    }

    return true;

}


static void string_output_append(StringOutputVisitor *sov, int64_t a)

{

    Range *r = g_malloc0(sizeof(*r));

    r->begin = a;

    r->end = a + 1;

    sov->ranges = range_list_insert(sov->ranges, r);

}


static void aarch64_cpu_register(const ARMCPUInfo *info)

{

    TypeInfo type_info = {

        .parent = TYPE_AARCH64_CPU,

        .instance_size = sizeof(ARMCPU),

        .instance_init = info->initfn,

        .class_size = sizeof(ARMCPUClass),

        .class_init = info->class_init,

    };

    /* TODO: drop when we support more CPUs - all entries will have name set */

    if (!info->name) {

        return;

    }

    type_info.name = g_strdup_printf("%s-" TYPE_ARM_CPU, info->name);

    type_register(&type_info);

    g_free((void *)type_info.name);

}


static void tx_fifo_push(lan9118_state *s, uint32_t val)

{

    int n;

    if (s->txp->fifo_used == s->tx_fifo_size) {

        s->int_sts |= TDFO_INT;

        return;

    }

    switch (s->txp->state) {

    case TX_IDLE:

        s->txp->cmd_a = val & 0x831f37ff;

        s->txp->fifo_used++;

        s->txp->state = TX_B;

        s->txp->buffer_size = extract32(s->txp->cmd_a, 0, 11);

        s->txp->offset = extract32(s->txp->cmd_a, 16, 5);

        break;

    case TX_B:

        if (s->txp->cmd_a & 0x2000) {

            /* First segment */

            s->txp->cmd_b = val;

            s->txp->fifo_used++;

            /* End alignment does not include command words.  */

            n = (s->txp->buffer_size + s->txp->offset + 3) >> 2;

            switch ((n >> 24) & 3) {

            case 1:

                n = (-n) & 3;

                break;

            case 2:

                n = (-n) & 7;

                break;

            default:

                n = 0;

            }

            s->txp->pad = n;

            s->txp->len = 0;

        }

        DPRINTF("Block len:%d offset:%d pad:%d cmd %08x\n",

                s->txp->buffer_size, s->txp->offset, s->txp->pad,

                s->txp->cmd_a);

        s->txp->state = TX_DATA;

        break;

    case TX_DATA:

        if (s->txp->offset >= 4) {

            s->txp->offset -= 4;

            break;

        }

        if (s->txp->buffer_size <= 0 && s->txp->pad != 0) {

            s->txp->pad--;

        } else {

            n = 4;

            while (s->txp->offset) {

                val >>= 8;

                n--;

                s->txp->offset--;

            }

            /* Documentation is somewhat unclear on the ordering of bytes

               in FIFO words.  Empirical results show it to be little-endian.

               */

            /* TODO: FIFO overflow checking.  */

            while (n--) {

                s->txp->data[s->txp->len] = val & 0xff;

                s->txp->len++;

                val >>= 8;

                s->txp->buffer_size--;

            }

            s->txp->fifo_used++;

        }

        if (s->txp->buffer_size <= 0 && s->txp->pad == 0) {

            if (s->txp->cmd_a & 0x1000) {

                do_tx_packet(s);

            }

            if (s->txp->cmd_a & 0x80000000) {

                s->int_sts |= TX_IOC_INT;

            }

            s->txp->state = TX_IDLE;

        }

        break;

    }

}


int ff_h264_decode_ref_pic_list_reordering(H264Context *h)

{

    int list, index, pic_structure, i;

    print_short_term(h);

    print_long_term(h);

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

        for (i = 0; i < h->ref_count[list]; i++)

            COPY_PICTURE(&h->ref_list[list][i], &h->default_ref_list[list][i]);

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

            int pred = h->curr_pic_num;

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

                unsigned int reordering_of_pic_nums_idc = get_ue_golomb_31(&h->gb);

                unsigned int pic_id;

                int i;

                Picture *ref = NULL;

                if (reordering_of_pic_nums_idc == 3)

                    break;

                if (index >= h->ref_count[list]) {

                    av_log(h->avctx, AV_LOG_ERROR, "reference count overflow\n");

                    return -1;

                }

                if (reordering_of_pic_nums_idc < 3) {

                    if (reordering_of_pic_nums_idc < 2) {

                        const unsigned int abs_diff_pic_num = get_ue_golomb(&h->gb) + 1;

                        int frame_num;

                        if (abs_diff_pic_num > h->max_pic_num) {

                            av_log(h->avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");

                            return -1;

                        }

                        if (reordering_of_pic_nums_idc == 0)

                            pred -= abs_diff_pic_num;

                        else

                            pred += abs_diff_pic_num;

                        pred &= h->max_pic_num - 1;

                        frame_num = pic_num_extract(h, pred, &pic_structure);

                        for (i = h->short_ref_count - 1; i >= 0; i--) {

                            ref = h->short_ref[i];

                            assert(ref->reference);

                            assert(!ref->long_ref);

                            if (ref->frame_num == frame_num &&

                                (ref->reference & pic_structure))

                                break;

                        }

                        if (i >= 0)

                            ref->pic_id = pred;

                    } else {

                        int long_idx;

                        pic_id = get_ue_golomb(&h->gb); //long_term_pic_idx

                        long_idx = pic_num_extract(h, pic_id, &pic_structure);

                        if (long_idx > 31) {

                            av_log(h->avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");

                            return -1;

                        }

                        ref = h->long_ref[long_idx];

                        assert(!(ref && !ref->reference));

                        if (ref && (ref->reference & pic_structure)) {

                            ref->pic_id = pic_id;

                            assert(ref->long_ref);

                            i = 0;

                        } else {

                            i = -1;

                        }

                    }

                    if (i < 0) {

                        av_log(h->avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");

                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME

                    } else {

                        for (i = index; i + 1 < h->ref_count[list]; i++) {

                            if (ref->long_ref == h->ref_list[list][i].long_ref &&

                                ref->pic_id   == h->ref_list[list][i].pic_id)

                                break;

                        }

                        for (; i > index; i--) {

                            COPY_PICTURE(&h->ref_list[list][i], &h->ref_list[list][i - 1]);

                        }

                        COPY_PICTURE(&h->ref_list[list][index], ref);

                        if (FIELD_PICTURE(h)) {

                            pic_as_field(&h->ref_list[list][index], pic_structure);

                        }

                    }

                } else {

                    av_log(h->avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");

                    return -1;

                }

            }

        }

    }

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

        for (index = 0; index < h->ref_count[list]; index++) {

            if (!h->ref_list[list][index].f.data[0]) {

                av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture\n");

                if (h->default_ref_list[list][0].f.data[0])

                    COPY_PICTURE(&h->ref_list[list][index], &h->default_ref_list[list][0]);

                else

                    return -1;

            }

        }

    }

    return 0;

}


static enum AVHWDeviceType hw_device_match_type_by_hwaccel(enum HWAccelID hwaccel_id)

{

    int i;

    if (hwaccel_id == HWACCEL_NONE)

        return AV_HWDEVICE_TYPE_NONE;

    for (i = 0; hwaccels[i].name; i++) {

        if (hwaccels[i].id == hwaccel_id)

            return hwaccels[i].device_type;

    }

    return AV_HWDEVICE_TYPE_NONE;

}


int swr_convert(struct SwrContext *s, uint8_t *out_arg[SWR_CH_MAX], int out_count,

                                const uint8_t *in_arg [SWR_CH_MAX], int  in_count){

    AudioData * in= &s->in;

    AudioData *out= &s->out;

    if(s->drop_output > 0){

        int ret;

        uint8_t *tmp_arg[SWR_CH_MAX];

        if((ret=swri_realloc_audio(&s->drop_temp, s->drop_output))<0)

            return ret;

        reversefill_audiodata(&s->drop_temp, tmp_arg);

        s->drop_output *= -1; //FIXME find a less hackish solution

        ret = swr_convert(s, tmp_arg, -s->drop_output, in_arg, in_count); //FIXME optimize but this is as good as never called so maybe it doesnt matter

        s->drop_output *= -1;

        if(ret>0)

            s->drop_output -= ret;

        if(s->drop_output || !out_arg)

            return 0;

        in_count = 0;

    }

    if(!in_arg){

        if(s->resample){

            if (!s->flushed)

                s->resampler->flush(s);

            s->resample_in_constraint = 0;

            s->flushed = 1;

        }else if(!s->in_buffer_count){

            return 0;

        }

    }else

        fill_audiodata(in ,  (void*)in_arg);

    fill_audiodata(out, out_arg);

    if(s->resample){

        int ret = swr_convert_internal(s, out, out_count, in, in_count);

        if(ret>0 && !s->drop_output)

            s->outpts += ret * (int64_t)s->in_sample_rate;

        return ret;

    }else{

        AudioData tmp= *in;

        int ret2=0;

        int ret, size;

        size = FFMIN(out_count, s->in_buffer_count);

        if(size){

            buf_set(&tmp, &s->in_buffer, s->in_buffer_index);

            ret= swr_convert_internal(s, out, size, &tmp, size);

            if(ret<0)

                return ret;

            ret2= ret;

            s->in_buffer_count -= ret;

            s->in_buffer_index += ret;

            buf_set(out, out, ret);

            out_count -= ret;

            if(!s->in_buffer_count)

                s->in_buffer_index = 0;

        }

        if(in_count){

            size= s->in_buffer_index + s->in_buffer_count + in_count - out_count;

            if(in_count > out_count) { //FIXME move after swr_convert_internal

                if(   size > s->in_buffer.count

                && s->in_buffer_count + in_count - out_count <= s->in_buffer_index){

                    buf_set(&tmp, &s->in_buffer, s->in_buffer_index);

                    copy(&s->in_buffer, &tmp, s->in_buffer_count);

                    s->in_buffer_index=0;

                }else

                    if((ret=swri_realloc_audio(&s->in_buffer, size)) < 0)

                        return ret;

            }

            if(out_count){

                size = FFMIN(in_count, out_count);

                ret= swr_convert_internal(s, out, size, in, size);

                if(ret<0)

                    return ret;

                buf_set(in, in, ret);

                in_count -= ret;

                ret2 += ret;

            }

            if(in_count){

                buf_set(&tmp, &s->in_buffer, s->in_buffer_index + s->in_buffer_count);

                copy(&tmp, in, in_count);

                s->in_buffer_count += in_count;

            }

        }

        if(ret2>0 && !s->drop_output)

            s->outpts += ret2 * (int64_t)s->in_sample_rate;

        return ret2;

    }

}


av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)

{

    MJpegDecodeContext *s = avctx->priv_data;

    int ret;

    if (!s->picture_ptr) {

        s->picture = av_frame_alloc();

        if (!s->picture)

            return AVERROR(ENOMEM);

        s->picture_ptr = s->picture;

    }

    s->avctx = avctx;

    ff_blockdsp_init(&s->bdsp, avctx);

    ff_hpeldsp_init(&s->hdsp, avctx->flags);

    ff_idctdsp_init(&s->idsp, avctx);

    ff_init_scantable(s->idsp.idct_permutation, &s->scantable,

                      ff_zigzag_direct);

    s->buffer_size   = 0;

    s->buffer        = NULL;

    s->start_code    = -1;

    s->first_picture = 1;

    s->org_height    = avctx->coded_height;

    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;

    avctx->colorspace = AVCOL_SPC_BT470BG;

    if ((ret = build_basic_mjpeg_vlc(s)) < 0)

        return ret;

    if (s->extern_huff) {

        av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");

        if ((ret = init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8)) < 0)

            return ret;

        if ((ret = ff_mjpeg_decode_dht(s))) {

            av_log(avctx, AV_LOG_ERROR,

                   "mjpeg: error using external huffman table\n");

            return ret;

        }

    }

    if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */

        s->interlace_polarity = 1;           /* bottom field first */

        av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");

    }

    if (avctx->codec->id == AV_CODEC_ID_AMV)

        s->flipped = 1;

    return 0;

}


static int seg_write_trailer(struct AVFormatContext *s)

{

    SegmentContext *seg = s->priv_data;

    AVFormatContext *oc = seg->avf;

    int ret = 0;

    if (!oc)

        goto fail;

    if (!seg->write_header_trailer) {

        if ((ret = segment_end(oc, 0)) < 0)

            goto fail;

        open_null_ctx(&oc->pb);

        ret = av_write_trailer(oc);

        close_null_ctx(oc->pb);

    } else {

        ret = segment_end(oc, 1);

    }

    if (ret < 0)

        goto fail;

    if (seg->list && seg->list_type == LIST_HLS) {

        if ((ret = segment_hls_window(s, 1) < 0))

            goto fail;

    }

fail:

    avio_close(seg->pb);

    avformat_free_context(oc);

    return ret;

}


int ff_tempfile(const char *prefix, char **filename) {

    int fd=-1;

#if !HAVE_MKSTEMP

    *filename = tempnam(".", prefix);

#else

    size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */

    *filename = av_malloc(len);

#endif

    /* -----common section-----*/

    if (*filename == NULL) {

        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");

        return -1;

    }

#if !HAVE_MKSTEMP

    fd = avpriv_open(*filename, O_RDWR | O_BINARY | O_CREAT, 0444);

#else

    snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);

    fd = mkstemp(*filename);

    if (fd < 0) {

        snprintf(*filename, len, "./%sXXXXXX", prefix);

        fd = mkstemp(*filename);

    }

#endif

    /* -----common section-----*/

    if (fd < 0) {

        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);

        return -1;

    }

    return fd; /* success */

}


static void ffm_seek1(AVFormatContext *s, int64_t pos1)

{

    FFMContext *ffm = s->priv_data;

    ByteIOContext *pb = s->pb;

    int64_t pos;

    pos = pos1 + ffm->write_index;

    if (pos >= ffm->file_size)

        pos -= (ffm->file_size - FFM_PACKET_SIZE);

#ifdef DEBUG_SEEK

    av_log(s, AV_LOG_DEBUG, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);

#endif

    url_fseek(pb, pos, SEEK_SET);

}


static int decode_init(AVCodecContext * avctx)

{

    MPADecodeContext *s = avctx->priv_data;

    static int init=0;

    int i, j, k;

#if defined(USE_HIGHPRECISION) && defined(CONFIG_AUDIO_NONSHORT)

    avctx->sample_fmt= SAMPLE_FMT_S32;

#else

    avctx->sample_fmt= SAMPLE_FMT_S16;

#endif

    if(avctx->antialias_algo != FF_AA_FLOAT)

        s->compute_antialias= compute_antialias_integer;

    else

        s->compute_antialias= compute_antialias_float;

    if (!init && !avctx->parse_only) {

        /* scale factors table for layer 1/2 */

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

            int shift, mod;

            /* 1.0 (i = 3) is normalized to 2 ^ FRAC_BITS */

            shift = (i / 3);

            mod = i % 3;

            scale_factor_modshift[i] = mod | (shift << 2);

        }

        /* scale factor multiply for layer 1 */

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

            int n, norm;

            n = i + 2;

            norm = ((int64_t_C(1) << n) * FRAC_ONE) / ((1 << n) - 1);

            scale_factor_mult[i][0] = MULL(FIXR(1.0 * 2.0), norm);

            scale_factor_mult[i][1] = MULL(FIXR(0.7937005259 * 2.0), norm);

            scale_factor_mult[i][2] = MULL(FIXR(0.6299605249 * 2.0), norm);

            dprintf("%d: norm=%x s=%x %x %x\n",

                    i, norm,

                    scale_factor_mult[i][0],

                    scale_factor_mult[i][1],

                    scale_factor_mult[i][2]);

        }

        ff_mpa_synth_init(window);

        /* huffman decode tables */

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

            const HuffTable *h = &mpa_huff_tables[i];

            int xsize, x, y;

            unsigned int n;

            uint8_t tmp_bits [256];

            uint16_t tmp_codes[256];

            memset(tmp_bits , 0, sizeof(tmp_bits ));

            memset(tmp_codes, 0, sizeof(tmp_codes));

            xsize = h->xsize;

            n = xsize * xsize;

            j = 0;

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

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

                    tmp_bits [(x << 4) | y]= h->bits [j  ];

                    tmp_codes[(x << 4) | y]= h->codes[j++];

                }

            }

            /* XXX: fail test */

            init_vlc(&huff_vlc[i], 7, 256,

                     tmp_bits, 1, 1, tmp_codes, 2, 2, 1);

        }

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

            init_vlc(&huff_quad_vlc[i], i == 0 ? 7 : 4, 16,

                     mpa_quad_bits[i], 1, 1, mpa_quad_codes[i], 1, 1, 1);

        }

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

            k = 0;

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

                band_index_long[i][j] = k;

                k += band_size_long[i][j];

            }

            band_index_long[i][22] = k;

        }

        /* compute n ^ (4/3) and store it in mantissa/exp format */

        table_4_3_exp= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_exp[0]));

        if(!table_4_3_exp)

            return -1;

        table_4_3_value= av_mallocz_static(TABLE_4_3_SIZE * sizeof(table_4_3_value[0]));

        if(!table_4_3_value)

            return -1;

        int_pow_init();

        for(i=1;i<TABLE_4_3_SIZE;i++) {

            double f, fm;

            int e, m;

            f = pow((double)(i/4), 4.0 / 3.0) * pow(2, (i&3)*0.25);

            fm = frexp(f, &e);

            m = (uint32_t)(fm*(1LL<<31) + 0.5);

            e+= FRAC_BITS - 31 + 5;

            /* normalized to FRAC_BITS */

            table_4_3_value[i] = m;

//            av_log(NULL, AV_LOG_DEBUG, "%d %d %f\n", i, m, pow((double)i, 4.0 / 3.0));

            table_4_3_exp[i] = -e;

        }

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

            int exponent= (i>>4)-400;

            double f= pow(i&15, 4.0 / 3.0) * pow(2, exponent*0.25 + FRAC_BITS + 5);

            expval_table[exponent+400][i&15]= lrintf(f);

            if((i&15)==1)

                exp_table[exponent+400]= lrintf(f);

        }

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

            float f;

            int v;

            if (i != 6) {

                f = tan((double)i * M_PI / 12.0);

                v = FIXR(f / (1.0 + f));

            } else {

                v = FIXR(1.0);

            }

            is_table[0][i] = v;

            is_table[1][6 - i] = v;

        }

        /* invalid values */

        for(i=7;i<16;i++)

            is_table[0][i] = is_table[1][i] = 0.0;

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

            double f;

            int e, k;

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

                e = -(j + 1) * ((i + 1) >> 1);

                f = pow(2.0, e / 4.0);

                k = i & 1;

                is_table_lsf[j][k ^ 1][i] = FIXR(f);

                is_table_lsf[j][k][i] = FIXR(1.0);

                dprintf("is_table_lsf %d %d: %x %x\n",

                        i, j, is_table_lsf[j][0][i], is_table_lsf[j][1][i]);

            }

        }

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

            float ci, cs, ca;

            ci = ci_table[i];

            cs = 1.0 / sqrt(1.0 + ci * ci);

            ca = cs * ci;

            csa_table[i][0] = FIXHR(cs/4);

            csa_table[i][1] = FIXHR(ca/4);

            csa_table[i][2] = FIXHR(ca/4) + FIXHR(cs/4);

            csa_table[i][3] = FIXHR(ca/4) - FIXHR(cs/4);

            csa_table_float[i][0] = cs;

            csa_table_float[i][1] = ca;

            csa_table_float[i][2] = ca + cs;

            csa_table_float[i][3] = ca - cs;

//            printf("%d %d %d %d\n", FIX(cs), FIX(cs-1), FIX(ca), FIX(cs)-FIX(ca));

//            av_log(NULL, AV_LOG_DEBUG,"%f %f %f %f\n", cs, ca, ca+cs, ca-cs);

        }

        /* compute mdct windows */

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

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

                double d;

                if(j==2 && i%3 != 1)

                    continue;

                d= sin(M_PI * (i + 0.5) / 36.0);

                if(j==1){

                    if     (i>=30) d= 0;

                    else if(i>=24) d= sin(M_PI * (i - 18 + 0.5) / 12.0);

                    else if(i>=18) d= 1;

                }else if(j==3){

                    if     (i<  6) d= 0;

                    else if(i< 12) d= sin(M_PI * (i -  6 + 0.5) / 12.0);

                    else if(i< 18) d= 1;

                }

                //merge last stage of imdct into the window coefficients

                d*= 0.5 / cos(M_PI*(2*i + 19)/72);

                if(j==2)

                    mdct_win[j][i/3] = FIXHR((d / (1<<5)));

                else

                    mdct_win[j][i  ] = FIXHR((d / (1<<5)));

//                av_log(NULL, AV_LOG_DEBUG, "%2d %d %f\n", i,j,d / (1<<5));

            }

        }

        /* NOTE: we do frequency inversion adter the MDCT by changing

           the sign of the right window coefs */

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

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

                mdct_win[j + 4][i] = mdct_win[j][i];

                mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];

            }

        }

#if defined(DEBUG)

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

            av_log(avctx, AV_LOG_DEBUG, "win%d=\n", j);

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

                av_log(avctx, AV_LOG_DEBUG, "%f, ", (double)mdct_win[j][i] / FRAC_ONE);

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

        }

#endif

        init = 1;

    }

    s->inbuf_index = 0;

    s->inbuf = &s->inbuf1[s->inbuf_index][BACKSTEP_SIZE];

    s->inbuf_ptr = s->inbuf;

#ifdef DEBUG

    s->frame_count = 0;

#endif

    if (avctx->codec_id == CODEC_ID_MP3ADU)

        s->adu_mode = 1;

    return 0;

}


void checkasm_check_vf_threshold(void)

{

    check_threshold_8();

    report("threshold8");

}


int loader_exec(const char * filename, char ** argv, char ** envp,

             struct target_pt_regs * regs, struct image_info *infop,

             struct linux_binprm *bprm)

{

    int retval;

    int i;

    bprm->p = TARGET_PAGE_SIZE*MAX_ARG_PAGES-sizeof(unsigned int);

    memset(bprm->page, 0, sizeof(bprm->page));

    retval = open(filename, O_RDONLY);

    if (retval < 0)

        return retval;

    bprm->fd = retval;

    bprm->filename = (char *)filename;

    bprm->argc = count(argv);

    bprm->argv = argv;

    bprm->envc = count(envp);

    bprm->envp = envp;

    retval = prepare_binprm(bprm);

    if(retval>=0) {

        if (bprm->buf[0] == 0x7f

                && bprm->buf[1] == 'E'

                && bprm->buf[2] == 'L'

                && bprm->buf[3] == 'F') {

            retval = load_elf_binary(bprm, regs, infop);

#if defined(TARGET_HAS_BFLT)

        } else if (bprm->buf[0] == 'b'

                && bprm->buf[1] == 'F'

                && bprm->buf[2] == 'L'

                && bprm->buf[3] == 'T') {

            retval = load_flt_binary(bprm,regs,infop);

#endif

        } else {

            fprintf(stderr, "Unknown binary format\n");

            return -1;

        }

    }

    if(retval>=0) {

        /* success.  Initialize important registers */

        do_init_thread(regs, infop);

        return retval;

    }

    /* Something went wrong, return the inode and free the argument pages*/

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

        free(bprm->page[i]);

    }

    return(retval);

}


static int mp_get_vlc(MotionPixelsContext *mp, GetBitContext *gb)

{

    int i;

    i = (mp->codes_count == 1) ? 0 : get_vlc2(gb, mp->vlc.table, mp->max_codes_bits, 1);

    return mp->codes[i].delta;

}


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

{

    uint64_t tl, th;

    muls64(&tl, &th, op1, op2);

    /* If th != 0 && th != -1, then we had an overflow */

    if (unlikely((th + 1) > 1)) {

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

    }

    return tl;

}


PCIDevice *pci_rtl8139_init(PCIBus *bus, NICInfo *nd, int devfn)

{

    PCIRTL8139State *d;

    RTL8139State *s;

    uint8_t *pci_conf;

    d = (PCIRTL8139State *)pci_register_device(bus,

                                              "RTL8139", sizeof(PCIRTL8139State),

                                              devfn,

                                              NULL, NULL);

    pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REALTEK);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REALTEK_8139);

    pci_conf[0x04] = 0x05; /* command = I/O space, Bus Master */

    pci_conf[0x08] = RTL8139_PCI_REVID; /* PCI revision ID; >=0x20 is for 8139C+ */

    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);

    pci_conf[0x0e] = 0x00; /* header_type */

    pci_conf[0x3d] = 1;    /* interrupt pin 0 */

    pci_conf[0x34] = 0xdc;

    s = &d->rtl8139;

    /* I/O handler for memory-mapped I/O */

    s->rtl8139_mmio_io_addr =

    cpu_register_io_memory(0, rtl8139_mmio_read, rtl8139_mmio_write, s);

    pci_register_io_region(&d->dev, 0, 0x100,

                           PCI_ADDRESS_SPACE_IO,  rtl8139_ioport_map);

    pci_register_io_region(&d->dev, 1, 0x100,

                           PCI_ADDRESS_SPACE_MEM, rtl8139_mmio_map);

    s->pci_dev = (PCIDevice *)d;

    memcpy(s->macaddr, nd->macaddr, 6);

    rtl8139_reset(s);

    s->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

                                 rtl8139_receive, rtl8139_can_receive, s);

    qemu_format_nic_info_str(s->vc, s->macaddr);

    s->cplus_txbuffer = NULL;

    s->cplus_txbuffer_len = 0;

    s->cplus_txbuffer_offset = 0;

    register_savevm("rtl8139", -1, 4, rtl8139_save, rtl8139_load, s);

#ifdef RTL8139_ONBOARD_TIMER

    s->timer = qemu_new_timer(vm_clock, rtl8139_timer, s);

    qemu_mod_timer(s->timer,

        rtl8139_get_next_tctr_time(s,qemu_get_clock(vm_clock)));

#endif /* RTL8139_ONBOARD_TIMER */

    return (PCIDevice *)d;

}


void usb_wakeup(USBEndpoint *ep, unsigned int stream)

{

    USBDevice *dev = ep->dev;

    USBBus *bus = usb_bus_from_device(dev);

    if (dev->remote_wakeup && dev->port && dev->port->ops->wakeup) {

        dev->port->ops->wakeup(dev->port);

    if (bus->ops->wakeup_endpoint) {

        bus->ops->wakeup_endpoint(bus, ep, stream);


target_ulong helper_load_slb_vsid(CPUPPCState *env, target_ulong rb)

{

    target_ulong rt;

    if (ppc_load_slb_vsid(env, rb, &rt) < 0) {

        helper_raise_exception_err(env, POWERPC_EXCP_PROGRAM,

                                   POWERPC_EXCP_INVAL);

    }

    return rt;

}