static int hls_slice_data_wpp(HEVCContext *s, const HEVCNAL *nal)

{

    const uint8_t *data = nal->data;

    int length          = nal->size;

    HEVCLocalContext *lc = s->HEVClc;

    int *ret = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));

    int *arg = av_malloc_array(s->sh.num_entry_point_offsets + 1, sizeof(int));

    int64_t offset;

    int startheader, cmpt = 0;

    int i, j, res = 0;

    if (!ret || !arg) {

        av_free(ret);

        av_free(arg);

        return AVERROR(ENOMEM);

    }

    if (s->sh.slice_ctb_addr_rs + s->sh.num_entry_point_offsets * s->ps.sps->ctb_width >= s->ps.sps->ctb_width * s->ps.sps->ctb_height) {

        av_log(s->avctx, AV_LOG_ERROR, "WPP ctb addresses are wrong (%d %d %d %d)\n",

            s->sh.slice_ctb_addr_rs, s->sh.num_entry_point_offsets,

            s->ps.sps->ctb_width, s->ps.sps->ctb_height

        );

        res = AVERROR_INVALIDDATA;

        goto error;

    }

    ff_alloc_entries(s->avctx, s->sh.num_entry_point_offsets + 1);

    if (!s->sList[1]) {

        for (i = 1; i < s->threads_number; i++) {

            s->sList[i] = av_malloc(sizeof(HEVCContext));

            memcpy(s->sList[i], s, sizeof(HEVCContext));

            s->HEVClcList[i] = av_mallocz(sizeof(HEVCLocalContext));

            s->sList[i]->HEVClc = s->HEVClcList[i];

        }

    }

    offset = (lc->gb.index >> 3);

    for (j = 0, cmpt = 0, startheader = offset + s->sh.entry_point_offset[0]; j < nal->skipped_bytes; j++) {

        if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {

            startheader--;

            cmpt++;

        }

    }

    for (i = 1; i < s->sh.num_entry_point_offsets; i++) {

        offset += (s->sh.entry_point_offset[i - 1] - cmpt);

        for (j = 0, cmpt = 0, startheader = offset

             + s->sh.entry_point_offset[i]; j < nal->skipped_bytes; j++) {

            if (nal->skipped_bytes_pos[j] >= offset && nal->skipped_bytes_pos[j] < startheader) {

                startheader--;

                cmpt++;

            }

        }

        s->sh.size[i - 1] = s->sh.entry_point_offset[i] - cmpt;

        s->sh.offset[i - 1] = offset;

    }

    if (s->sh.num_entry_point_offsets != 0) {

        offset += s->sh.entry_point_offset[s->sh.num_entry_point_offsets - 1] - cmpt;

        if (length < offset) {

            av_log(s->avctx, AV_LOG_ERROR, "entry_point_offset table is corrupted\n");

            res = AVERROR_INVALIDDATA;

            goto error;

        }

        s->sh.size[s->sh.num_entry_point_offsets - 1] = length - offset;

        s->sh.offset[s->sh.num_entry_point_offsets - 1] = offset;

    }

    s->data = data;

    for (i = 1; i < s->threads_number; i++) {

        s->sList[i]->HEVClc->first_qp_group = 1;

        s->sList[i]->HEVClc->qp_y = s->sList[0]->HEVClc->qp_y;

        memcpy(s->sList[i], s, sizeof(HEVCContext));

        s->sList[i]->HEVClc = s->HEVClcList[i];

    }

    avpriv_atomic_int_set(&s->wpp_err, 0);

    ff_reset_entries(s->avctx);

    for (i = 0; i <= s->sh.num_entry_point_offsets; i++) {

        arg[i] = i;

        ret[i] = 0;

    }

    if (s->ps.pps->entropy_coding_sync_enabled_flag)

        s->avctx->execute2(s->avctx, hls_decode_entry_wpp, arg, ret, s->sh.num_entry_point_offsets + 1);

    for (i = 0; i <= s->sh.num_entry_point_offsets; i++)

        res += ret[i];

error:

    av_free(ret);

    av_free(arg);

    return res;

}


void qemu_file_reset_rate_limit(QEMUFile *f)

{

    f->bytes_xfer = 0;

}


static struct mmsghdr *build_l2tpv3_vector(NetL2TPV3State *s, int count)

{

    int i;

    struct iovec *iov;

    struct mmsghdr *msgvec, *result;

    msgvec = g_malloc(sizeof(struct mmsghdr) * count);

    result = msgvec;

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

        msgvec->msg_hdr.msg_name = NULL;

        msgvec->msg_hdr.msg_namelen = 0;

        iov =  g_malloc(sizeof(struct iovec) * IOVSIZE);

        msgvec->msg_hdr.msg_iov = iov;

        iov->iov_base = g_malloc(s->header_size);

        iov->iov_len = s->header_size;

        iov++ ;

        iov->iov_base = qemu_memalign(BUFFER_ALIGN, BUFFER_SIZE);

        iov->iov_len = BUFFER_SIZE;

        msgvec->msg_hdr.msg_iovlen = 2;

        msgvec->msg_hdr.msg_control = NULL;

        msgvec->msg_hdr.msg_controllen = 0;

        msgvec->msg_hdr.msg_flags = 0;

        msgvec++;

    }

    return result;

}


int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,

                              int nb_sectors, int *pnum)

{

    Coroutine *co;

    BdrvCoGetBlockStatusData data = {

        .bs = bs,

        .sector_num = sector_num,

        .nb_sectors = nb_sectors,

        .pnum = pnum,

        .done = false,

    };

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_get_block_status_co_entry(&data);

    } else {

        co = qemu_coroutine_create(bdrv_get_block_status_co_entry);

        qemu_coroutine_enter(co, &data);

        while (!data.done) {

            qemu_aio_wait();

        }

    }

    return data.ret;

}


static BlockDriverState *bdrv_new_open(const char *filename,

                                       const char *fmt,

                                       int flags,

                                       bool require_io,

                                       bool quiet)

{

    BlockDriverState *bs;

    BlockDriver *drv;

    char password[256];

    Error *local_err = NULL;

    int ret;

    bs = bdrv_new("image");

    if (fmt) {

        drv = bdrv_find_format(fmt);

        if (!drv) {

            error_report("Unknown file format '%s'", fmt);

            goto fail;

        }

    } else {

        drv = NULL;

    }

    ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);

    if (ret < 0) {

        error_report("Could not open '%s': %s", filename,

                     error_get_pretty(local_err));

        error_free(local_err);

        goto fail;

    }

    if (bdrv_is_encrypted(bs) && require_io) {

        qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);

        if (read_password(password, sizeof(password)) < 0) {

            error_report("No password given");

            goto fail;

        }

        if (bdrv_set_key(bs, password) < 0) {

            error_report("invalid password");

            goto fail;

        }

    }

    return bs;

fail:

    bdrv_unref(bs);

    return NULL;

}


void monitor_init(CharDriverState *hd, int show_banner)

{

    int i;

    if (is_first_init) {

        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);

        if (!key_timer)

            return;

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

            monitor_hd[i] = NULL;

        }

        is_first_init = 0;

    }

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

        if (monitor_hd[i] == NULL) {

            monitor_hd[i] = hd;

            break;

        }

    }

    hide_banner = !show_banner;

    qemu_chr_add_handlers(hd, term_can_read, term_read, term_event, NULL);

    readline_start("", 0, monitor_handle_command1, NULL);

}


void OPPROTO op_jz_T0_label(void)

{

    if (!T0)

        GOTO_LABEL_PARAM(1);

    FORCE_RET();

}


struct omap_lcd_panel_s *omap_lcdc_init(MemoryRegion *sysmem,

                                        hwaddr base,

                                        qemu_irq irq,

                                        struct omap_dma_lcd_channel_s *dma,

                                        omap_clk clk)

{

    struct omap_lcd_panel_s *s = (struct omap_lcd_panel_s *)

            g_malloc0(sizeof(struct omap_lcd_panel_s));

    s->irq = irq;

    s->dma = dma;

    s->sysmem = sysmem;

    omap_lcdc_reset(s);

    memory_region_init_io(&s->iomem, &omap_lcdc_ops, s, "omap.lcdc", 0x100);

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

    s->con = graphic_console_init(omap_update_display,

                                  omap_invalidate_display,

                                  omap_screen_dump, NULL, s);

    return s;

}


int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){

    AVPacketList *pktl, **next_point, *this_pktl;

    int stream_count=0;

    int streams[MAX_STREAMS];

    if(pkt){

        AVStream *st= s->streams[ pkt->stream_index];

//        assert(pkt->destruct != av_destruct_packet); //FIXME

        this_pktl = av_mallocz(sizeof(AVPacketList));

        this_pktl->pkt= *pkt;

        if(pkt->destruct == av_destruct_packet)

            pkt->destruct= NULL; // not shared -> must keep original from being freed

        else

            av_dup_packet(&this_pktl->pkt);  //shared -> must dup

        next_point = &s->packet_buffer;

        while(*next_point){

            AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];

            int64_t left=  st2->time_base.num * (int64_t)st ->time_base.den;

            int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;

            if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow

                break;

            next_point= &(*next_point)->next;

        }

        this_pktl->next= *next_point;

        *next_point= this_pktl;

    }

    memset(streams, 0, sizeof(streams));

    pktl= s->packet_buffer;

    while(pktl){

//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%"PRId64"\n", pktl->pkt.stream_index, pktl->pkt.dts);

        if(streams[ pktl->pkt.stream_index ] == 0)

            stream_count++;

        streams[ pktl->pkt.stream_index ]++;

        pktl= pktl->next;

    }

    if(s->nb_streams == stream_count || (flush && stream_count)){

        pktl= s->packet_buffer;

        *out= pktl->pkt;

        s->packet_buffer= pktl->next;

        av_freep(&pktl);

        return 1;

    }else{

        av_init_packet(out);

        return 0;

    }

}


int cpu_mb_handle_mmu_fault (CPUState *env, target_ulong address, int rw,

                               int mmu_idx, int is_softmmu)

{

    unsigned int hit;

    unsigned int mmu_available;

    int r = 1;

    int prot;

    mmu_available = 0;

    if (env->pvr.regs[0] & PVR0_USE_MMU) {

        mmu_available = 1;

        if ((env->pvr.regs[0] & PVR0_PVR_FULL_MASK)

            && (env->pvr.regs[11] & PVR11_USE_MMU) != PVR11_USE_MMU) {

            mmu_available = 0;

        }

    }

    /* Translate if the MMU is available and enabled.  */

    if (mmu_available && (env->sregs[SR_MSR] & MSR_VM)) {

        target_ulong vaddr, paddr;

        struct microblaze_mmu_lookup lu;

        hit = mmu_translate(&env->mmu, &lu, address, rw, mmu_idx);

        if (hit) {

            vaddr = address & TARGET_PAGE_MASK;

            paddr = lu.paddr + vaddr - lu.vaddr;

            DMMU(qemu_log("MMU map mmu=%d v=%x p=%x prot=%x\n",

                     mmu_idx, vaddr, paddr, lu.prot));

            r = tlb_set_page(env, vaddr,

                             paddr, lu.prot, mmu_idx, is_softmmu);

        } else {

            env->sregs[SR_EAR] = address;

            DMMU(qemu_log("mmu=%d miss v=%x\n", mmu_idx, address));

            switch (lu.err) {

                case ERR_PROT:

                    env->sregs[SR_ESR] = rw == 2 ? 17 : 16;

                    env->sregs[SR_ESR] |= (rw == 1) << 10;

                    break;

                case ERR_MISS:

                    env->sregs[SR_ESR] = rw == 2 ? 19 : 18;

                    env->sregs[SR_ESR] |= (rw == 1) << 10;

                    break;

                default:

                    abort();

                    break;

            }

            if (env->exception_index == EXCP_MMU) {

                cpu_abort(env, "recursive faults\n");

            }

            /* TLB miss.  */

            env->exception_index = EXCP_MMU;

        }

    } else {

        /* MMU disabled or not available.  */

        address &= TARGET_PAGE_MASK;

        prot = PAGE_BITS;

        r = tlb_set_page(env, address, address, prot, mmu_idx, is_softmmu);

    }

    return r;

}


static uint64_t grlib_irqmp_read(void *opaque, target_phys_addr_t addr,

                                 unsigned size)

{

    IRQMP      *irqmp = opaque;

    IRQMPState *state;

    assert(irqmp != NULL);

    state = irqmp->state;

    assert(state != NULL);

    addr &= 0xff;

    /* global registers */

    switch (addr) {

    case LEVEL_OFFSET:

        return state->level;

    case PENDING_OFFSET:

        return state->pending;

    case FORCE0_OFFSET:

        /* This register is an "alias" for the force register of CPU 0 */

        return state->force[0];

    case CLEAR_OFFSET:

    case MP_STATUS_OFFSET:

        /* Always read as 0 */

        return 0;

    case BROADCAST_OFFSET:

        return state->broadcast;

    default:

        break;

    }

    /* mask registers */

    if (addr >= MASK_OFFSET && addr < FORCE_OFFSET) {

        int cpu = (addr - MASK_OFFSET) / 4;

        assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);

        return state->mask[cpu];

    }

    /* force registers */

    if (addr >= FORCE_OFFSET && addr < EXTENDED_OFFSET) {

        int cpu = (addr - FORCE_OFFSET) / 4;

        assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);

        return state->force[cpu];

    }

    /* extended (not supported) */

    if (addr >= EXTENDED_OFFSET && addr < IRQMP_REG_SIZE) {

        int cpu = (addr - EXTENDED_OFFSET) / 4;

        assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);

        return state->extended[cpu];

    }

    trace_grlib_irqmp_readl_unknown(addr);

    return 0;

}


Object *object_new_with_propv(const char *typename,

                              Object *parent,

                              const char *id,

                              Error **errp,

                              va_list vargs)

{

    Object *obj;

    ObjectClass *klass;

    Error *local_err = NULL;

    klass = object_class_by_name(typename);

    if (!klass) {

        error_setg(errp, "invalid object type: %s", typename);

        return NULL;

    }

    if (object_class_is_abstract(klass)) {

        error_setg(errp, "object type '%s' is abstract", typename);

        return NULL;

    }

    obj = object_new(typename);

    if (object_set_propv(obj, &local_err, vargs) < 0) {

        goto error;

    }

    object_property_add_child(parent, id, obj, &local_err);

    if (local_err) {

        goto error;

    }

    if (object_dynamic_cast(obj, TYPE_USER_CREATABLE)) {

        user_creatable_complete(obj, &local_err);

        if (local_err) {

            object_unparent(obj);

            goto error;

        }

    }

    object_unref(OBJECT(obj));

    return obj;

 error:

    if (local_err) {

        error_propagate(errp, local_err);

    }

    object_unref(obj);

    return NULL;

}


void start_auth_sasl(VncState *vs)

{

    const char *mechlist = NULL;

    sasl_security_properties_t secprops;

    int err;

    char *localAddr, *remoteAddr;

    int mechlistlen;

    VNC_DEBUG("Initialize SASL auth %d\n", vs->csock);

    /* Get local & remote client addresses in form  IPADDR;PORT */

    if (!(localAddr = vnc_socket_local_addr("%s;%s", vs->csock)))

        goto authabort;

    if (!(remoteAddr = vnc_socket_remote_addr("%s;%s", vs->csock))) {

        free(localAddr);

        goto authabort;

    }

    err = sasl_server_new("vnc",

                          NULL, /* FQDN - just delegates to gethostname */

                          NULL, /* User realm */

                          localAddr,

                          remoteAddr,

                          NULL, /* Callbacks, not needed */

                          SASL_SUCCESS_DATA,

                          &vs->sasl.conn);

    free(localAddr);

    free(remoteAddr);

    localAddr = remoteAddr = NULL;

    if (err != SASL_OK) {

        VNC_DEBUG("sasl context setup failed %d (%s)",

                  err, sasl_errstring(err, NULL, NULL));

        vs->sasl.conn = NULL;

        goto authabort;

    }

#ifdef CONFIG_VNC_TLS

    /* Inform SASL that we've got an external SSF layer from TLS/x509 */

    if (vs->vd->auth == VNC_AUTH_VENCRYPT &&

        vs->vd->subauth == VNC_AUTH_VENCRYPT_X509SASL) {

        gnutls_cipher_algorithm_t cipher;

        sasl_ssf_t ssf;

        cipher = gnutls_cipher_get(vs->tls.session);

        if (!(ssf = (sasl_ssf_t)gnutls_cipher_get_key_size(cipher))) {

            VNC_DEBUG("%s", "cannot TLS get cipher size\n");

            sasl_dispose(&vs->sasl.conn);

            vs->sasl.conn = NULL;

            goto authabort;

        }

        ssf *= 8; /* tls key size is bytes, sasl wants bits */

        err = sasl_setprop(vs->sasl.conn, SASL_SSF_EXTERNAL, &ssf);

        if (err != SASL_OK) {

            VNC_DEBUG("cannot set SASL external SSF %d (%s)\n",

                      err, sasl_errstring(err, NULL, NULL));

            sasl_dispose(&vs->sasl.conn);

            vs->sasl.conn = NULL;

            goto authabort;

        }

    } else

#endif /* CONFIG_VNC_TLS */

        vs->sasl.wantSSF = 1;

    memset (&secprops, 0, sizeof secprops);

    /* Inform SASL that we've got an external SSF layer from TLS */

    if (strncmp(vs->vd->display, "unix:", 5) == 0

#ifdef CONFIG_VNC_TLS

        /* Disable SSF, if using TLS+x509+SASL only. TLS without x509

           is not sufficiently strong */

        || (vs->vd->auth == VNC_AUTH_VENCRYPT &&

            vs->vd->subauth == VNC_AUTH_VENCRYPT_X509SASL)

#endif /* CONFIG_VNC_TLS */

        ) {

        /* If we've got TLS or UNIX domain sock, we don't care about SSF */

        secprops.min_ssf = 0;

        secprops.max_ssf = 0;

        secprops.maxbufsize = 8192;

        secprops.security_flags = 0;

    } else {

        /* Plain TCP, better get an SSF layer */

        secprops.min_ssf = 56; /* Good enough to require kerberos */

        secprops.max_ssf = 100000; /* Arbitrary big number */

        secprops.maxbufsize = 8192;

        /* Forbid any anonymous or trivially crackable auth */

        secprops.security_flags =

            SASL_SEC_NOANONYMOUS | SASL_SEC_NOPLAINTEXT;

    }

    err = sasl_setprop(vs->sasl.conn, SASL_SEC_PROPS, &secprops);

    if (err != SASL_OK) {

        VNC_DEBUG("cannot set SASL security props %d (%s)\n",

                  err, sasl_errstring(err, NULL, NULL));

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    err = sasl_listmech(vs->sasl.conn,

                        NULL, /* Don't need to set user */

                        "", /* Prefix */

                        ",", /* Separator */

                        "", /* Suffix */

                        &mechlist,

                        NULL,

                        NULL);

    if (err != SASL_OK) {

        VNC_DEBUG("cannot list SASL mechanisms %d (%s)\n",

                  err, sasl_errdetail(vs->sasl.conn));

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    VNC_DEBUG("Available mechanisms for client: '%s'\n", mechlist);

    if (!(vs->sasl.mechlist = strdup(mechlist))) {

        VNC_DEBUG("Out of memory");

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    mechlistlen = strlen(mechlist);

    vnc_write_u32(vs, mechlistlen);

    vnc_write(vs, mechlist, mechlistlen);

    vnc_flush(vs);

    VNC_DEBUG("Wait for client mechname length\n");

    vnc_read_when(vs, protocol_client_auth_sasl_mechname_len, 4);

    return;

 authabort:

    vnc_client_error(vs);

    return;

}


static void visitor_output_teardown(TestOutputVisitorData *data,

                                    const void *unused)

{

    visit_free(data->ov);

    data->sov = NULL;

    data->ov = NULL;

    g_free(data->str);

    data->str = NULL;

}


static void megasas_port_write(void *opaque, target_phys_addr_t addr,

                               uint64_t val, unsigned size)

{

    megasas_mmio_write(opaque, addr & 0xff, val, size);

}


static inline void os_host_main_loop_wait(int *timeout)

{

}


uint32_t HELPER(ucf64_get_fpscr)(CPUUniCore32State *env)

{

    int i;

    uint32_t fpscr;

    fpscr = (env->ucf64.xregs[UC32_UCF64_FPSCR] & UCF64_FPSCR_MASK);

    i = get_float_exception_flags(&env->ucf64.fp_status);

    fpscr |= ucf64_exceptbits_from_host(i);

    return fpscr;

}


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

{

    int c, ret, relative;

    const char *filename, *fmt, *size;

    int64_t n, total_size;

    BlockDriverState *bs = NULL;

    QemuOpts *param;

    static QemuOptsList resize_options = {

        .name = "resize_options",

        .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),

        .desc = {

            {

                .name = BLOCK_OPT_SIZE,

                .type = QEMU_OPT_SIZE,

                .help = "Virtual disk size"

            }, {

                /* end of list */

            }

        },

    };

    /* Remove size from argv manually so that negative numbers are not treated

     * as options by getopt. */

    if (argc < 3) {

        help();

        return 1;

    }

    size = argv[--argc];

    /* Parse getopt arguments */

    fmt = NULL;

    for(;;) {

        c = getopt(argc, argv, "f:h");

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            break;

        case 'f':

            fmt = optarg;

            break;

        }

    }

    if (optind >= argc) {

        help();

    }

    filename = argv[optind++];

    /* Choose grow, shrink, or absolute resize mode */

    switch (size[0]) {

    case '+':

        relative = 1;

        size++;

        break;

    case '-':

        relative = -1;

        size++;

        break;

    default:

        relative = 0;

        break;

    }

    /* Parse size */

    param = qemu_opts_create(&resize_options, NULL, 0, NULL);

    if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {

        /* Error message already printed when size parsing fails */

        ret = -1;

        qemu_opts_del(param);

        goto out;

    }

    n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);

    qemu_opts_del(param);

    bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR);

    if (!bs) {

        ret = -1;

        goto out;

    }

    if (relative) {

        total_size = bdrv_getlength(bs) + n * relative;

    } else {

        total_size = n;

    }

    if (total_size <= 0) {

        error_report("New image size must be positive");

        ret = -1;

        goto out;

    }

    ret = bdrv_truncate(bs, total_size);

    switch (ret) {

    case 0:

        printf("Image resized.\n");

        break;

    case -ENOTSUP:

        error_report("This image does not support resize");

        break;

    case -EACCES:

        error_report("Image is read-only");

        break;

    default:

        error_report("Error resizing image (%d)", -ret);

        break;

    }

out:

    if (bs) {

        bdrv_delete(bs);

    }

    if (ret) {

        return 1;

    }

    return 0;

}


void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)

{

    int i, target_code_size, max_target_code_size;

    int direct_jmp_count, direct_jmp2_count, cross_page;

    TranslationBlock *tb;

    struct qht_stats hst;

    tb_lock();

    if (!tcg_enabled()) {

        cpu_fprintf(f, "TCG not enabled\n");

        return;

    }

    target_code_size = 0;

    max_target_code_size = 0;

    cross_page = 0;

    direct_jmp_count = 0;

    direct_jmp2_count = 0;

    for (i = 0; i < tcg_ctx.tb_ctx.nb_tbs; i++) {

        tb = tcg_ctx.tb_ctx.tbs[i];

        target_code_size += tb->size;

        if (tb->size > max_target_code_size) {

            max_target_code_size = tb->size;

        }

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

            cross_page++;

        }

        if (tb->jmp_reset_offset[0] != TB_JMP_RESET_OFFSET_INVALID) {

            direct_jmp_count++;

            if (tb->jmp_reset_offset[1] != TB_JMP_RESET_OFFSET_INVALID) {

                direct_jmp2_count++;

            }

        }

    }

    /* XXX: avoid using doubles ? */

    cpu_fprintf(f, "Translation buffer state:\n");

    cpu_fprintf(f, "gen code size       %td/%zd\n",

                tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer,

                tcg_ctx.code_gen_highwater - tcg_ctx.code_gen_buffer);

    cpu_fprintf(f, "TB count            %d\n", tcg_ctx.tb_ctx.nb_tbs);

    cpu_fprintf(f, "TB avg target size  %d max=%d bytes\n",

            tcg_ctx.tb_ctx.nb_tbs ? target_code_size /

                    tcg_ctx.tb_ctx.nb_tbs : 0,

            max_target_code_size);

    cpu_fprintf(f, "TB avg host size    %td bytes (expansion ratio: %0.1f)\n",

            tcg_ctx.tb_ctx.nb_tbs ? (tcg_ctx.code_gen_ptr -

                                     tcg_ctx.code_gen_buffer) /

                                     tcg_ctx.tb_ctx.nb_tbs : 0,

                target_code_size ? (double) (tcg_ctx.code_gen_ptr -

                                             tcg_ctx.code_gen_buffer) /

                                             target_code_size : 0);

    cpu_fprintf(f, "cross page TB count %d (%d%%)\n", cross_page,

            tcg_ctx.tb_ctx.nb_tbs ? (cross_page * 100) /

                                    tcg_ctx.tb_ctx.nb_tbs : 0);

    cpu_fprintf(f, "direct jump count   %d (%d%%) (2 jumps=%d %d%%)\n",

                direct_jmp_count,

                tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp_count * 100) /

                        tcg_ctx.tb_ctx.nb_tbs : 0,

                direct_jmp2_count,

                tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp2_count * 100) /

                        tcg_ctx.tb_ctx.nb_tbs : 0);

    qht_statistics_init(&tcg_ctx.tb_ctx.htable, &hst);

    print_qht_statistics(f, cpu_fprintf, hst);

    qht_statistics_destroy(&hst);

    cpu_fprintf(f, "\nStatistics:\n");

    cpu_fprintf(f, "TB flush count      %u\n",

            atomic_read(&tcg_ctx.tb_ctx.tb_flush_count));

    cpu_fprintf(f, "TB invalidate count %d\n",

            tcg_ctx.tb_ctx.tb_phys_invalidate_count);

    cpu_fprintf(f, "TLB flush count     %d\n", tlb_flush_count);

    tcg_dump_info(f, cpu_fprintf);

    tb_unlock();

}


build_fadt(GArray *table_data, BIOSLinker *linker, AcpiPmInfo *pm,

           unsigned facs, unsigned dsdt,

           const char *oem_id, const char *oem_table_id)

{

    AcpiFadtDescriptorRev1 *fadt = acpi_data_push(table_data, sizeof(*fadt));

    fadt->firmware_ctrl = cpu_to_le32(facs);

    /* FACS address to be filled by Guest linker */

    bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,

                                   ACPI_BUILD_TABLE_FILE,

                                   &fadt->firmware_ctrl,

                                   sizeof fadt->firmware_ctrl);

    fadt->dsdt = cpu_to_le32(dsdt);

    /* DSDT address to be filled by Guest linker */

    bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,

                                   ACPI_BUILD_TABLE_FILE,

                                   &fadt->dsdt,

                                   sizeof fadt->dsdt);

    fadt_setup(fadt, pm);

    build_header(linker, table_data,

                 (void *)fadt, "FACP", sizeof(*fadt), 1, oem_id, oem_table_id);

}


void arm_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr, int is_write,

                                 int is_user, uintptr_t retaddr)

{

    ARMCPU *cpu = ARM_CPU(cs);

    CPUARMState *env = &cpu->env;

    int target_el;

    bool same_el;

    if (retaddr) {

        /* now we have a real cpu fault */

        cpu_restore_state(cs, retaddr);

    }

    target_el = exception_target_el(env);

    same_el = (arm_current_el(env) == target_el);

    env->exception.vaddress = vaddr;

    /* the DFSR for an alignment fault depends on whether we're using

     * the LPAE long descriptor format, or the short descriptor format

     */

    if (arm_regime_using_lpae_format(env, cpu_mmu_index(env, false))) {

        env->exception.fsr = 0x21;

    } else {

        env->exception.fsr = 0x1;

    }

    if (is_write == 1 && arm_feature(env, ARM_FEATURE_V6)) {

        env->exception.fsr |= (1 << 11);

    }

    raise_exception(env, EXCP_DATA_ABORT,

                    syn_data_abort(same_el, 0, 0, 0, is_write == 1, 0x21),

                    target_el);

}


static void flash_sync_page(Flash *s, int page)

{

    int bdrv_sector, nb_sectors;

    QEMUIOVector iov;

    if (!s->bdrv || bdrv_is_read_only(s->bdrv)) {

        return;

    }

    bdrv_sector = (page * s->pi->page_size) / BDRV_SECTOR_SIZE;

    nb_sectors = DIV_ROUND_UP(s->pi->page_size, BDRV_SECTOR_SIZE);

    qemu_iovec_init(&iov, 1);

    qemu_iovec_add(&iov, s->storage + bdrv_sector * BDRV_SECTOR_SIZE,

                   nb_sectors * BDRV_SECTOR_SIZE);

    bdrv_aio_writev(s->bdrv, bdrv_sector, &iov, nb_sectors, bdrv_sync_complete,

                    NULL);

}


static int proxy_lstat(FsContext *fs_ctx, V9fsPath *fs_path, struct stat *stbuf)

{

    int retval;

    retval = v9fs_request(fs_ctx->private, T_LSTAT, stbuf, "s", fs_path);

    if (retval < 0) {

        errno = -retval;

        return -1;

    }

    return retval;

}


void bios_linker_loader_add_checksum(GArray *linker, const char *file,

                                     GArray *table,

                                     void *start, unsigned size,

                                     uint8_t *checksum)

{

    BiosLinkerLoaderEntry entry;

    ptrdiff_t checksum_offset = (gchar *)checksum - table->data;

    ptrdiff_t start_offset = (gchar *)start - table->data;

    assert(checksum_offset >= 0);

    assert(start_offset >= 0);

    assert(checksum_offset + 1 <= table->len);

    assert(start_offset + size <= table->len);

    assert(*checksum == 0x0);

    memset(&entry, 0, sizeof entry);

    strncpy(entry.cksum.file, file, sizeof entry.cksum.file - 1);

    entry.command = cpu_to_le32(BIOS_LINKER_LOADER_COMMAND_ADD_CHECKSUM);

    entry.cksum.offset = cpu_to_le32(checksum_offset);

    entry.cksum.start = cpu_to_le32(start_offset);

    entry.cksum.length = cpu_to_le32(size);

    g_array_append_vals(linker, &entry, sizeof entry);

}


void backup_do_checkpoint(BlockJob *job, Error **errp)

{

    BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common);

    int64_t len;

    assert(job->driver->job_type == BLOCK_JOB_TYPE_BACKUP);

    if (backup_job->sync_mode != MIRROR_SYNC_MODE_NONE) {

        error_setg(errp, "The backup job only supports block checkpoint in"

                   " sync=none mode");

        return;

    }

    len = DIV_ROUND_UP(backup_job->common.len, backup_job->cluster_size);

    bitmap_zero(backup_job->done_bitmap, len);

}


int floatx80_is_nan( floatx80 a1 )

{

    floatx80u u;

    u.f = a1;

    return ( ( u.i.high & 0x7FFF ) == 0x7FFF ) && (bits64) ( u.i.low<<1 );

}


static void taihu_cpld_writel (void *opaque,

                               hwaddr addr, uint32_t value)

{

    taihu_cpld_writel(opaque, addr, (value >> 24) & 0xFF);

    taihu_cpld_writel(opaque, addr + 1, (value >> 16) & 0xFF);

    taihu_cpld_writel(opaque, addr + 2, (value >> 8) & 0xFF);

    taihu_cpld_writeb(opaque, addr + 3, value & 0xFF);

}


static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)

{

    MOVStts *stts_entries;

    uint32_t entries = -1;

    uint32_t atom_size;

    int i;

    if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {

        stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */

        if (!stts_entries)

            return AVERROR(ENOMEM);

        stts_entries[0].count = track->sample_count;

        stts_entries[0].duration = 1;

        entries = 1;

    } else {

        stts_entries = track->entry ?

                       av_malloc_array(track->entry, sizeof(*stts_entries)) : /* worst case */

                       NULL;

        if (!stts_entries)

            return AVERROR(ENOMEM);

        for (i = 0; i < track->entry; i++) {

            int duration = get_cluster_duration(track, i);

            if (i && duration == stts_entries[entries].duration) {

                stts_entries[entries].count++; /* compress */

            } else {

                entries++;

                stts_entries[entries].duration = duration;

                stts_entries[entries].count = 1;

            }

        }

        entries++; /* last one */

    }

    atom_size = 16 + (entries * 8);

    avio_wb32(pb, atom_size); /* size */

    ffio_wfourcc(pb, "stts");

    avio_wb32(pb, 0); /* version & flags */

    avio_wb32(pb, entries); /* entry count */

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

        avio_wb32(pb, stts_entries[i].count);

        avio_wb32(pb, stts_entries[i].duration);

    }

    av_free(stts_entries);

    return atom_size;

}


void qcrypto_cipher_free(QCryptoCipher *cipher)

{

    QCryptoCipherBuiltin *ctxt = cipher->opaque;

    if (!cipher) {

        return;

    }

    ctxt->free(cipher);

    g_free(cipher);

}


static uint64_t omap_wd_timer_read(void *opaque, target_phys_addr_t addr,

                                   unsigned size)

{

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

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (addr) {

    case 0x00:	/* CNTL_TIMER */

        return (s->timer.ptv << 9) | (s->timer.ar << 8) |

                (s->timer.st << 7) | (s->free << 1);

    case 0x04:	/* READ_TIMER */

        return omap_timer_read(&s->timer);

    case 0x08:	/* TIMER_MODE */

        return s->mode << 15;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


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

{

    int all_devices;

    DriveInfo *dinfo;

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

    all_devices = !strcmp(device, "all");

    TAILQ_FOREACH(dinfo, &drives, next) {

        if (!all_devices)

            if (strcmp(bdrv_get_device_name(dinfo->bdrv), device))

                continue;

        bdrv_commit(dinfo->bdrv);

    }

}


long do_sigreturn(CPUPPCState *env)

{

    struct target_sigcontext *sc = NULL;

    struct target_mcontext *sr = NULL;

    target_ulong sr_addr = 0, sc_addr;

    sigset_t blocked;

    target_sigset_t set;

    sc_addr = env->gpr[1] + SIGNAL_FRAMESIZE;

    if (!lock_user_struct(VERIFY_READ, sc, sc_addr, 1))

        goto sigsegv;

#if defined(TARGET_PPC64)

    set.sig[0] = sc->oldmask + ((long)(sc->_unused[3]) << 32);

#else

    if(__get_user(set.sig[0], &sc->oldmask) ||

       __get_user(set.sig[1], &sc->_unused[3]))

       goto sigsegv;

#endif

    target_to_host_sigset_internal(&blocked, &set);

    sigprocmask(SIG_SETMASK, &blocked, NULL);

    if (__get_user(sr_addr, &sc->regs))

        goto sigsegv;

    if (!lock_user_struct(VERIFY_READ, sr, sr_addr, 1))

        goto sigsegv;

    if (restore_user_regs(env, sr, 1))

        goto sigsegv;

    unlock_user_struct(sr, sr_addr, 1);

    unlock_user_struct(sc, sc_addr, 1);

    return -TARGET_QEMU_ESIGRETURN;

sigsegv:

    unlock_user_struct(sr, sr_addr, 1);

    unlock_user_struct(sc, sc_addr, 1);

    qemu_log("segfaulting from do_sigreturn\n");

    force_sig(TARGET_SIGSEGV);

    return 0;

}


int kvm_arch_irqchip_create(MachineState *ms, KVMState *s)

{

    int ret;

    if (machine_kernel_irqchip_split(ms)) {

        ret = kvm_vm_enable_cap(s, KVM_CAP_SPLIT_IRQCHIP, 0, 24);

        if (ret) {

            error_report("Could not enable split irqchip mode: %s\n",

                         strerror(-ret));

            exit(1);

        } else {

            DPRINTF("Enabled KVM_CAP_SPLIT_IRQCHIP\n");

            kvm_split_irqchip = true;

            return 1;

        }

    } else {

        return 0;

    }

}


void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns,

                                 int64_t grow, int64_t shrink, Error **errp)

{

    /* No thread synchronization here, it doesn't matter if an incorrect value

     * is used once.

     */

    ctx->poll_max_ns = max_ns;

    ctx->poll_ns = 0;

    ctx->poll_grow = grow;

    ctx->poll_shrink = shrink;

    aio_notify(ctx);

}


static void rtas_ibm_change_msi(PowerPCCPU *cpu, sPAPREnvironment *spapr,

                                uint32_t token, uint32_t nargs,

                                target_ulong args, uint32_t nret,

                                target_ulong rets)

{

    uint32_t config_addr = rtas_ld(args, 0);

    uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    unsigned int func = rtas_ld(args, 3);

    unsigned int req_num = rtas_ld(args, 4); /* 0 == remove all */

    unsigned int seq_num = rtas_ld(args, 5);

    unsigned int ret_intr_type;

    unsigned int irq, max_irqs = 0, num = 0;

    sPAPRPHBState *phb = NULL;

    PCIDevice *pdev = NULL;

    spapr_pci_msi *msi;

    int *config_addr_key;

    switch (func) {

    case RTAS_CHANGE_MSI_FN:

    case RTAS_CHANGE_FN:

        ret_intr_type = RTAS_TYPE_MSI;

        break;

    case RTAS_CHANGE_MSIX_FN:

        ret_intr_type = RTAS_TYPE_MSIX;

        break;

    default:

        error_report("rtas_ibm_change_msi(%u) is not implemented", func);

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    /* Fins sPAPRPHBState */

    phb = find_phb(spapr, buid);

    if (phb) {

        pdev = find_dev(spapr, buid, config_addr);

    }

    if (!phb || !pdev) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    /* Releasing MSIs */

    if (!req_num) {

        msi = (spapr_pci_msi *) g_hash_table_lookup(phb->msi, &config_addr);

        if (!msi) {

            trace_spapr_pci_msi("Releasing wrong config", config_addr);

            rtas_st(rets, 0, RTAS_OUT_HW_ERROR);

            return;

        }

        xics_free(spapr->icp, msi->first_irq, msi->num);

        if (msi_present(pdev)) {

            spapr_msi_setmsg(pdev, 0, false, 0, num);

        }

        if (msix_present(pdev)) {

            spapr_msi_setmsg(pdev, 0, true, 0, num);

        }

        g_hash_table_remove(phb->msi, &config_addr);

        trace_spapr_pci_msi("Released MSIs", config_addr);

        rtas_st(rets, 0, RTAS_OUT_SUCCESS);

        rtas_st(rets, 1, 0);

        return;

    }

    /* Enabling MSI */

    /* Check if the device supports as many IRQs as requested */

    if (ret_intr_type == RTAS_TYPE_MSI) {

        max_irqs = msi_nr_vectors_allocated(pdev);

    } else if (ret_intr_type == RTAS_TYPE_MSIX) {

        max_irqs = pdev->msix_entries_nr;

    }

    if (!max_irqs) {

        error_report("Requested interrupt type %d is not enabled for device %x",

                     ret_intr_type, config_addr);

        rtas_st(rets, 0, -1); /* Hardware error */

        return;

    }

    /* Correct the number if the guest asked for too many */

    if (req_num > max_irqs) {

        trace_spapr_pci_msi_retry(config_addr, req_num, max_irqs);

        req_num = max_irqs;

        irq = 0; /* to avoid misleading trace */

        goto out;

    }

    /* Allocate MSIs */

    irq = xics_alloc_block(spapr->icp, 0, req_num, false,

                           ret_intr_type == RTAS_TYPE_MSI);

    if (!irq) {

        error_report("Cannot allocate MSIs for device %x", config_addr);

        rtas_st(rets, 0, RTAS_OUT_HW_ERROR);

        return;

    }

    /* Setup MSI/MSIX vectors in the device (via cfgspace or MSIX BAR) */

    spapr_msi_setmsg(pdev, SPAPR_PCI_MSI_WINDOW, ret_intr_type == RTAS_TYPE_MSIX,

                     irq, req_num);

    /* Add MSI device to cache */

    msi = g_new(spapr_pci_msi, 1);

    msi->first_irq = irq;

    msi->num = req_num;

    config_addr_key = g_new(int, 1);

    *config_addr_key = config_addr;

    g_hash_table_insert(phb->msi, config_addr_key, msi);

out:

    rtas_st(rets, 0, RTAS_OUT_SUCCESS);

    rtas_st(rets, 1, req_num);

    rtas_st(rets, 2, ++seq_num);

    rtas_st(rets, 3, ret_intr_type);

    trace_spapr_pci_rtas_ibm_change_msi(config_addr, func, req_num, irq);

}


START_TEST(simple_number)

{

    int i;

    struct {

        const char *encoded;

        int64_t decoded;

    } test_cases[] = {

        { "0", 0 },

        { "1234", 1234 },

        { "1", 1 },

        { "-32", -32 },

        { "-0", 0 },

        { },

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QInt *qint;

        obj = qobject_from_json(test_cases[i].encoded);

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QINT);

        qint = qobject_to_qint(obj);

        fail_unless(qint_get_int(qint) == test_cases[i].decoded);

        QDECREF(qint);

    }

}


static int v410_encode_frame(AVCodecContext *avctx, uint8_t *buf,

                             int buf_size, void *data)

{

    AVFrame *pic = data;

    uint8_t *dst = buf;

    uint16_t *y, *u, *v;

    uint32_t val;

    int i, j;

    int output_size = 0;

    if (buf_size < avctx->width * avctx->height * 3) {

        av_log(avctx, AV_LOG_ERROR, "Out buffer is too small.\n");

        return AVERROR(ENOMEM);

    }

    avctx->coded_frame->reference = 0;

    avctx->coded_frame->key_frame = 1;

    avctx->coded_frame->pict_type = FF_I_TYPE;

    y = (uint16_t *)pic->data[0];

    u = (uint16_t *)pic->data[1];

    v = (uint16_t *)pic->data[2];

    for (i = 0; i < avctx->height; i++) {

        for (j = 0; j < avctx->width; j++) {

            val  = u[j] << 2;

            val |= y[j] << 12;

            val |= v[j] << 22;

            AV_WL32(dst, val);

            dst += 4;

            output_size += 4;

        }

        y += pic->linesize[0] >> 1;

        u += pic->linesize[1] >> 1;

        v += pic->linesize[2] >> 1;

    }

    return output_size;

}


static void exynos4210_rtc_write(void *opaque, target_phys_addr_t offset,

        uint64_t value, unsigned size)

{

    Exynos4210RTCState *s = (Exynos4210RTCState *)opaque;

    switch (offset) {

    case INTP:

        if (value & INTP_ALM_ENABLE) {

            qemu_irq_lower(s->alm_irq);

            s->reg_intp &= (~INTP_ALM_ENABLE);

        }

        if (value & INTP_TICK_ENABLE) {

            qemu_irq_lower(s->tick_irq);

            s->reg_intp &= (~INTP_TICK_ENABLE);

        }

        break;

    case RTCCON:

        if (value & RTC_ENABLE) {

            exynos4210_rtc_update_freq(s, value);

        }

        if ((value & RTC_ENABLE) > (s->reg_rtccon & RTC_ENABLE)) {

            /* clock timer */

            ptimer_set_count(s->ptimer_1Hz, RTC_BASE_FREQ);

            ptimer_run(s->ptimer_1Hz, 1);

            DPRINTF("run clock timer\n");

        }

        if ((value & RTC_ENABLE) < (s->reg_rtccon & RTC_ENABLE)) {

            /* tick timer */

            ptimer_stop(s->ptimer);

            /* clock timer */

            ptimer_stop(s->ptimer_1Hz);

            DPRINTF("stop all timers\n");

        }

        if (value & RTC_ENABLE) {

            if ((value & TICK_TIMER_ENABLE) >

                (s->reg_rtccon & TICK_TIMER_ENABLE) &&

                (s->reg_ticcnt)) {

                ptimer_set_count(s->ptimer, s->reg_ticcnt);

                ptimer_run(s->ptimer, 1);

                DPRINTF("run tick timer\n");

            }

            if ((value & TICK_TIMER_ENABLE) <

                (s->reg_rtccon & TICK_TIMER_ENABLE)) {

                ptimer_stop(s->ptimer);

            }

        }

        s->reg_rtccon = value;

        break;

    case TICCNT:

        if (value > TICNT_THRESHHOLD) {

            s->reg_ticcnt = value;

        } else {

            fprintf(stderr,

                    "[exynos4210.rtc: bad TICNT value %u ]\n",

                    (uint32_t)value);

        }

        break;

    case RTCALM:

        s->reg_rtcalm = value;

        break;

    case ALMSEC:

        s->reg_almsec = (value & 0x7f);

        break;

    case ALMMIN:

        s->reg_almmin = (value & 0x7f);

        break;

    case ALMHOUR:

        s->reg_almhour = (value & 0x3f);

        break;

    case ALMDAY:

        s->reg_almday = (value & 0x3f);

        break;

    case ALMMON:

        s->reg_almmon = (value & 0x1f);

        break;

    case ALMYEAR:

        s->reg_almyear = (value & 0x0fff);

        break;

    case BCDSEC:

        if (s->reg_rtccon & RTC_ENABLE) {

            s->current_tm.tm_sec = (int)from_bcd((uint8_t)value);

        }

        break;

    case BCDMIN:

        if (s->reg_rtccon & RTC_ENABLE) {

            s->current_tm.tm_min = (int)from_bcd((uint8_t)value);

        }

        break;

    case BCDHOUR:

        if (s->reg_rtccon & RTC_ENABLE) {

            s->current_tm.tm_hour = (int)from_bcd((uint8_t)value);

        }

        break;

    case BCDDAYWEEK:

        if (s->reg_rtccon & RTC_ENABLE) {

            s->current_tm.tm_wday = (int)from_bcd((uint8_t)value);

        }

        break;

    case BCDDAY:

        if (s->reg_rtccon & RTC_ENABLE) {

            s->current_tm.tm_mday = (int)from_bcd((uint8_t)value);

        }

        break;

    case BCDMON:

        if (s->reg_rtccon & RTC_ENABLE) {

            s->current_tm.tm_mon = (int)from_bcd((uint8_t)value) - 1;

        }

        break;

    case BCDYEAR:

        if (s->reg_rtccon & RTC_ENABLE) {

            /* 3 digits */

            s->current_tm.tm_year = (int)from_bcd((uint8_t)value) +

                    (int)from_bcd((uint8_t)((value >> 8) & 0x0f)) * 100;

        }

        break;

    default:

        fprintf(stderr,

                "[exynos4210.rtc: bad write offset " TARGET_FMT_plx "]\n",

                offset);

        break;

    }

}


static void dummy_m68k_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    CPUM68KState *env;

    MemoryRegion *address_space_mem =  get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    int kernel_size;

    uint64_t elf_entry;

    target_phys_addr_t entry;

    if (!cpu_model)

        cpu_model = "cfv4e";

    env = cpu_init(cpu_model);

    if (!env) {

        fprintf(stderr, "Unable to find m68k CPU definition\n");

        exit(1);

    }

    /* Initialize CPU registers.  */

    env->vbr = 0;

    /* RAM at address zero */

    memory_region_init_ram(ram, "dummy_m68k.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(address_space_mem, 0, ram);

    /* Load kernel.  */

    if (kernel_filename) {

        kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,

                               NULL, NULL, 1, ELF_MACHINE, 0);

        entry = elf_entry;

        if (kernel_size < 0) {

            kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL);

        }

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename,

                                              KERNEL_LOAD_ADDR,

                                              ram_size - KERNEL_LOAD_ADDR);

            entry = KERNEL_LOAD_ADDR;

        }

        if (kernel_size < 0) {

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

                    kernel_filename);

            exit(1);

        }

    } else {

        entry = 0;

    }

    env->pc = entry;

}


static void memory_dump(int count, int format, int wsize,

                        target_phys_addr_t addr, int is_physical)

{

    CPUState *env;

    int nb_per_line, l, line_size, i, max_digits, len;

    uint8_t buf[16];

    uint64_t v;

    if (format == 'i') {

        int flags;

        flags = 0;

        env = mon_get_cpu();

        if (!env && !is_physical)

            return;

#ifdef TARGET_I386

        if (wsize == 2) {

            flags = 1;

        } else if (wsize == 4) {

            flags = 0;

        } else {

            /* as default we use the current CS size */

            flags = 0;

            if (env) {

#ifdef TARGET_X86_64

                if ((env->efer & MSR_EFER_LMA) &&

                    (env->segs[R_CS].flags & DESC_L_MASK))

                    flags = 2;

                else

#endif

                if (!(env->segs[R_CS].flags & DESC_B_MASK))

                    flags = 1;

            }

        }

#endif

        monitor_disas(env, addr, count, is_physical, flags);

        return;

    }

    len = wsize * count;

    if (wsize == 1)

        line_size = 8;

    else

        line_size = 16;

    nb_per_line = line_size / wsize;

    max_digits = 0;

    switch(format) {

    case 'o':

        max_digits = (wsize * 8 + 2) / 3;

        break;

    default:

    case 'x':

        max_digits = (wsize * 8) / 4;

        break;

    case 'u':

    case 'd':

        max_digits = (wsize * 8 * 10 + 32) / 33;

        break;

    case 'c':

        wsize = 1;

        break;

    }

    while (len > 0) {

        if (is_physical)

            term_printf(TARGET_FMT_plx ":", addr);

        else

            term_printf(TARGET_FMT_lx ":", (target_ulong)addr);

        l = len;

        if (l > line_size)

            l = line_size;

        if (is_physical) {

            cpu_physical_memory_rw(addr, buf, l, 0);

        } else {

            env = mon_get_cpu();

            if (!env)

                break;

            cpu_memory_rw_debug(env, addr, buf, l, 0);

        }

        i = 0;

        while (i < l) {

            switch(wsize) {

            default:

            case 1:

                v = ldub_raw(buf + i);

                break;

            case 2:

                v = lduw_raw(buf + i);

                break;

            case 4:

                v = (uint32_t)ldl_raw(buf + i);

                break;

            case 8:

                v = ldq_raw(buf + i);

                break;

            }

            term_printf(" ");

            switch(format) {

            case 'o':

                term_printf("%#*" PRIo64, max_digits, v);

                break;

            case 'x':

                term_printf("0x%0*" PRIx64, max_digits, v);

                break;

            case 'u':

                term_printf("%*" PRIu64, max_digits, v);

                break;

            case 'd':

                term_printf("%*" PRId64, max_digits, v);

                break;

            case 'c':

                term_printc(v);

                break;

            }

            i += wsize;

        }

        term_printf("\n");

        addr += l;

        len -= l;

    }

}


void ide_sector_write(IDEState *s)

{

    int64_t sector_num;

    int n;

    s->status = READY_STAT | SEEK_STAT | BUSY_STAT;

    sector_num = ide_get_sector(s);

#if defined(DEBUG_IDE)

    printf("sector=%" PRId64 "\n", sector_num);

#endif

    n = s->nsector;

    if (n > s->req_nb_sectors) {

        n = s->req_nb_sectors;

    }

    if (!ide_sect_range_ok(s, sector_num, n)) {

        ide_rw_error(s);

        return;

    }

    s->iov.iov_base = s->io_buffer;

    s->iov.iov_len  = n * BDRV_SECTOR_SIZE;

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

    block_acct_start(bdrv_get_stats(s->bs), &s->acct,

                     n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);

    s->pio_aiocb = bdrv_aio_writev(s->bs, sector_num, &s->qiov, n,

                                   ide_sector_write_cb, s);

}


int bdrv_write(BlockDriverState *bs, int64_t sector_num,

               const uint8_t *buf, int nb_sectors)

{

    return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);

}


static ssize_t tap_receive_iov(void *opaque, const struct iovec *iov,

                               int iovcnt)

{

    TAPState *s = opaque;

    ssize_t len;

    do {

        len = writev(s->fd, iov, iovcnt);

    } while (len == -1 && (errno == EINTR || errno == EAGAIN));

    return len;

}


static void qemu_coroutine_thread_cleanup(void *opaque)

{

    CoroutineThreadState *s = opaque;

    Coroutine *co;

    Coroutine *tmp;

    QLIST_FOREACH_SAFE(co, &s->pool, pool_next, tmp) {

        g_free(DO_UPCAST(CoroutineUContext, base, co)->stack);

        g_free(co);

    }

    g_free(s);

}


static int ioh3420_initfn(PCIDevice *d)

{

    PCIBridge* br = DO_UPCAST(PCIBridge, dev, d);

    PCIEPort *p = DO_UPCAST(PCIEPort, br, br);

    PCIESlot *s = DO_UPCAST(PCIESlot, port, p);

    int rc;

    int tmp;

    rc = pci_bridge_initfn(d);

    if (rc < 0) {

        return rc;

    }

    d->config[PCI_REVISION_ID] = PCI_DEVICE_ID_IOH_REV;

    pcie_port_init_reg(d);

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_IOH_EPORT);

    rc = pci_bridge_ssvid_init(d, IOH_EP_SSVID_OFFSET,

                               IOH_EP_SSVID_SVID, IOH_EP_SSVID_SSID);

    if (rc < 0) {

        goto err_bridge;

    }

    rc = msi_init(d, IOH_EP_MSI_OFFSET, IOH_EP_MSI_NR_VECTOR,

                  IOH_EP_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_64BIT,

                  IOH_EP_MSI_SUPPORTED_FLAGS & PCI_MSI_FLAGS_MASKBIT);

    if (rc < 0) {

        goto err_bridge;

    }

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

    if (rc < 0) {

        goto err_msi;

    }

    pcie_cap_deverr_init(d);

    pcie_cap_slot_init(d, s->slot);

    pcie_chassis_create(s->chassis);

    rc = pcie_chassis_add_slot(s);

    if (rc < 0) {

        goto err_pcie_cap;

        return rc;

    }

    pcie_cap_root_init(d);

    rc = pcie_aer_init(d, IOH_EP_AER_OFFSET);

    if (rc < 0) {

        goto err;

    }

    pcie_aer_root_init(d);

    ioh3420_aer_vector_update(d);

    return 0;

err:

    pcie_chassis_del_slot(s);

err_pcie_cap:

    pcie_cap_exit(d);

err_msi:

    msi_uninit(d);

err_bridge:

    tmp = pci_bridge_exitfn(d);

    assert(!tmp);

    return rc;

}


static inline bool cpu_handle_interrupt(CPUState *cpu,

                                        TranslationBlock **last_tb)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    int interrupt_request = cpu->interrupt_request;

    if (unlikely(interrupt_request)) {

        if (unlikely(cpu->singlestep_enabled & SSTEP_NOIRQ)) {

            /* Mask out external interrupts for this step. */

            interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;

        }

        if (interrupt_request & CPU_INTERRUPT_DEBUG) {

            cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;

            cpu->exception_index = EXCP_DEBUG;

            return true;

        }

        if (replay_mode == REPLAY_MODE_PLAY && !replay_has_interrupt()) {

            /* Do nothing */

        } else if (interrupt_request & CPU_INTERRUPT_HALT) {

            replay_interrupt();

            cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;

            cpu->halted = 1;

            cpu->exception_index = EXCP_HLT;

            return true;

        }

#if defined(TARGET_I386)

        else if (interrupt_request & CPU_INTERRUPT_INIT) {

            X86CPU *x86_cpu = X86_CPU(cpu);

            CPUArchState *env = &x86_cpu->env;

            replay_interrupt();

            cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0, 0);

            do_cpu_init(x86_cpu);

            cpu->exception_index = EXCP_HALTED;

            return true;

        }

#else

        else if (interrupt_request & CPU_INTERRUPT_RESET) {

            replay_interrupt();

            cpu_reset(cpu);

            return true;

        }

#endif

        /* The target hook has 3 exit conditions:

           False when the interrupt isn't processed,

           True when it is, and we should restart on a new TB,

           and via longjmp via cpu_loop_exit.  */

        else {

            if (cc->cpu_exec_interrupt(cpu, interrupt_request)) {

                replay_interrupt();

                *last_tb = NULL;

            }

            /* The target hook may have updated the 'cpu->interrupt_request';

             * reload the 'interrupt_request' value */

            interrupt_request = cpu->interrupt_request;

        }

        if (interrupt_request & CPU_INTERRUPT_EXITTB) {

            cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;

            /* ensure that no TB jump will be modified as

               the program flow was changed */

            *last_tb = NULL;

        }

    }

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

        atomic_set(&cpu->exit_request, 0);

        cpu->exception_index = EXCP_INTERRUPT;

        return true;

    }

    return false;

}


void scsi_req_cancel(SCSIRequest *req)

{

    trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);

    if (!req->enqueued) {

        return;

    }

    scsi_req_ref(req);

    scsi_req_dequeue(req);

    req->io_canceled = true;

    if (req->aiocb) {

        bdrv_aio_cancel(req->aiocb);

    }

}


static void test_visitor_in_int(TestInputVisitorData *data,

                                const void *unused)

{

    int64_t res = 0, value = -42;

    Visitor *v;

    v = visitor_input_test_init(data, "%" PRId64, value);

    visit_type_int(v, NULL, &res, &error_abort);

    g_assert_cmpint(res, ==, value);

}


static int onenand_initfn(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    OneNANDState *s = ONE_NAND(dev);

    uint32_t size = 1 << (24 + ((s->id.dev >> 4) & 7));

    void *ram;

    s->base = (hwaddr)-1;

    s->rdy = NULL;

    s->blocks = size >> BLOCK_SHIFT;

    s->secs = size >> 9;

    s->blockwp = g_malloc(s->blocks);

    s->density_mask = (s->id.dev & 0x08)

        ? (1 << (6 + ((s->id.dev >> 4) & 7))) : 0;

    memory_region_init_io(&s->iomem, OBJECT(s), &onenand_ops, s, "onenand",

                          0x10000 << s->shift);

    if (!s->bdrv) {

        s->image = memset(g_malloc(size + (size >> 5)),

                          0xff, size + (size >> 5));

    } else {

        if (bdrv_is_read_only(s->bdrv)) {

            error_report("Can't use a read-only drive");

            return -1;

        }

        s->bdrv_cur = s->bdrv;

    }

    s->otp = memset(g_malloc((64 + 2) << PAGE_SHIFT),

                    0xff, (64 + 2) << PAGE_SHIFT);

    memory_region_init_ram(&s->ram, OBJECT(s), "onenand.ram",

                           0xc000 << s->shift, &error_abort);

    vmstate_register_ram_global(&s->ram);

    ram = memory_region_get_ram_ptr(&s->ram);

    s->boot[0] = ram + (0x0000 << s->shift);

    s->boot[1] = ram + (0x8000 << s->shift);

    s->data[0][0] = ram + ((0x0200 + (0 << (PAGE_SHIFT - 1))) << s->shift);

    s->data[0][1] = ram + ((0x8010 + (0 << (PAGE_SHIFT - 6))) << s->shift);

    s->data[1][0] = ram + ((0x0200 + (1 << (PAGE_SHIFT - 1))) << s->shift);

    s->data[1][1] = ram + ((0x8010 + (1 << (PAGE_SHIFT - 6))) << s->shift);

    onenand_mem_setup(s);

    sysbus_init_irq(sbd, &s->intr);

    sysbus_init_mmio(sbd, &s->container);

    vmstate_register(dev,

                     ((s->shift & 0x7f) << 24)

                     | ((s->id.man & 0xff) << 16)

                     | ((s->id.dev & 0xff) << 8)

                     | (s->id.ver & 0xff),

                     &vmstate_onenand, s);

    return 0;

}


static void pxa2xx_lcdc_dma0_redraw_rot90(PXA2xxLCDState *s,

               hwaddr addr, int *miny, int *maxy)

{

    DisplaySurface *surface = qemu_console_surface(s->con);

    int src_width, dest_width;

    drawfn fn = NULL;

    if (s->dest_width)

        fn = s->line_fn[s->transp][s->bpp];

    if (!fn)

        return;

    src_width = (s->xres + 3) & ~3;     /* Pad to a 4 pixels multiple */

    if (s->bpp == pxa_lcdc_19pbpp || s->bpp == pxa_lcdc_18pbpp)

        src_width *= 3;

    else if (s->bpp > pxa_lcdc_16bpp)

        src_width *= 4;

    else if (s->bpp > pxa_lcdc_8bpp)

        src_width *= 2;

    dest_width = s->yres * s->dest_width;

    *miny = 0;

    framebuffer_update_display(surface, s->sysmem,

                               addr, s->xres, s->yres,

                               src_width, s->dest_width, -dest_width,

                               s->invalidated,

                               fn, s->dma_ch[0].palette,

                               miny, maxy);

}


static BlockBackend *bdrv_first_blk(BlockDriverState *bs)

{

    BdrvChild *child;

    QLIST_FOREACH(child, &bs->parents, next_parent) {

        if (child->role == &child_root) {

            assert(bs->blk);

            return child->opaque;

        }

    }

    assert(!bs->blk);

    return NULL;

}


static void s390_print_cpu_model_list_entry(gpointer data, gpointer user_data)

{

    CPUListState *s = user_data;

    const S390CPUClass *scc = S390_CPU_CLASS((ObjectClass *)data);

    char *name = g_strdup(object_class_get_name((ObjectClass *)data));

    const char *details = "";

    if (scc->is_static) {

        details = "(static, migration-safe)";

    } else if (scc->is_migration_safe) {

        details = "(migration-safe)";

    }

    /* strip off the -s390-cpu */

    g_strrstr(name, "-" TYPE_S390_CPU)[0] = 0;

    (*s->cpu_fprintf)(s->file, "s390 %-15s %-35s %s\n", name, scc->desc,

                      details);

    g_free(name);

}


static void simple_varargs(void)

{

    QObject *embedded_obj;

    QObject *obj;

    LiteralQObject decoded = QLIT_QLIST(((LiteralQObject[]){

            QLIT_QINT(1),

            QLIT_QINT(2),

            QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(32),

                        QLIT_QINT(42),

                        {}})),

            {}}));

    embedded_obj = qobject_from_json("[32, 42]");

    g_assert(embedded_obj != NULL);

    obj = qobject_from_jsonf("[%d, 2, %p]", 1, embedded_obj);

    g_assert(obj != NULL);

    g_assert(compare_litqobj_to_qobj(&decoded, obj) == 1);

    qobject_decref(obj);

}


static void add_device_config(int type, const char *cmdline)

{

    struct device_config *conf;

    conf = qemu_mallocz(sizeof(*conf));

    conf->type = type;

    conf->cmdline = cmdline;

    TAILQ_INSERT_TAIL(&device_configs, conf, next);

}


static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)

{

    CompandContext *s    = ctx->priv;

    AVFilterLink *inlink = ctx->inputs[0];

    const int channels = inlink->channels;

    const int nb_samples = frame->nb_samples;

    AVFrame *out_frame;

    int chan, i;

    if (av_frame_is_writable(frame)) {

        out_frame = frame;

    } else {

        out_frame = ff_get_audio_buffer(inlink, nb_samples);

        if (!out_frame) {

            av_frame_free(&frame);

            return AVERROR(ENOMEM);

        }

        av_frame_copy_props(out_frame, frame);

    }

    for (chan = 0; chan < channels; chan++) {

        const double *src = (double *)frame->extended_data[chan];

        double *dst = (double *)out_frame->extended_data[chan];

        ChanParam *cp = &s->channels[chan];

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

            update_volume(cp, fabs(src[i]));

            dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);

        }

    }

    if (frame != out_frame)

        av_frame_free(&frame);

    return ff_filter_frame(ctx->outputs[0], out_frame);

}


static int get_sot(Jpeg2000DecoderContext *s, int n)

{

    Jpeg2000TilePart *tp;

    uint16_t Isot;

    uint32_t Psot;

    uint8_t TPsot;

    if (bytestream2_get_bytes_left(&s->g) < 8)

        return AVERROR_INVALIDDATA;

    s->curtileno = 0;

    Isot = bytestream2_get_be16u(&s->g);        // Isot

    if (Isot >= s->numXtiles * s->numYtiles)

        return AVERROR_INVALIDDATA;

    s->curtileno = Isot;

    Psot  = bytestream2_get_be32u(&s->g);       // Psot

    TPsot = bytestream2_get_byteu(&s->g);       // TPsot

    /* Read TNSot but not used */

    bytestream2_get_byteu(&s->g);               // TNsot

    if (!Psot)

        Psot = bytestream2_get_bytes_left(&s->g) + n + 2;

    if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {

        av_log(s->avctx, AV_LOG_ERROR, "Psot %"PRIu32" too big\n", Psot);

        return AVERROR_INVALIDDATA;

    }

    if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {

        avpriv_request_sample(s->avctx, "Support for %"PRIu8" components", TPsot);

        return AVERROR_PATCHWELCOME;

    }

    s->tile[Isot].tp_idx = TPsot;

    tp             = s->tile[Isot].tile_part + TPsot;

    tp->tile_index = Isot;

    tp->tp_end     = s->g.buffer + Psot - n - 2;

    if (!TPsot) {

        Jpeg2000Tile *tile = s->tile + s->curtileno;

        /* copy defaults */

        memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));

        memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));

    }

    return 0;

}


int MPV_encode_picture(AVCodecContext *avctx,

                       unsigned char *buf, int buf_size, void *data)

{

    MpegEncContext *s = avctx->priv_data;

    AVFrame *pic_arg = data;

    int i, stuffing_count;

    for(i=0; i<avctx->thread_count; i++){

        int start_y= s->thread_context[i]->start_mb_y;

        int   end_y= s->thread_context[i]->  end_mb_y;

        int h= s->mb_height;

        uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);

        uint8_t *end  = buf + (size_t)(((int64_t) buf_size)*  end_y/h);

        init_put_bits(&s->thread_context[i]->pb, start, end - start);

    }

    s->picture_in_gop_number++;

    if(load_input_picture(s, pic_arg) < 0)

        return -1;

    select_input_picture(s);

    /* output? */

    if(s->new_picture.data[0]){

        s->pict_type= s->new_picture.pict_type;

//emms_c();

//printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);

        MPV_frame_start(s, avctx);

vbv_retry:

        if (encode_picture(s, s->picture_number) < 0)

            return -1;

        avctx->real_pict_num  = s->picture_number;

        avctx->header_bits = s->header_bits;

        avctx->mv_bits     = s->mv_bits;

        avctx->misc_bits   = s->misc_bits;

        avctx->i_tex_bits  = s->i_tex_bits;

        avctx->p_tex_bits  = s->p_tex_bits;

        avctx->i_count     = s->i_count;

        avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx

        avctx->skip_count  = s->skip_count;

        MPV_frame_end(s);

        if (s->out_format == FMT_MJPEG)

            mjpeg_picture_trailer(s);

        if(avctx->rc_buffer_size){

            RateControlContext *rcc= &s->rc_context;

            int max_size= rcc->buffer_index/3;

            if(put_bits_count(&s->pb) > max_size && s->qscale < s->avctx->qmax){

                s->next_lambda= s->lambda*(s->qscale+1) / s->qscale;

                s->mb_skipped = 0;        //done in MPV_frame_start()

                if(s->pict_type==P_TYPE){ //done in encode_picture() so we must undo it

                    if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)

                        s->no_rounding ^= 1;

                }

//                av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);

                for(i=0; i<avctx->thread_count; i++){

                    PutBitContext *pb= &s->thread_context[i]->pb;

                    init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);

                }

                goto vbv_retry;

            }

            assert(s->avctx->rc_max_rate);

        }

        if(s->flags&CODEC_FLAG_PASS1)

            ff_write_pass1_stats(s);

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

            s->current_picture_ptr->error[i]= s->current_picture.error[i];

            avctx->error[i] += s->current_picture_ptr->error[i];

        }

        if(s->flags&CODEC_FLAG_PASS1)

            assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));

        flush_put_bits(&s->pb);

        s->frame_bits  = put_bits_count(&s->pb);

        stuffing_count= ff_vbv_update(s, s->frame_bits);

        if(stuffing_count){

            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){

                av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");

                return -1;

            }

            switch(s->codec_id){

            case CODEC_ID_MPEG1VIDEO:

            case CODEC_ID_MPEG2VIDEO:

                while(stuffing_count--){

                    put_bits(&s->pb, 8, 0);

                }

            break;

            case CODEC_ID_MPEG4:

                put_bits(&s->pb, 16, 0);

                put_bits(&s->pb, 16, 0x1C3);

                stuffing_count -= 4;

                while(stuffing_count--){

                    put_bits(&s->pb, 8, 0xFF);

                }

            break;

            default:

                av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");

            }

            flush_put_bits(&s->pb);

            s->frame_bits  = put_bits_count(&s->pb);

        }

        /* update mpeg1/2 vbv_delay for CBR */

        if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1

           && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){

            int vbv_delay;

            assert(s->repeat_first_field==0);

            vbv_delay= lrintf(90000 * s->rc_context.buffer_index / s->avctx->rc_max_rate);

            assert(vbv_delay < 0xFFFF);

            s->vbv_delay_ptr[0] &= 0xF8;

            s->vbv_delay_ptr[0] |= vbv_delay>>13;

            s->vbv_delay_ptr[1]  = vbv_delay>>5;

            s->vbv_delay_ptr[2] &= 0x07;

            s->vbv_delay_ptr[2] |= vbv_delay<<3;

        }

        s->total_bits += s->frame_bits;

        avctx->frame_bits  = s->frame_bits;

    }else{

        assert((pbBufPtr(&s->pb) == s->pb.buf));

        s->frame_bits=0;

    }

    assert((s->frame_bits&7)==0);

    return s->frame_bits/8;

}


static int rtc_load_td(QEMUFile *f, void *opaque, int version_id)

{

    RTCState *s = opaque;

    if (version_id != 1)

        return -EINVAL;

    s->irq_coalesced = qemu_get_be32(f);

    s->period = qemu_get_be32(f);

    rtc_coalesced_timer_update(s);

    return 0;

}


static GtkWidget *gd_create_menu_view(GtkDisplayState *s, GtkAccelGroup *accel_group)

{

    GSList *group = NULL;

    GtkWidget *view_menu;

    GtkWidget *separator;

    int i;

    view_menu = gtk_menu_new();

    gtk_menu_set_accel_group(GTK_MENU(view_menu), accel_group);

    s->full_screen_item =

        gtk_image_menu_item_new_from_stock(GTK_STOCK_FULLSCREEN, NULL);

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->full_screen_item),

                                 "<QEMU>/View/Full Screen");

    gtk_accel_map_add_entry("<QEMU>/View/Full Screen", GDK_KEY_f, GDK_CONTROL_MASK | GDK_MOD1_MASK);

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->full_screen_item);

    separator = gtk_separator_menu_item_new();

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator);

    s->zoom_in_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_IN, NULL);

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->zoom_in_item),

                                 "<QEMU>/View/Zoom In");

    gtk_accel_map_add_entry("<QEMU>/View/Zoom In", GDK_KEY_plus, GDK_CONTROL_MASK | GDK_MOD1_MASK);

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_in_item);

    s->zoom_out_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_OUT, NULL);

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->zoom_out_item),

                                 "<QEMU>/View/Zoom Out");

    gtk_accel_map_add_entry("<QEMU>/View/Zoom Out", GDK_KEY_minus, GDK_CONTROL_MASK | GDK_MOD1_MASK);

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_out_item);

    s->zoom_fixed_item = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_100, NULL);

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->zoom_fixed_item),

                                 "<QEMU>/View/Zoom Fixed");

    gtk_accel_map_add_entry("<QEMU>/View/Zoom Fixed", GDK_KEY_0, GDK_CONTROL_MASK | GDK_MOD1_MASK);

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_fixed_item);

    s->zoom_fit_item = gtk_check_menu_item_new_with_mnemonic(_("Zoom To _Fit"));

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->zoom_fit_item);

    separator = gtk_separator_menu_item_new();

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator);

    s->grab_on_hover_item = gtk_check_menu_item_new_with_mnemonic(_("Grab On _Hover"));

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->grab_on_hover_item);

    s->grab_item = gtk_check_menu_item_new_with_mnemonic(_("_Grab Input"));

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->grab_item),

                                 "<QEMU>/View/Grab Input");

    gtk_accel_map_add_entry("<QEMU>/View/Grab Input", GDK_KEY_g, GDK_CONTROL_MASK | GDK_MOD1_MASK);

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->grab_item);

    separator = gtk_separator_menu_item_new();

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator);

    s->vga_item = gtk_radio_menu_item_new_with_mnemonic(group, "_VGA");

    group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(s->vga_item));

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(s->vga_item),

                                 "<QEMU>/View/VGA");

    gtk_accel_map_add_entry("<QEMU>/View/VGA", GDK_KEY_1, GDK_CONTROL_MASK | GDK_MOD1_MASK);

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->vga_item);

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

        VirtualConsole *vc = &s->vc[i];

        group = gd_vc_init(s, vc, i, group, view_menu);

        s->nb_vcs++;

    }

    separator = gtk_separator_menu_item_new();

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), separator);

    s->show_tabs_item = gtk_check_menu_item_new_with_mnemonic(_("Show _Tabs"));

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), s->show_tabs_item);

    return view_menu;

}


static int v9fs_synth_readdir_r(FsContext *ctx, V9fsFidOpenState *fs,

                                struct dirent *entry, struct dirent **result)

{

    int ret;

    V9fsSynthOpenState *synth_open = fs->private;

    V9fsSynthNode *node = synth_open->node;

    ret = v9fs_synth_get_dentry(node, entry, result, synth_open->offset);

    if (!ret && *result != NULL) {

        synth_open->offset++;

    }

    return ret;

}


static ssize_t vnc_tls_push(gnutls_transport_ptr_t transport,

                            const void *data,

                            size_t len) {

    struct VncState *vs = (struct VncState *)transport;

    int ret;

 retry:

    ret = send(vs->csock, data, len, 0);

    if (ret < 0) {

	if (errno == EINTR)

	    goto retry;

	return -1;

    }

    return ret;

}


void aio_context_release(AioContext *ctx)

{

    qemu_rec_mutex_unlock(&ctx->lock);

}


static int parse_pair(JSONParserContext *ctxt, QDict *dict, va_list *ap)

{

    QObject *key = NULL, *token = NULL, *value, *peek;

    JSONParserContext saved_ctxt = parser_context_save(ctxt);

    peek = parser_context_peek_token(ctxt);

    if (peek == NULL) {

        parse_error(ctxt, NULL, "premature EOI");

        goto out;

    }

    key = parse_value(ctxt, ap);

    if (!key || qobject_type(key) != QTYPE_QSTRING) {

        parse_error(ctxt, peek, "key is not a string in object");

        goto out;

    }

    token = parser_context_pop_token(ctxt);

    if (token == NULL) {

        parse_error(ctxt, NULL, "premature EOI");

        goto out;

    }

    if (!token_is_operator(token, ':')) {

        parse_error(ctxt, token, "missing : in object pair");

        goto out;

    }

    value = parse_value(ctxt, ap);

    if (value == NULL) {

        parse_error(ctxt, token, "Missing value in dict");

        goto out;

    }

    qdict_put_obj(dict, qstring_get_str(qobject_to_qstring(key)), value);

    qobject_decref(key);

    return 0;

out:

    parser_context_restore(ctxt, saved_ctxt);

    qobject_decref(key);

    return -1;

}


gen_intermediate_code_internal (CPUState *env, TranslationBlock *tb,

                                int search_pc)

{

    DisasContext ctx;

    target_ulong pc_start;

    uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int j, lj = -1;

    int num_insns;

    int max_insns;

    if (search_pc && loglevel)

        fprintf (logfile, "search pc %d\n", search_pc);

    pc_start = tb->pc;

    /* Leave some spare opc slots for branch handling. */

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE - 16;

    ctx.pc = pc_start;

    ctx.saved_pc = -1;

    ctx.tb = tb;

    ctx.bstate = BS_NONE;

    /* Restore delay slot state from the tb context.  */

    ctx.hflags = (uint32_t)tb->flags; /* FIXME: maybe use 64 bits here? */

    restore_cpu_state(env, &ctx);

    if (env->user_mode_only)

        ctx.mem_idx = MIPS_HFLAG_UM;

    else

        ctx.mem_idx = ctx.hflags & MIPS_HFLAG_KSU;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

#ifdef DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_CPU) {

        fprintf(logfile, "------------------------------------------------\n");

        /* FIXME: This may print out stale hflags from env... */

        cpu_dump_state(env, logfile, fprintf, 0);

    }

#endif

#ifdef MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM)

        fprintf(logfile, "\ntb %p idx %d hflags %04x\n",

                tb, ctx.mem_idx, ctx.hflags);

#endif

    gen_icount_start();

    while (ctx.bstate == BS_NONE) {

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

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

                if (bp->pc == ctx.pc) {

                    save_cpu_state(&ctx, 1);

                    ctx.bstate = BS_BRANCH;

                    gen_helper_0i(raise_exception, EXCP_DEBUG);

                    /* Include the breakpoint location or the tb won't

                     * be flushed when it must be.  */

                    ctx.pc += 4;

                    goto done_generating;

                }

            }

        }

        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] = ctx.pc;

            gen_opc_hflags[lj] = ctx.hflags & MIPS_HFLAG_BMASK;

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

        ctx.opcode = ldl_code(ctx.pc);

        decode_opc(env, &ctx);

        ctx.pc += 4;

        num_insns++;

        if (env->singlestep_enabled)

            break;

        if ((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0)

            break;

        if (gen_opc_ptr >= gen_opc_end)

            break;

        if (num_insns >= max_insns)

            break;

#if defined (MIPS_SINGLE_STEP)

        break;

#endif

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    if (env->singlestep_enabled) {

        save_cpu_state(&ctx, ctx.bstate == BS_NONE);

        gen_helper_0i(raise_exception, EXCP_DEBUG);

    } else {

	switch (ctx.bstate) {

        case BS_STOP:

            gen_helper_interrupt_restart();

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_NONE:

            save_cpu_state(&ctx, 0);

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_EXCP:

            gen_helper_interrupt_restart();

            tcg_gen_exit_tb(0);

            break;

        case BS_BRANCH:

        default:

            break;

	}

    }

done_generating:

    gen_icount_end(tb, num_insns);

    *gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = ctx.pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM)

        fprintf(logfile, "\n");

#endif

    if (loglevel & CPU_LOG_TB_IN_ASM) {

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

        target_disas(logfile, pc_start, ctx.pc - pc_start, 0);

        fprintf(logfile, "\n");

    }

    if (loglevel & CPU_LOG_TB_CPU) {

        fprintf(logfile, "---------------- %d %08x\n", ctx.bstate, ctx.hflags);

    }

#endif

}


static void *nbd_client_thread(void *arg)

{

    int fd = *(int *)arg;

    off_t size;

    size_t blocksize;

    uint32_t nbdflags;

    int sock;

    int ret;

    pthread_t show_parts_thread;

    do {

        sock = unix_socket_outgoing(sockpath);

        if (sock == -1) {

            goto out;

        }

    } while (sock == -1);

    ret = nbd_receive_negotiate(sock, NULL, &nbdflags,

                                &size, &blocksize);

    if (ret == -1) {

        goto out;

    }

    ret = nbd_init(fd, sock, nbdflags, size, blocksize);

    if (ret == -1) {

        goto out;

    }

    /* update partition table */

    pthread_create(&show_parts_thread, NULL, show_parts, NULL);

    if (verbose) {

        fprintf(stderr, "NBD device %s is now connected to %s\n",

                device, srcpath);

    } else {

        /* Close stderr so that the qemu-nbd process exits.  */

        dup2(STDOUT_FILENO, STDERR_FILENO);

    }

    ret = nbd_client(fd);

    if (ret) {

        goto out;

    }

    close(fd);

    kill(getpid(), SIGTERM);

    return (void *) EXIT_SUCCESS;

out:

    kill(getpid(), SIGTERM);

    return (void *) EXIT_FAILURE;

}


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

{

    TCGv tmp;

    TCGv tmpl;

    TCGv tmph;

    /* Load 64-bit value rd:rn.  */

    tmpl = load_reg(s, rlow);

    tmph = load_reg(s, rhigh);

    tmp = tcg_temp_new(TCG_TYPE_I64);

    tcg_gen_concat_i32_i64(tmp, tmpl, tmph);

    dead_tmp(tmpl);

    dead_tmp(tmph);

    tcg_gen_add_i64(val, val, tmp);

}


static void onenand_reset(OneNANDState *s, int cold)

{

    memset(&s->addr, 0, sizeof(s->addr));

    s->command = 0;

    s->count = 1;

    s->bufaddr = 0;

    s->config[0] = 0x40c0;

    s->config[1] = 0x0000;

    onenand_intr_update(s);

    qemu_irq_raise(s->rdy);

    s->status = 0x0000;

    s->intstatus = cold ? 0x8080 : 0x8010;

    s->unladdr[0] = 0;

    s->unladdr[1] = 0;

    s->wpstatus = 0x0002;

    s->cycle = 0;

    s->otpmode = 0;

    s->bdrv_cur = s->bdrv;

    s->current = s->image;

    s->secs_cur = s->secs;

    if (cold) {

        /* Lock the whole flash */

        memset(s->blockwp, ONEN_LOCK_LOCKED, s->blocks);

        if (s->bdrv_cur && bdrv_read(s->bdrv_cur, 0, s->boot[0], 8) < 0) {

            hw_error("%s: Loading the BootRAM failed.\n", __func__);

        }

    }

}


static void qpi_mem_writew(void *opaque, target_phys_addr_t addr, uint32_t val)

{

}


static void RENAME(yuv2bgr24_1)(SwsContext *c, const uint16_t *buf0,

                                const uint16_t *ubuf0, const uint16_t *ubuf1,

                                const uint16_t *vbuf0, const uint16_t *vbuf1,

                                const uint16_t *abuf0, uint8_t *dest,

                                int dstW, int uvalpha, enum PixelFormat dstFormat,

                                int flags, int y)

{

    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

            "mov        %4, %%"REG_b"               \n\t"

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    } else {

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

            "mov        %4, %%"REG_b"               \n\t"

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1b(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    }

}


static void asf_build_simple_index(AVFormatContext *s, int stream_index)

{

    ff_asf_guid g;

    ASFContext *asf = s->priv_data;

    int64_t current_pos= avio_tell(s->pb);

    int i;

    avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);

    ff_get_guid(s->pb, &g);

    /* the data object can be followed by other top-level objects,

       skip them until the simple index object is reached */

    while (ff_guidcmp(&g, &index_guid)) {

        int64_t gsize= avio_rl64(s->pb);

        if (gsize < 24 || url_feof(s->pb)) {

            avio_seek(s->pb, current_pos, SEEK_SET);

            return;

        }

        avio_skip(s->pb, gsize-24);

        ff_get_guid(s->pb, &g);

    }

    {

        int64_t itime, last_pos=-1;

        int pct, ict;

        int64_t av_unused gsize= avio_rl64(s->pb);

        ff_get_guid(s->pb, &g);

        itime=avio_rl64(s->pb);

        pct=avio_rl32(s->pb);

        ict=avio_rl32(s->pb);

        av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);

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

            int pktnum=avio_rl32(s->pb);

            int pktct =avio_rl16(s->pb);

            int64_t pos      = s->data_offset + s->packet_size*(int64_t)pktnum;

            int64_t index_pts= FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);

            if(pos != last_pos){

            av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n", pktnum, pktct, index_pts);

            av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);

            last_pos=pos;

            }

        }

        asf->index_read= 1;

    }

    avio_seek(s->pb, current_pos, SEEK_SET);

}


void spapr_drc_attach(sPAPRDRConnector *drc, DeviceState *d, void *fdt,

                      int fdt_start_offset, Error **errp)

{

    trace_spapr_drc_attach(spapr_drc_index(drc));

    if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {

        error_setg(errp, "an attached device is still awaiting release");

        return;

    }

    if (spapr_drc_type(drc) == SPAPR_DR_CONNECTOR_TYPE_PCI) {

        g_assert(drc->allocation_state == SPAPR_DR_ALLOCATION_STATE_USABLE);

    }

    g_assert(fdt);

    drc->dev = d;

    drc->fdt = fdt;

    drc->fdt_start_offset = fdt_start_offset;

    object_property_add_link(OBJECT(drc), "device",

                             object_get_typename(OBJECT(drc->dev)),

                             (Object **)(&drc->dev),

                             NULL, 0, NULL);

}


void qxl_guest_bug(PCIQXLDevice *qxl, const char *msg, ...)

{

#if SPICE_INTERFACE_QXL_MINOR >= 1

    qxl_send_events(qxl, QXL_INTERRUPT_ERROR);

#endif

    if (qxl->guestdebug) {

        va_list ap;

        va_start(ap, msg);

        fprintf(stderr, "qxl-%d: guest bug: ", qxl->id);

        vfprintf(stderr, msg, ap);

        fprintf(stderr, "\n");

        va_end(ap);

    }

}


static void rtas_get_time_of_day(sPAPREnvironment *spapr,

                                 uint32_t token, uint32_t nargs,

                                 target_ulong args,

                                 uint32_t nret, target_ulong rets)

{

    struct tm tm;

    if (nret != 8) {

        rtas_st(rets, 0, -3);

        return;

    }

    qemu_get_timedate(&tm, spapr->rtc_offset);

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

    rtas_st(rets, 1, tm.tm_year + 1900);

    rtas_st(rets, 2, tm.tm_mon + 1);

    rtas_st(rets, 3, tm.tm_mday);

    rtas_st(rets, 4, tm.tm_hour);

    rtas_st(rets, 5, tm.tm_min);

    rtas_st(rets, 6, tm.tm_sec);

    rtas_st(rets, 7, 0); /* we don't do nanoseconds */

}


static void qmp_input_type_uint64(Visitor *v, const char *name, uint64_t *obj,

                                  Error **errp)

{

    /* FIXME: qobject_to_qint mishandles values over INT64_MAX */

    QmpInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qmp_input_get_object(qiv, name, true, errp);

    QInt *qint;

    if (!qobj) {

        return;

    }

    qint = qobject_to_qint(qobj);

    if (!qint) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

                   "integer");

        return;

    }

    *obj = qint_get_int(qint);

}


static int do_info(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    const mon_cmd_t *cmd;

    const char *item = qdict_get_try_str(qdict, "item");

    if (!item) {

        goto help;

    }

    for (cmd = info_cmds; cmd->name != NULL; cmd++) {

        if (compare_cmd(item, cmd->name))

            break;

    }

    if (cmd->name == NULL) {

        goto help;

    }

    if (monitor_handler_is_async(cmd)) {

        user_async_info_handler(mon, cmd);

        /*

         * Indicate that this command is asynchronous and will not return any

         * data (not even empty).  Instead, the data will be returned via a

         * completion callback.

         */

        *ret_data = qobject_from_jsonf("{ '__mon_async': 'return' }");

    } else if (monitor_handler_ported(cmd)) {

        QObject *info_data = NULL;

        cmd->mhandler.info_new(mon, &info_data);

        if (info_data) {

            cmd->user_print(mon, info_data);

            qobject_decref(info_data);

        }

    } else {

        cmd->mhandler.info(mon);

    }

    return 0;

help:

    help_cmd(mon, "info");

    return 0;

}


int tcp_fconnect(struct socket *so)

{

  Slirp *slirp = so->slirp;

  int ret=0;

  DEBUG_CALL("tcp_fconnect");

  DEBUG_ARG("so = %p", so);

  if( (ret = so->s = qemu_socket(AF_INET,SOCK_STREAM,0)) >= 0) {

    int opt, s=so->s;

    struct sockaddr_in addr;

    qemu_set_nonblock(s);

    socket_set_fast_reuse(s);

    opt = 1;

    qemu_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));

    addr.sin_family = AF_INET;

    if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==

        slirp->vnetwork_addr.s_addr) {

      /* It's an alias */

      if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {

	if (get_dns_addr(&addr.sin_addr) < 0)

	  addr.sin_addr = loopback_addr;

      } else {

	addr.sin_addr = loopback_addr;

      }

    } else

      addr.sin_addr = so->so_faddr;

    addr.sin_port = so->so_fport;

    DEBUG_MISC((dfd, " connect()ing, addr.sin_port=%d, "

		"addr.sin_addr.s_addr=%.16s\n",

		ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));

    /* We don't care what port we get */

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

    /*

     * If it's not in progress, it failed, so we just return 0,

     * without clearing SS_NOFDREF

     */

    soisfconnecting(so);

  }

  return(ret);

}


int cpu_watchpoint_insert(CPUState *cpu, vaddr addr, vaddr len,

                          int flags, CPUWatchpoint **watchpoint)

{

    CPUWatchpoint *wp;

    /* forbid ranges which are empty or run off the end of the address space */

    if (len == 0 || (addr + len - 1) <= addr) {

        error_report("tried to set invalid watchpoint at %"

                     VADDR_PRIx ", len=%" VADDR_PRIu, addr, len);

        return -EINVAL;

    }

    wp = g_malloc(sizeof(*wp));

    wp->vaddr = addr;

    wp->len = len;

    wp->flags = flags;

    /* keep all GDB-injected watchpoints in front */

    if (flags & BP_GDB) {

        QTAILQ_INSERT_HEAD(&cpu->watchpoints, wp, entry);

    } else {

        QTAILQ_INSERT_TAIL(&cpu->watchpoints, wp, entry);

    }

    tlb_flush_page(cpu, addr);

    if (watchpoint)

        *watchpoint = wp;

    return 0;

}


static int unix_connect_saddr(UnixSocketAddress *saddr,

                              NonBlockingConnectHandler *callback, void *opaque,

                              Error **errp)

{

    struct sockaddr_un un;

    ConnectState *connect_state = NULL;

    int sock, rc;

    if (saddr->path == NULL) {

        error_setg(errp, "unix connect: no path specified");

        return -1;

    }

    sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

        error_setg_errno(errp, errno, "Failed to create socket");

        return -1;

    }

    if (callback != NULL) {

        connect_state = g_malloc0(sizeof(*connect_state));

        connect_state->callback = callback;

        connect_state->opaque = opaque;

        qemu_set_nonblock(sock);

    }

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

    un.sun_family = AF_UNIX;

    snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);

    /* connect to peer */

    do {

        rc = 0;

        if (connect(sock, (struct sockaddr *) &un, sizeof(un)) < 0) {

            rc = -errno;

        }

    } while (rc == -EINTR);

    if (connect_state != NULL && QEMU_SOCKET_RC_INPROGRESS(rc)) {

        connect_state->fd = sock;

        qemu_set_fd_handler(sock, NULL, wait_for_connect, connect_state);

        return sock;

    } else if (rc >= 0) {

        /* non blocking socket immediate success, call callback */

        if (callback != NULL) {

            callback(sock, NULL, opaque);

        }

    }

    if (rc < 0) {

        error_setg_errno(errp, -rc, "Failed to connect socket");

        close(sock);

        sock = -1;

    }

    g_free(connect_state);

    return sock;

}


void qemu_thread_create(QemuThread *thread,

                       void *(*start_routine)(void *),

                       void *arg, int mode)

{

    HANDLE hThread;

    assert(mode == QEMU_THREAD_DETACHED);

    struct QemuThreadData *data;

    qemu_thread_init();

    data = g_malloc(sizeof *data);

    data->thread = thread;

    data->start_routine = start_routine;

    data->arg = arg;

    hThread = (HANDLE) _beginthreadex(NULL, 0, win32_start_routine,

                                      data, 0, NULL);

    if (!hThread) {

        error_exit(GetLastError(), __func__);

    }

    CloseHandle(hThread);

}


uint32_t kvm_arch_get_supported_cpuid(KVMState *s, uint32_t function,
                                      uint32_t index, int reg)
{
    struct kvm_cpuid2 *cpuid;
    uint32_t ret = 0;
    uint32_t cpuid_1_edx;
    bool found = false;
    cpuid = get_supported_cpuid(s);
    struct kvm_cpuid_entry2 *entry = cpuid_find_entry(cpuid, function, index);
    if (entry) {
        found = true;
        ret = cpuid_entry_get_reg(entry, reg);
    /* Fixups for the data returned by KVM, below */
    if (function == 1 && reg == R_EDX) {
        /* KVM before 2.6.30 misreports the following features */
        ret |= CPUID_MTRR | CPUID_PAT | CPUID_MCE | CPUID_MCA;
    } else if (function == 1 && reg == R_ECX) {
        /* We can set the hypervisor flag, even if KVM does not return it on
         * GET_SUPPORTED_CPUID
        ret |= CPUID_EXT_HYPERVISOR;
        /* tsc-deadline flag is not returned by GET_SUPPORTED_CPUID, but it
         * can be enabled if the kernel has KVM_CAP_TSC_DEADLINE_TIMER,
         * and the irqchip is in the kernel.
        if (kvm_irqchip_in_kernel() &&
                kvm_check_extension(s, KVM_CAP_TSC_DEADLINE_TIMER)) {
            ret |= CPUID_EXT_TSC_DEADLINE_TIMER;
    } else if (function == 0x80000001 && reg == R_EDX) {
        /* On Intel, kvm returns cpuid according to the Intel spec,
         * so add missing bits according to the AMD spec:
        cpuid_1_edx = kvm_arch_get_supported_cpuid(s, 1, 0, R_EDX);
        ret |= cpuid_1_edx & CPUID_EXT2_AMD_ALIASES;
    g_free(cpuid);
    /* fallback for older kernels */
    if ((function == KVM_CPUID_FEATURES) && !found) {
        ret = get_para_features(s);
    return ret;


static uint16_t handle_write_event_buf(SCLPEventFacility *ef,

                                       EventBufferHeader *event_buf, SCCB *sccb)

{

    uint16_t rc;

    BusChild *kid;

    SCLPEvent *event;

    SCLPEventClass *ec;

    QTAILQ_FOREACH(kid, &ef->sbus.qbus.children, sibling) {

        DeviceState *qdev = kid->child;

        event = (SCLPEvent *) qdev;

        ec = SCLP_EVENT_GET_CLASS(event);

        rc = SCLP_RC_INVALID_FUNCTION;

        if (ec->write_event_data &&

            ec->event_type() == event_buf->type) {

            rc = ec->write_event_data(event, event_buf);

            break;

        }

    }

    return rc;

}


static int mpl2_probe(AVProbeData *p)

{

    int i;

    char c;

    int64_t start, end;

    const unsigned char *ptr = p->buf;

    const unsigned char *ptr_end = ptr + p->buf_size;

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

        if (sscanf(ptr, "[%"SCNd64"][%"SCNd64"]%c", &start, &end, &c) != 3 &&

            sscanf(ptr, "[%"SCNd64"][]%c",          &start,       &c) != 2)

            return 0;

        ptr += strcspn(ptr, "\n") + 1;

        if (ptr >= ptr_end)

            return 0;

    }

    return AVPROBE_SCORE_MAX;

}


static DWORD WINAPI do_suspend(LPVOID opaque)

{

    GuestSuspendMode *mode = opaque;

    DWORD ret = 0;

    if (!SetSuspendState(*mode == GUEST_SUSPEND_MODE_DISK, TRUE, TRUE)) {

        slog("failed to suspend guest, %s", GetLastError());

        ret = -1;

    }

    g_free(mode);

    return ret;

}