static inline void gen_intermediate_code_internal(CPUState *env,
                                                  TranslationBlock *tb,
                                                  int search_pc)
{
    DisasContext dc1, *dc = &dc1;
    CPUBreakpoint *bp;
    uint16_t *gen_opc_end;
    int j, lj;
    target_ulong pc_start;
    uint32_t next_page_start;
    int num_insns;
    int max_insns;
    /* generate intermediate code */
    pc_start = tb->pc;
    dc->tb = tb;
    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;
    dc->is_jmp = DISAS_NEXT;
    dc->pc = pc_start;
    dc->singlestep_enabled = env->singlestep_enabled;
    dc->condjmp = 0;
    dc->thumb = ARM_TBFLAG_THUMB(tb->flags);
    dc->condexec_mask = (ARM_TBFLAG_CONDEXEC(tb->flags) & 0xf) << 1;
    dc->condexec_cond = ARM_TBFLAG_CONDEXEC(tb->flags) >> 4;
#if !defined(CONFIG_USER_ONLY)
    dc->user = (ARM_TBFLAG_PRIV(tb->flags) == 0);
#endif
    dc->vfp_enabled = ARM_TBFLAG_VFPEN(tb->flags);
    dc->vec_len = ARM_TBFLAG_VECLEN(tb->flags);
    dc->vec_stride = ARM_TBFLAG_VECSTRIDE(tb->flags);
    cpu_F0s = tcg_temp_new_i32();
    cpu_F1s = tcg_temp_new_i32();
    cpu_F0d = tcg_temp_new_i64();
    cpu_F1d = tcg_temp_new_i64();
    cpu_V0 = cpu_F0d;
    cpu_V1 = cpu_F1d;
    /* FIXME: cpu_M0 can probably be the same as cpu_V0.  */
    cpu_M0 = tcg_temp_new_i64();
    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
    lj = -1;
    num_insns = 0;
    max_insns = tb->cflags & CF_COUNT_MASK;
    if (max_insns == 0)
        max_insns = CF_COUNT_MASK;
    gen_icount_start();
    tcg_clear_temp_count();
    /* A note on handling of the condexec (IT) bits:
     *
     * We want to avoid the overhead of having to write the updated condexec
     * bits back to the CPUState for every instruction in an IT block. So:
     * (1) if the condexec bits are not already zero then we write
     * zero back into the CPUState now. This avoids complications trying
     * to do it at the end of the block. (For example if we don't do this
     * it's hard to identify whether we can safely skip writing condexec
     * at the end of the TB, which we definitely want to do for the case
     * where a TB doesn't do anything with the IT state at all.)
     * (2) if we are going to leave the TB then we call gen_set_condexec()
     * which will write the correct value into CPUState if zero is wrong.
     * This is done both for leaving the TB at the end, and for leaving
     * it because of an exception we know will happen, which is done in
     * gen_exception_insn(). The latter is necessary because we need to
     * leave the TB with the PC/IT state just prior to execution of the
     * instruction which caused the exception.
     * (3) if we leave the TB unexpectedly (eg a data abort on a load)
     * then the CPUState will be wrong and we need to reset it.
     * This is handled in the same way as restoration of the
     * PC in these situations: we will be called again with search_pc=1
     * and generate a mapping of the condexec bits for each PC in
     * gen_opc_condexec_bits[]. gen_pc_load[] then uses this to restore
     * the condexec bits.
     *
     * Note that there are no instructions which can read the condexec
     * bits, and none which can write non-static values to them, so
     * we don't need to care about whether CPUState is correct in the
     * middle of a TB.
     */
    /* Reset the conditional execution bits immediately. This avoids
       complications trying to do it at the end of the block.  */
    if (dc->condexec_mask || dc->condexec_cond)
      {
        TCGv tmp = tcg_temp_new_i32();
        tcg_gen_movi_i32(tmp, 0);
        store_cpu_field(tmp, condexec_bits);
    do {
#ifdef CONFIG_USER_ONLY
        /* Intercept jump to the magic kernel page.  */
        if (dc->pc >= 0xffff0000) {
            /* We always get here via a jump, so know we are not in a
               conditional execution block.  */
            gen_exception(EXCP_KERNEL_TRAP);
            dc->is_jmp = DISAS_UPDATE;
            break;
#else
        if (dc->pc >= 0xfffffff0 && IS_M(env)) {
            /* We always get here via a jump, so know we are not in a
               conditional execution block.  */
            gen_exception(EXCP_EXCEPTION_EXIT);
            dc->is_jmp = DISAS_UPDATE;
            break;
#endif
        if (unlikely(!QTAILQ_EMPTY(&env->breakpoints))) {
            QTAILQ_FOREACH(bp, &env->breakpoints, entry) {
                if (bp->pc == dc->pc) {
                    gen_exception_insn(dc, 0, EXCP_DEBUG);
                    /* Advance PC so that clearing the breakpoint will
                       invalidate this TB.  */
                    dc->pc += 2;
                    goto done_generating;
                    break;
        if (search_pc) {
            j = gen_opc_ptr - gen_opc_buf;
            if (lj < j) {
                lj++;
                while (lj < j)
                    gen_opc_instr_start[lj++] = 0;
            gen_opc_pc[lj] = dc->pc;
            gen_opc_condexec_bits[lj] = (dc->condexec_cond << 4) | (dc->condexec_mask >> 1);
            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();
        if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP))) {
            tcg_gen_debug_insn_start(dc->pc);
        if (dc->thumb) {
            disas_thumb_insn(env, dc);
            if (dc->condexec_mask) {
                dc->condexec_cond = (dc->condexec_cond & 0xe)
                                   | ((dc->condexec_mask >> 4) & 1);
                dc->condexec_mask = (dc->condexec_mask << 1) & 0x1f;
                if (dc->condexec_mask == 0) {
                    dc->condexec_cond = 0;
        } else {
            disas_arm_insn(env, dc);
        if (dc->condjmp && !dc->is_jmp) {
            gen_set_label(dc->condlabel);
            dc->condjmp = 0;
        /* Translation stops when a conditional branch is encountered.
         * Otherwise the subsequent code could get translated several times.
         * Also stop translation when a page boundary is reached.  This
         * ensures prefetch aborts occur at the right place.  */
        num_insns ++;
    } while (!dc->is_jmp && gen_opc_ptr < gen_opc_end &&
             !env->singlestep_enabled &&
             !singlestep &&
             dc->pc < next_page_start &&
             num_insns < max_insns);
    if (tb->cflags & CF_LAST_IO) {
        if (dc->condjmp) {
            /* FIXME:  This can theoretically happen with self-modifying
               code.  */
            cpu_abort(env, "IO on conditional branch instruction");
        gen_io_end();
    /* At this stage dc->condjmp will only be set when the skipped
       instruction was a conditional branch or trap, and the PC has
       already been written.  */
    if (unlikely(env->singlestep_enabled)) {
        /* Make sure the pc is updated, and raise a debug exception.  */
        if (dc->condjmp) {
            gen_set_condexec(dc);
            if (dc->is_jmp == DISAS_SWI) {
                gen_exception(EXCP_SWI);
            } else {
                gen_exception(EXCP_DEBUG);
            gen_set_label(dc->condlabel);
        if (dc->condjmp || !dc->is_jmp) {
            gen_set_pc_im(dc->pc);
            dc->condjmp = 0;
        gen_set_condexec(dc);
        if (dc->is_jmp == DISAS_SWI && !dc->condjmp) {
            gen_exception(EXCP_SWI);
        } else {
            /* FIXME: Single stepping a WFI insn will not halt
               the CPU.  */
            gen_exception(EXCP_DEBUG);
    } else {
        /* While branches must always occur at the end of an IT block,
           there are a few other things that can cause us to terminate
           the TB in the middel of an IT block:
            - Exception generating instructions (bkpt, swi, undefined).
            - Page boundaries.
            - Hardware watchpoints.
           Hardware breakpoints have already been handled and skip this code.
         */
        gen_set_condexec(dc);
        switch(dc->is_jmp) {
        case DISAS_NEXT:
            gen_goto_tb(dc, 1, dc->pc);
            break;
        default:
        case DISAS_JUMP:
        case DISAS_UPDATE:
            /* indicate that the hash table must be used to find the next TB */
            tcg_gen_exit_tb(0);
            break;
        case DISAS_TB_JUMP:
            /* nothing more to generate */
            break;
        case DISAS_WFI:
            gen_helper_wfi();
            break;
        case DISAS_SWI:
            gen_exception(EXCP_SWI);
            break;
        if (dc->condjmp) {
            gen_set_label(dc->condlabel);
            gen_set_condexec(dc);
            gen_goto_tb(dc, 1, dc->pc);
            dc->condjmp = 0;
done_generating:
    gen_icount_end(tb, num_insns);
    *gen_opc_ptr = INDEX_op_end;
#ifdef DEBUG_DISAS
    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {
        qemu_log("----------------\n");
        qemu_log("IN: %s\n", lookup_symbol(pc_start));
        log_target_disas(pc_start, dc->pc - pc_start, dc->thumb);
        qemu_log("\n");
#endif
    if (search_pc) {
        j = gen_opc_ptr - gen_opc_buf;
        lj++;
        while (lj <= j)
            gen_opc_instr_start[lj++] = 0;
    } else {
        tb->size = dc->pc - pc_start;
        tb->icount = num_insns;


static av_always_inline void thread_park_workers(SliceThreadContext *c, int thread_count)

{

    while (c->current_job != thread_count + c->job_count)

        pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);

    pthread_mutex_unlock(&c->current_job_lock);

}


int av_image_get_linesize(enum PixelFormat pix_fmt, int width, int plane)

{

    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];

    int max_step     [4];       /* max pixel step for each plane */

    int max_step_comp[4];       /* the component for each plane which has the max pixel step */

    int s, linesize;

    if ((unsigned)pix_fmt >= PIX_FMT_NB || desc->flags & PIX_FMT_HWACCEL)

        return AVERROR(EINVAL);

    av_image_fill_max_pixsteps(max_step, max_step_comp, desc);

    s = (max_step_comp[plane] == 1 || max_step_comp[plane] == 2) ? desc->log2_chroma_w : 0;

    linesize = max_step[plane] * (((width + (1 << s) - 1)) >> s);

    if (desc->flags & PIX_FMT_BITSTREAM)

        linesize = (linesize + 7) >> 3;

    return linesize;

}


static int field_end(H264Context *h, int in_setup)

{

    MpegEncContext *const s     = &h->s;

    AVCodecContext *const avctx = s->avctx;

    int err = 0;

    s->mb_y = 0;

    if (!in_setup && !s->droppable)

        ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,

                                  s->picture_structure == PICT_BOTTOM_FIELD);

    if (CONFIG_H264_VDPAU_DECODER &&

        s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)

        ff_vdpau_h264_set_reference_frames(s);

    if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {

        if (!s->droppable) {

            err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);

            h->prev_poc_msb = h->poc_msb;

            h->prev_poc_lsb = h->poc_lsb;

        }

        h->prev_frame_num_offset = h->frame_num_offset;

        h->prev_frame_num        = h->frame_num;

        h->outputed_poc          = h->next_outputed_poc;

    }

    if (avctx->hwaccel) {

        if (avctx->hwaccel->end_frame(avctx) < 0)

            av_log(avctx, AV_LOG_ERROR,

                   "hardware accelerator failed to decode picture\n");

    }

    if (CONFIG_H264_VDPAU_DECODER &&

        s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)

        ff_vdpau_h264_picture_complete(s);

    /*

     * FIXME: Error handling code does not seem to support interlaced

     * when slices span multiple rows

     * The ff_er_add_slice calls don't work right for bottom

     * fields; they cause massive erroneous error concealing

     * Error marking covers both fields (top and bottom).

     * This causes a mismatched s->error_count

     * and a bad error table. Further, the error count goes to

     * INT_MAX when called for bottom field, because mb_y is

     * past end by one (callers fault) and resync_mb_y != 0

     * causes problems for the first MB line, too.

     */

    if (!FIELD_PICTURE && h->current_slice)

        ff_er_frame_end(s);

    ff_MPV_frame_end(s);

    h->current_slice = 0;

    return err;

}


static int vmd_decode(VmdVideoContext *s, AVFrame *frame)

{

    int i;

    unsigned int *palette32;

    unsigned char r, g, b;

    GetByteContext gb;

    unsigned char meth;

    unsigned char *dp;   /* pointer to current frame */

    unsigned char *pp;   /* pointer to previous frame */

    unsigned char len;

    int ofs;

    int frame_x, frame_y;

    int frame_width, frame_height;

    frame_x = AV_RL16(&s->buf[6]);

    frame_y = AV_RL16(&s->buf[8]);

    frame_width = AV_RL16(&s->buf[10]) - frame_x + 1;

    frame_height = AV_RL16(&s->buf[12]) - frame_y + 1;

    if (frame_x < 0 || frame_width < 0 ||

        frame_x >= s->avctx->width ||

        frame_width > s->avctx->width ||

        frame_x + frame_width > s->avctx->width) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Invalid horizontal range %d-%d\n",

               frame_x, frame_width);

        return AVERROR_INVALIDDATA;

    }

    if (frame_y < 0 || frame_height < 0 ||

        frame_y >= s->avctx->height ||

        frame_height > s->avctx->height ||

        frame_y + frame_height > s->avctx->height) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Invalid vertical range %d-%d\n",

               frame_x, frame_width);

        return AVERROR_INVALIDDATA;

    }

    if ((frame_width == s->avctx->width && frame_height == s->avctx->height) &&

        (frame_x || frame_y)) {

        s->x_off = frame_x;

        s->y_off = frame_y;

    }

    frame_x -= s->x_off;

    frame_y -= s->y_off;

    /* if only a certain region will be updated, copy the entire previous

     * frame before the decode */

    if (s->prev_frame.data[0] &&

        (frame_x || frame_y || (frame_width != s->avctx->width) ||

        (frame_height != s->avctx->height))) {

        memcpy(frame->data[0], s->prev_frame.data[0],

            s->avctx->height * frame->linesize[0]);

    }

    /* check if there is a new palette */

    bytestream2_init(&gb, s->buf + 16, s->size - 16);

    if (s->buf[15] & 0x02) {

        bytestream2_skip(&gb, 2);

        palette32 = (unsigned int *)s->palette;

        if (bytestream2_get_bytes_left(&gb) >= PALETTE_COUNT * 3) {

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

                r = bytestream2_get_byteu(&gb) * 4;

                g = bytestream2_get_byteu(&gb) * 4;

                b = bytestream2_get_byteu(&gb) * 4;

                palette32[i] = (r << 16) | (g << 8) | (b);

            }

        } else {

            av_log(s->avctx, AV_LOG_ERROR, "Incomplete palette\n");

            return AVERROR_INVALIDDATA;

        }

        s->size -= PALETTE_COUNT * 3 + 2;

    }

    if (s->size > 0) {

        /* originally UnpackFrame in VAG's code */

        bytestream2_init(&gb, gb.buffer, s->buf + s->size - gb.buffer);

        if (bytestream2_get_bytes_left(&gb) < 1)

            return AVERROR_INVALIDDATA;

        meth = bytestream2_get_byteu(&gb);

        if (meth & 0x80) {

            lz_unpack(gb.buffer, bytestream2_get_bytes_left(&gb),

                      s->unpack_buffer, s->unpack_buffer_size);

            meth &= 0x7F;

            bytestream2_init(&gb, s->unpack_buffer, s->unpack_buffer_size);

        }

        dp = &frame->data[0][frame_y * frame->linesize[0] + frame_x];

        pp = &s->prev_frame.data[0][frame_y * s->prev_frame.linesize[0] + frame_x];

        switch (meth) {

        case 1:

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

                ofs = 0;

                do {

                    len = bytestream2_get_byte(&gb);

                    if (len & 0x80) {

                        len = (len & 0x7F) + 1;

                        if (ofs + len > frame_width || bytestream2_get_bytes_left(&gb) < len)

                            return AVERROR_INVALIDDATA;

                        bytestream2_get_buffer(&gb, &dp[ofs], len);

                        ofs += len;

                    } else {

                        /* interframe pixel copy */

                        if (ofs + len + 1 > frame_width || !s->prev_frame.data[0])

                            return AVERROR_INVALIDDATA;

                        memcpy(&dp[ofs], &pp[ofs], len + 1);

                        ofs += len + 1;

                    }

                } while (ofs < frame_width);

                if (ofs > frame_width) {

                    av_log(s->avctx, AV_LOG_ERROR, "VMD video: offset > width (%d > %d)\n",

                        ofs, frame_width);

                    return AVERROR_INVALIDDATA;

                }

                dp += frame->linesize[0];

                pp += s->prev_frame.linesize[0];

            }

            break;

        case 2:

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

                bytestream2_get_buffer(&gb, dp, frame_width);

                dp += frame->linesize[0];

                pp += s->prev_frame.linesize[0];

            }

            break;

        case 3:

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

                ofs = 0;

                do {

                    len = bytestream2_get_byte(&gb);

                    if (len & 0x80) {

                        len = (len & 0x7F) + 1;

                        if (bytestream2_get_byte(&gb) == 0xFF)

                            len = rle_unpack(gb.buffer, &dp[ofs],

                                             len, bytestream2_get_bytes_left(&gb),

                                             frame_width - ofs);

                        else

                            bytestream2_get_buffer(&gb, &dp[ofs], len);

                        bytestream2_skip(&gb, len);

                    } else {

                        /* interframe pixel copy */

                        if (ofs + len + 1 > frame_width || !s->prev_frame.data[0])

                            return AVERROR_INVALIDDATA;

                        memcpy(&dp[ofs], &pp[ofs], len + 1);

                        ofs += len + 1;

                    }

                } while (ofs < frame_width);

                if (ofs > frame_width) {

                    av_log(s->avctx, AV_LOG_ERROR, "VMD video: offset > width (%d > %d)\n",

                        ofs, frame_width);

                    return AVERROR_INVALIDDATA;

                }

                dp += frame->linesize[0];

                pp += s->prev_frame.linesize[0];

            }

            break;

        }

    }

    return 0;

}


static void joint_decode(COOKContext *q, float* mlt_buffer1,

                         float* mlt_buffer2) {

    int i,j;

    int decouple_tab[SUBBAND_SIZE];

    float decode_buffer[2048];  //Only 1060 might be needed.

    int idx, cpl_tmp,tmp_idx;

    float f1,f2;

    float* cplscale;

    memset(decouple_tab, 0, sizeof(decouple_tab));

    memset(decode_buffer, 0, sizeof(decode_buffer));

    /* Make sure the buffers are zeroed out. */

    memset(mlt_buffer1,0, 1024*sizeof(float));

    memset(mlt_buffer2,0, 1024*sizeof(float));

    decouple_info(q, decouple_tab);

    mono_decode(q, decode_buffer);

    /* The two channels are stored interleaved in decode_buffer. */

    for (i=0 ; i<q->js_subband_start ; i++) {

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

            mlt_buffer1[i*20+j] = decode_buffer[i*40+j];

            mlt_buffer2[i*20+j] = decode_buffer[i*40+20+j];

        }

    }

    /* When we reach js_subband_start (the higher frequencies)

       the coefficients are stored in a coupling scheme. */

    idx = (1 << q->js_vlc_bits) - 1;

    if (q->js_subband_start < q->subbands) {

        for (i=0 ; i<q->subbands ; i++) {

            cpl_tmp = cplband[i + q->js_subband_start];

            idx -=decouple_tab[cpl_tmp];

            cplscale = (float*)cplscales[q->js_vlc_bits-2];  //choose decoupler table

            f1 = cplscale[decouple_tab[cpl_tmp]];

            f2 = cplscale[idx-1];

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

                tmp_idx = ((2*q->js_subband_start + i)*20)+j;

                mlt_buffer1[20*(i+q->js_subband_start) + j] = f1 * decode_buffer[tmp_idx];

                mlt_buffer2[20*(i+q->js_subband_start) + j] = f2 * decode_buffer[tmp_idx];

            }

            idx = (1 << q->js_vlc_bits) - 1;

        }

    }

}


static inline int nvic_exec_prio(NVICState *s)

{

    CPUARMState *env = &s->cpu->env;

    int running;

    if (env->daif & PSTATE_F) { /* FAULTMASK */

        running = -1;

    } else if (env->daif & PSTATE_I) { /* PRIMASK */

        running = 0;

    } else if (env->v7m.basepri > 0) {

        running = env->v7m.basepri & nvic_gprio_mask(s);

    } else {

        running = NVIC_NOEXC_PRIO; /* lower than any possible priority */

    }

    /* consider priority of active handler */

    return MIN(running, s->exception_prio);

}


static int get_uint16(QEMUFile *f, void *pv, size_t size)

{

    uint16_t *v = pv;

    qemu_get_be16s(f, v);

    return 0;

}


void *qemu_malloc(size_t size)

{

    if (!size && !allow_zero_malloc()) {

        abort();

    }

    return oom_check(malloc(size ? size : 1));

}


int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,

                          off_t *size, size_t *blocksize)

{

    char buf[256];

    uint64_t magic, s;

    uint16_t tmp;

    TRACE("Receiving negotiation.");

    if (read_sync(csock, buf, 8) != 8) {

        LOG("read failed");

        errno = EINVAL;

        return -1;

    }

    buf[8] = '\0';

    if (strlen(buf) == 0) {

        LOG("server connection closed");

        errno = EINVAL;

        return -1;

    }

    TRACE("Magic is %c%c%c%c%c%c%c%c",

          qemu_isprint(buf[0]) ? buf[0] : '.',

          qemu_isprint(buf[1]) ? buf[1] : '.',

          qemu_isprint(buf[2]) ? buf[2] : '.',

          qemu_isprint(buf[3]) ? buf[3] : '.',

          qemu_isprint(buf[4]) ? buf[4] : '.',

          qemu_isprint(buf[5]) ? buf[5] : '.',

          qemu_isprint(buf[6]) ? buf[6] : '.',

          qemu_isprint(buf[7]) ? buf[7] : '.');

    if (memcmp(buf, "NBDMAGIC", 8) != 0) {

        LOG("Invalid magic received");

        errno = EINVAL;

        return -1;

    }

    if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {

        LOG("read failed");

        errno = EINVAL;

        return -1;

    }

    magic = be64_to_cpu(magic);

    TRACE("Magic is 0x%" PRIx64, magic);

    if (name) {

        uint32_t reserved = 0;

        uint32_t opt;

        uint32_t namesize;

        TRACE("Checking magic (opts_magic)");

        if (magic != 0x49484156454F5054LL) {

            LOG("Bad magic received");

            errno = EINVAL;

            return -1;

        }

        if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {

            LOG("flags read failed");

            errno = EINVAL;

            return -1;

        }

        *flags = be16_to_cpu(tmp) << 16;

        /* reserved for future use */

        if (write_sync(csock, &reserved, sizeof(reserved)) !=

            sizeof(reserved)) {

            LOG("write failed (reserved)");

            errno = EINVAL;

            return -1;

        }

        /* write the export name */

        magic = cpu_to_be64(magic);

        if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {

            LOG("write failed (magic)");

            errno = EINVAL;

            return -1;

        }

        opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);

        if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {

            LOG("write failed (opt)");

            errno = EINVAL;

            return -1;

        }

        namesize = cpu_to_be32(strlen(name));

        if (write_sync(csock, &namesize, sizeof(namesize)) !=

            sizeof(namesize)) {

            LOG("write failed (namesize)");

            errno = EINVAL;

            return -1;

        }

        if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {

            LOG("write failed (name)");

            errno = EINVAL;

            return -1;

        }

    } else {

        TRACE("Checking magic (cli_magic)");

        if (magic != 0x00420281861253LL) {

            LOG("Bad magic received");

            errno = EINVAL;

            return -1;

        }

    }

    if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {

        LOG("read failed");

        errno = EINVAL;

        return -1;

    }

    *size = be64_to_cpu(s);

    *blocksize = 1024;

    TRACE("Size is %" PRIu64, *size);

    if (!name) {

        if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {

            LOG("read failed (flags)");

            errno = EINVAL;

            return -1;

        }

        *flags = be32_to_cpup(flags);

    } else {

        if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {

            LOG("read failed (tmp)");

            errno = EINVAL;

            return -1;

        }

        *flags |= be32_to_cpu(tmp);

    }

    if (read_sync(csock, &buf, 124) != 124) {

        LOG("read failed (buf)");

        errno = EINVAL;

        return -1;

    }

        return 0;

}


static bool timer_mod_ns_locked(QEMUTimerList *timer_list,

                                QEMUTimer *ts, int64_t expire_time)

{

    QEMUTimer **pt, *t;

    /* add the timer in the sorted list */

    pt = &timer_list->active_timers;

    for (;;) {

        t = *pt;

        if (!timer_expired_ns(t, expire_time)) {

            break;

        }

        pt = &t->next;

    }

    ts->expire_time = MAX(expire_time, 0);

    ts->next = *pt;

    *pt = ts;

    return pt == &timer_list->active_timers;

}


static void qvirtio_9p_start(void)

{

    char *args;

    test_share = g_strdup("/tmp/qtest.XXXXXX");

    g_assert_nonnull(mkdtemp(test_share));

    args = g_strdup_printf("-fsdev local,id=fsdev0,security_model=none,path=%s "

                           "-device virtio-9p-pci,fsdev=fsdev0,mount_tag=%s",

                           test_share, mount_tag);

    qtest_start(args);

    g_free(args);

}


static void build_fs_mount_list(FsMountList *mounts, Error **errp)

{

    FsMount *mount;

    char const *mountinfo = "/proc/self/mountinfo";

    FILE *fp;

    char *line = NULL, *dash;

    size_t n;

    char check;

    unsigned int devmajor, devminor;

    int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;

    fp = fopen(mountinfo, "r");

    if (!fp) {

        build_fs_mount_list_from_mtab(mounts, errp);

        return;

    }

    while (getline(&line, &n, fp) != -1) {

        ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",

                     &devmajor, &devminor, &dir_s, &dir_e, &check);

        if (ret < 3) {

            continue;

        }

        dash = strstr(line + dir_e, " - ");

        if (!dash) {

            continue;

        }

        ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",

                     &type_s, &type_e, &dev_s, &dev_e, &check);

        if (ret < 1) {

            continue;

        }

        line[dir_e] = 0;

        dash[type_e] = 0;

        dash[dev_e] = 0;

        decode_mntname(line + dir_s, dir_e - dir_s);

        decode_mntname(dash + dev_s, dev_e - dev_s);

        if (devmajor == 0) {

            /* btrfs reports major number = 0 */

            if (strcmp("btrfs", dash + type_s) != 0 ||

                dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {

                continue;

            }

        }

        mount = g_malloc0(sizeof(FsMount));

        mount->dirname = g_strdup(line + dir_s);

        mount->devtype = g_strdup(dash + type_s);

        mount->devmajor = devmajor;

        mount->devminor = devminor;

        QTAILQ_INSERT_TAIL(mounts, mount, next);

    }

    free(line);

    fclose(fp);

}


float64 int32_to_float64( int32 a STATUS_PARAM )

{

    flag zSign;

    uint32 absA;

    int8 shiftCount;

    bits64 zSig;

    if ( a == 0 ) return 0;

    zSign = ( a < 0 );

    absA = zSign ? - a : a;

    shiftCount = countLeadingZeros32( absA ) + 21;

    zSig = absA;

    return packFloat64( zSign, 0x432 - shiftCount, zSig<<shiftCount );

}


void blkconf_serial(BlockConf *conf, char **serial)

{

    DriveInfo *dinfo;

    if (!*serial) {

        /* try to fall back to value set with legacy -drive serial=... */

        dinfo = drive_get_by_blockdev(conf->bs);

        if (*dinfo->serial) {

            *serial = g_strdup(dinfo->serial);

        }

    }

}


int bitbang_i2c_set(bitbang_i2c_interface *i2c, int line, int level)

{

    int data;

    if (level != 0 && level != 1) {

        abort();

    }

    if (line == BITBANG_I2C_SDA) {

        if (level == i2c->last_data) {

            return bitbang_i2c_nop(i2c);

        }

        i2c->last_data = level;

        if (i2c->last_clock == 0) {

            return bitbang_i2c_nop(i2c);

        }

        if (level == 0) {

            DPRINTF("START\n");

            /* START condition.  */

            i2c->state = SENDING_BIT7;

            i2c->current_addr = -1;

        } else {

            /* STOP condition.  */

            bitbang_i2c_enter_stop(i2c);

        }

        return bitbang_i2c_ret(i2c, 1);

    }

    data = i2c->last_data;

    if (i2c->last_clock == level) {

        return bitbang_i2c_nop(i2c);

    }

    i2c->last_clock = level;

    if (level == 0) {

        /* State is set/read at the start of the clock pulse.

           release the data line at the end.  */

        return bitbang_i2c_ret(i2c, 1);

    }

    switch (i2c->state) {

    case STOPPED:

    case SENT_NACK:

        return bitbang_i2c_ret(i2c, 1);

    case SENDING_BIT7 ... SENDING_BIT0:

        i2c->buffer = (i2c->buffer << 1) | data;

        /* will end up in WAITING_FOR_ACK */

        i2c->state++;

        return bitbang_i2c_ret(i2c, 1);

    case WAITING_FOR_ACK:

        if (i2c->current_addr < 0) {

            i2c->current_addr = i2c->buffer;

            DPRINTF("Address 0x%02x\n", i2c->current_addr);

            i2c_start_transfer(i2c->bus, i2c->current_addr >> 1,

                               i2c->current_addr & 1);

        } else {

            DPRINTF("Sent 0x%02x\n", i2c->buffer);

            i2c_send(i2c->bus, i2c->buffer);

        }

        if (i2c->current_addr & 1) {

            i2c->state = RECEIVING_BIT7;

        } else {

            i2c->state = SENDING_BIT7;

        }

        return bitbang_i2c_ret(i2c, 0);

    case RECEIVING_BIT7:

        i2c->buffer = i2c_recv(i2c->bus);

        DPRINTF("RX byte 0x%02x\n", i2c->buffer);

        /* Fall through... */

    case RECEIVING_BIT6 ... RECEIVING_BIT0:

        data = i2c->buffer >> 7;

        /* will end up in SENDING_ACK */

        i2c->state++;

        i2c->buffer <<= 1;

        return bitbang_i2c_ret(i2c, data);

    case SENDING_ACK:

        i2c->state = RECEIVING_BIT7;

        if (data != 0) {

            DPRINTF("NACKED\n");

            i2c->state = SENT_NACK;

            i2c_nack(i2c->bus);

        } else {

            DPRINTF("ACKED\n");

        }

        return bitbang_i2c_ret(i2c, 1);

    }

    abort();

}


static void peripheral_device_del_completion(ReadLineState *rs,

                                             const char *str, size_t len)

{

    Object *peripheral;

    GSList *list = NULL, *item;

    peripheral = object_resolve_path("/machine/peripheral/", NULL);

    if (peripheral == NULL) {

        return;

    }

    object_child_foreach(peripheral, qdev_build_hotpluggable_device_list,

                         &list);

    for (item = list; item; item = g_slist_next(item)) {

        DeviceState *dev = item->data;

        if (dev->id && !strncmp(str, dev->id, len)) {

            readline_add_completion(rs, dev->id);

        }

    }

    g_slist_free(list);

}


av_cold void ff_synth_filter_init(SynthFilterContext *c)

{

    c->synth_filter_float = synth_filter_float;

    if (ARCH_ARM) ff_synth_filter_init_arm(c);

    if (ARCH_X86) ff_synth_filter_init_x86(c);

}


static void tcp_accept_incoming_migration(void *opaque)

{

    struct sockaddr_in addr;

    socklen_t addrlen = sizeof(addr);

    int s = (unsigned long)opaque;

    QEMUFile *f;

    int c, ret;

    do {

        c = qemu_accept(s, (struct sockaddr *)&addr, &addrlen);

    } while (c == -1 && socket_error() == EINTR);

    DPRINTF("accepted migration\n");

    if (c == -1) {

        fprintf(stderr, "could not accept migration connection\n");

        return;

    }

    f = qemu_fopen_socket(c);

    if (f == NULL) {

        fprintf(stderr, "could not qemu_fopen socket\n");

        goto out;

    }

    ret = qemu_loadvm_state(f);

    if (ret < 0) {

        fprintf(stderr, "load of migration failed\n");

        goto out_fopen;

    }

    qemu_announce_self();

    DPRINTF("successfully loaded vm state\n");

    /* we've successfully migrated, close the server socket */

    qemu_set_fd_handler2(s, NULL, NULL, NULL, NULL);

    close(s);

    if (autostart)

        vm_start();

out_fopen:

    qemu_fclose(f);

out:

    close(c);

}


int main(int argc, char** argv)

{

    FILE *f= fopen(argv[1], "rb+");

    int count= atoi(argv[2]);

    int maxburst= atoi(argv[3]);

    int length;

    srand (time (0));

    fseek(f, 0, SEEK_END);

    length= ftell(f);

    fseek(f, 0, SEEK_SET);

    while(count--){

        int burst= 1 + random() * (uint64_t) (abs(maxburst)-1) / RAND_MAX;

        int pos= random() * (uint64_t) length / RAND_MAX;

        fseek(f, pos, SEEK_SET);

        if(maxburst<0) burst= -maxburst;

        if(pos + burst > length)

            continue;

        while(burst--){

            int val= random() * 256ULL / RAND_MAX;

            if(maxburst<0) val=0;

            fwrite(&val, 1, 1, f);

        }

    }

    return 0;

}


static void do_info_network(int argc, const char **argv)

{

    int i, j;

    NetDriverState *nd;

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

        nd = &nd_table[i];

        term_printf("%d: ifname=%s macaddr=", i, nd->ifname);

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

            if (j > 0)

                term_printf(":");

            term_printf("%02x", nd->macaddr[j]);

        }

        term_printf("\n");

    }

}


static int qemu_rdma_registration_handle(QEMUFile *f, void *opaque)

{

    RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),

                               .type = RDMA_CONTROL_REGISTER_RESULT,

                               .repeat = 0,

                             };

    RDMAControlHeader unreg_resp = { .len = 0,

                               .type = RDMA_CONTROL_UNREGISTER_FINISHED,

                               .repeat = 0,

                             };

    RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,

                                 .repeat = 1 };

    QIOChannelRDMA *rioc = QIO_CHANNEL_RDMA(opaque);

    RDMAContext *rdma = rioc->rdma;

    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    RDMAControlHeader head;

    RDMARegister *reg, *registers;

    RDMACompress *comp;

    RDMARegisterResult *reg_result;

    static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];

    RDMALocalBlock *block;

    void *host_addr;

    int ret = 0;

    int idx = 0;

    int count = 0;

    int i = 0;

    CHECK_ERROR_STATE();

    do {

        trace_qemu_rdma_registration_handle_wait();

        ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE);

        if (ret < 0) {

            break;

        }

        if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {

            error_report("rdma: Too many requests in this message (%d)."

                            "Bailing.", head.repeat);

            ret = -EIO;

            break;

        }

        switch (head.type) {

        case RDMA_CONTROL_COMPRESS:

            comp = (RDMACompress *) rdma->wr_data[idx].control_curr;

            network_to_compress(comp);

            trace_qemu_rdma_registration_handle_compress(comp->length,

                                                         comp->block_idx,

                                                         comp->offset);

            if (comp->block_idx >= rdma->local_ram_blocks.nb_blocks) {

                error_report("rdma: 'compress' bad block index %u (vs %d)",

                             (unsigned int)comp->block_idx,

                             rdma->local_ram_blocks.nb_blocks);

                ret = -EIO;

                goto out;

            }

            block = &(rdma->local_ram_blocks.block[comp->block_idx]);

            host_addr = block->local_host_addr +

                            (comp->offset - block->offset);

            ram_handle_compressed(host_addr, comp->value, comp->length);

            break;

        case RDMA_CONTROL_REGISTER_FINISHED:

            trace_qemu_rdma_registration_handle_finished();

            goto out;

        case RDMA_CONTROL_RAM_BLOCKS_REQUEST:

            trace_qemu_rdma_registration_handle_ram_blocks();

            /* Sort our local RAM Block list so it's the same as the source,

             * we can do this since we've filled in a src_index in the list

             * as we received the RAMBlock list earlier.

             */

            qsort(rdma->local_ram_blocks.block,

                  rdma->local_ram_blocks.nb_blocks,

                  sizeof(RDMALocalBlock), dest_ram_sort_func);

            if (rdma->pin_all) {

                ret = qemu_rdma_reg_whole_ram_blocks(rdma);

                if (ret) {

                    error_report("rdma migration: error dest "

                                    "registering ram blocks");

                    goto out;

                }

            }

            /*

             * Dest uses this to prepare to transmit the RAMBlock descriptions

             * to the source VM after connection setup.

             * Both sides use the "remote" structure to communicate and update

             * their "local" descriptions with what was sent.

             */

            for (i = 0; i < local->nb_blocks; i++) {

                rdma->dest_blocks[i].remote_host_addr =

                    (uintptr_t)(local->block[i].local_host_addr);

                if (rdma->pin_all) {

                    rdma->dest_blocks[i].remote_rkey = local->block[i].mr->rkey;

                }

                rdma->dest_blocks[i].offset = local->block[i].offset;

                rdma->dest_blocks[i].length = local->block[i].length;

                dest_block_to_network(&rdma->dest_blocks[i]);

                trace_qemu_rdma_registration_handle_ram_blocks_loop(

                    local->block[i].block_name,

                    local->block[i].offset,

                    local->block[i].length,

                    local->block[i].local_host_addr,

                    local->block[i].src_index);

            }

            blocks.len = rdma->local_ram_blocks.nb_blocks

                                                * sizeof(RDMADestBlock);

            ret = qemu_rdma_post_send_control(rdma,

                                        (uint8_t *) rdma->dest_blocks, &blocks);

            if (ret < 0) {

                error_report("rdma migration: error sending remote info");

                goto out;

            }

            break;

        case RDMA_CONTROL_REGISTER_REQUEST:

            trace_qemu_rdma_registration_handle_register(head.repeat);

            reg_resp.repeat = head.repeat;

            registers = (RDMARegister *) rdma->wr_data[idx].control_curr;

            for (count = 0; count < head.repeat; count++) {

                uint64_t chunk;

                uint8_t *chunk_start, *chunk_end;

                reg = &registers[count];

                network_to_register(reg);

                reg_result = &results[count];

                trace_qemu_rdma_registration_handle_register_loop(count,

                         reg->current_index, reg->key.current_addr, reg->chunks);

                if (reg->current_index >= rdma->local_ram_blocks.nb_blocks) {

                    error_report("rdma: 'register' bad block index %u (vs %d)",

                                 (unsigned int)reg->current_index,

                                 rdma->local_ram_blocks.nb_blocks);

                    ret = -ENOENT;

                    goto out;

                }

                block = &(rdma->local_ram_blocks.block[reg->current_index]);

                if (block->is_ram_block) {

                    if (block->offset > reg->key.current_addr) {

                        error_report("rdma: bad register address for block %s"

                            " offset: %" PRIx64 " current_addr: %" PRIx64,

                            block->block_name, block->offset,

                            reg->key.current_addr);

                        ret = -ERANGE;

                        goto out;

                    }

                    host_addr = (block->local_host_addr +

                                (reg->key.current_addr - block->offset));

                    chunk = ram_chunk_index(block->local_host_addr,

                                            (uint8_t *) host_addr);

                } else {

                    chunk = reg->key.chunk;

                    host_addr = block->local_host_addr +

                        (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));

                    /* Check for particularly bad chunk value */

                    if (host_addr < (void *)block->local_host_addr) {

                        error_report("rdma: bad chunk for block %s"

                            " chunk: %" PRIx64,

                            block->block_name, reg->key.chunk);

                        ret = -ERANGE;

                        goto out;

                    }

                }

                chunk_start = ram_chunk_start(block, chunk);

                chunk_end = ram_chunk_end(block, chunk + reg->chunks);

                if (qemu_rdma_register_and_get_keys(rdma, block,

                            (uintptr_t)host_addr, NULL, &reg_result->rkey,

                            chunk, chunk_start, chunk_end)) {

                    error_report("cannot get rkey");

                    ret = -EINVAL;

                    goto out;

                }

                reg_result->host_addr = (uintptr_t)block->local_host_addr;

                trace_qemu_rdma_registration_handle_register_rkey(

                                                           reg_result->rkey);

                result_to_network(reg_result);

            }

            ret = qemu_rdma_post_send_control(rdma,

                            (uint8_t *) results, &reg_resp);

            if (ret < 0) {

                error_report("Failed to send control buffer");

                goto out;

            }

            break;

        case RDMA_CONTROL_UNREGISTER_REQUEST:

            trace_qemu_rdma_registration_handle_unregister(head.repeat);

            unreg_resp.repeat = head.repeat;

            registers = (RDMARegister *) rdma->wr_data[idx].control_curr;

            for (count = 0; count < head.repeat; count++) {

                reg = &registers[count];

                network_to_register(reg);

                trace_qemu_rdma_registration_handle_unregister_loop(count,

                           reg->current_index, reg->key.chunk);

                block = &(rdma->local_ram_blocks.block[reg->current_index]);

                ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);

                block->pmr[reg->key.chunk] = NULL;

                if (ret != 0) {

                    perror("rdma unregistration chunk failed");

                    ret = -ret;

                    goto out;

                }

                rdma->total_registrations--;

                trace_qemu_rdma_registration_handle_unregister_success(

                                                       reg->key.chunk);

            }

            ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp);

            if (ret < 0) {

                error_report("Failed to send control buffer");

                goto out;

            }

            break;

        case RDMA_CONTROL_REGISTER_RESULT:

            error_report("Invalid RESULT message at dest.");

            ret = -EIO;

            goto out;

        default:

            error_report("Unknown control message %s", control_desc[head.type]);

            ret = -EIO;

            goto out;

        }

    } while (1);

out:

    if (ret < 0) {

        rdma->error_state = ret;

    }

    return ret;

}


void xen_invalidate_map_cache(void)

{

    unsigned long i;

    MapCacheRev *reventry;

    /* Flush pending AIO before destroying the mapcache */

    bdrv_drain_all();

    QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {

        DPRINTF("There should be no locked mappings at this time, "

                "but "TARGET_FMT_plx" -> %p is present\n",

                reventry->paddr_index, reventry->vaddr_req);

    }

    mapcache_lock();

    for (i = 0; i < mapcache->nr_buckets; i++) {

        MapCacheEntry *entry = &mapcache->entry[i];

        if (entry->vaddr_base == NULL) {

            continue;

        }

        if (entry->lock > 0) {

            continue;

        }

        if (munmap(entry->vaddr_base, entry->size) != 0) {

            perror("unmap fails");

            exit(-1);

        }

        entry->paddr_index = 0;

        entry->vaddr_base = NULL;

        entry->size = 0;

        g_free(entry->valid_mapping);

        entry->valid_mapping = NULL;

    }

    mapcache->last_entry = NULL;

    mapcache_unlock();

}


static uint64_t omap_clkdsp_read(void *opaque, target_phys_addr_t addr,

                                 unsigned size)

{

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

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (addr) {

    case 0x04:	/* DSP_IDLECT1 */

        return s->clkm.dsp_idlect1;

    case 0x08:	/* DSP_IDLECT2 */

        return s->clkm.dsp_idlect2;

    case 0x14:	/* DSP_RSTCT2 */

        return s->clkm.dsp_rstct2;

    case 0x18:	/* DSP_SYSST */

        return (s->clkm.clocking_scheme << 11) | s->clkm.cold_start |

                (s->cpu->env.halted << 6);      /* Quite useless... */

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static int fd_close(MigrationState *s)

{

    DPRINTF("fd_close\n");

    if (s->fd != -1) {

        close(s->fd);

        s->fd = -1;

    }

    return 0;

}


static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext)

{

    OggVorbisContext *context = avccontext->priv_data;

    ogg_packet header, header_comm, header_code;

    uint8_t *p;

    unsigned int offset;

    vorbis_info_init(&context->vi);

    if (oggvorbis_init_encoder(&context->vi, avccontext) < 0) {

        av_log(avccontext, AV_LOG_ERROR, "oggvorbis_encode_init: init_encoder failed\n");

        return -1;

    }

    vorbis_analysis_init(&context->vd, &context->vi);

    vorbis_block_init(&context->vd, &context->vb);

    vorbis_comment_init(&context->vc);

    vorbis_comment_add_tag(&context->vc, "encoder", LIBAVCODEC_IDENT);

    vorbis_analysis_headerout(&context->vd, &context->vc, &header,

                              &header_comm, &header_code);

    avccontext->extradata_size =

        1 + xiph_len(header.bytes) + xiph_len(header_comm.bytes) +

        header_code.bytes;

    p = avccontext->extradata =

            av_malloc(avccontext->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

    p[0]    = 2;

    offset  = 1;

    offset += av_xiphlacing(&p[offset], header.bytes);

    offset += av_xiphlacing(&p[offset], header_comm.bytes);

    memcpy(&p[offset], header.packet, header.bytes);

    offset += header.bytes;

    memcpy(&p[offset], header_comm.packet, header_comm.bytes);

    offset += header_comm.bytes;

    memcpy(&p[offset], header_code.packet, header_code.bytes);

    offset += header_code.bytes;

    assert(offset == avccontext->extradata_size);

#if 0

    vorbis_block_clear(&context->vb);

    vorbis_dsp_clear(&context->vd);

    vorbis_info_clear(&context->vi);

#endif

    vorbis_comment_clear(&context->vc);

    avccontext->frame_size = OGGVORBIS_FRAME_SIZE;

    avccontext->coded_frame = avcodec_alloc_frame();

    return 0;

}


static int iff_read_header(AVFormatContext *s)

{

    IffDemuxContext *iff = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st;

    uint8_t *buf;

    uint32_t chunk_id, data_size;

    uint32_t screenmode = 0, num, den;

    unsigned transparency = 0;

    unsigned masking = 0; // no mask

    uint8_t fmt[16];

    int fmt_size;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->channels = 1;

    st->codec->channel_layout = AV_CH_LAYOUT_MONO;

    avio_skip(pb, 8);

    // codec_tag used by ByteRun1 decoder to distinguish progressive (PBM) and interlaced (ILBM) content

    st->codec->codec_tag = avio_rl32(pb);

    while(!url_feof(pb)) {

        uint64_t orig_pos;

        int res;

        const char *metadata_tag = NULL;

        chunk_id = avio_rl32(pb);

        data_size = avio_rb32(pb);

        orig_pos = avio_tell(pb);

        switch(chunk_id) {

        case ID_VHDR:

            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            if (data_size < 14)

                return AVERROR_INVALIDDATA;

            avio_skip(pb, 12);

            st->codec->sample_rate = avio_rb16(pb);

            if (data_size >= 16) {

                avio_skip(pb, 1);

                iff->svx8_compression = avio_r8(pb);

            }

            break;

        case ID_MHDR:

            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            iff->maud_bits = -1;

            iff->maud_compression = -1;

            if (data_size < 32)

                return AVERROR_INVALIDDATA;

            avio_skip(pb, 4);

            iff->maud_bits = avio_rb16(pb);

            avio_skip(pb, 2);

            num = avio_rb32(pb);

            den = avio_rb16(pb);

            if (!den)

                return AVERROR_INVALIDDATA;

            avio_skip(pb, 2);

            st->codec->sample_rate = num / den;

            st->codec->channels = avio_rb16(pb);

            iff->maud_compression = avio_rb16(pb);

            if (st->codec->channels == 1)

                st->codec->channel_layout = AV_CH_LAYOUT_MONO;

            else if (st->codec->channels == 2)

                st->codec->channel_layout = AV_CH_LAYOUT_STEREO;

            break;

        case ID_ABIT:

        case ID_BODY:

        case ID_DBOD:

        case ID_MDAT:

            iff->body_pos = avio_tell(pb);

            iff->body_size = data_size;

            break;

        case ID_CHAN:

            if (data_size < 4)

                return AVERROR_INVALIDDATA;

            if (avio_rb32(pb) < 6) {

                st->codec->channels       = 1;

                st->codec->channel_layout = AV_CH_LAYOUT_MONO;

            } else {

                st->codec->channels       = 2;

                st->codec->channel_layout = AV_CH_LAYOUT_STEREO;

            }

            break;

        case ID_CAMG:

            if (data_size < 4)

                return AVERROR_INVALIDDATA;

            screenmode                = avio_rb32(pb);

            break;

        case ID_CMAP:

            st->codec->extradata_size = data_size + IFF_EXTRA_VIDEO_SIZE;

            st->codec->extradata      = av_malloc(data_size + IFF_EXTRA_VIDEO_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!st->codec->extradata)

                return AVERROR(ENOMEM);

            if (avio_read(pb, st->codec->extradata + IFF_EXTRA_VIDEO_SIZE, data_size) < 0)

                return AVERROR(EIO);

            break;

        case ID_BMHD:

            iff->bitmap_compression = -1;

            st->codec->codec_type            = AVMEDIA_TYPE_VIDEO;

            if (data_size <= 8)

                return AVERROR_INVALIDDATA;

            st->codec->width                 = avio_rb16(pb);

            st->codec->height                = avio_rb16(pb);

            avio_skip(pb, 4); // x, y offset

            st->codec->bits_per_coded_sample = avio_r8(pb);

            if (data_size >= 10)

                masking                      = avio_r8(pb);

            if (data_size >= 11)

                iff->bitmap_compression      = avio_r8(pb);

            if (data_size >= 14) {

                avio_skip(pb, 1); // padding

                transparency                 = avio_rb16(pb);

            }

            if (data_size >= 16) {

                st->sample_aspect_ratio.num  = avio_r8(pb);

                st->sample_aspect_ratio.den  = avio_r8(pb);

            }

            break;

        case ID_DPEL:

            if (data_size < 4 || (data_size & 3))

                return AVERROR_INVALIDDATA;

            if ((fmt_size = avio_read(pb, fmt, sizeof(fmt))) < 0)

                return fmt_size;

            if (fmt_size == sizeof(deep_rgb24) && !memcmp(fmt, deep_rgb24, sizeof(deep_rgb24)))

                st->codec->pix_fmt = AV_PIX_FMT_RGB24;

            else if (fmt_size == sizeof(deep_rgba) && !memcmp(fmt, deep_rgba, sizeof(deep_rgba)))

                st->codec->pix_fmt = AV_PIX_FMT_RGBA;

            else if (fmt_size == sizeof(deep_bgra) && !memcmp(fmt, deep_bgra, sizeof(deep_bgra)))

                st->codec->pix_fmt = AV_PIX_FMT_BGRA;

            else if (fmt_size == sizeof(deep_argb) && !memcmp(fmt, deep_argb, sizeof(deep_argb)))

                st->codec->pix_fmt = AV_PIX_FMT_ARGB;

            else if (fmt_size == sizeof(deep_abgr) && !memcmp(fmt, deep_abgr, sizeof(deep_abgr)))

                st->codec->pix_fmt = AV_PIX_FMT_ABGR;

            else {

                av_log_ask_for_sample(s, "unsupported color format\n");

                return AVERROR_PATCHWELCOME;

            }

            break;

        case ID_DGBL:

            st->codec->codec_type            = AVMEDIA_TYPE_VIDEO;

            if (data_size < 8)

                return AVERROR_INVALIDDATA;

            st->codec->width                 = avio_rb16(pb);

            st->codec->height                = avio_rb16(pb);

            iff->bitmap_compression          = avio_rb16(pb);

            st->sample_aspect_ratio.num      = avio_r8(pb);

            st->sample_aspect_ratio.den      = avio_r8(pb);

            st->codec->bits_per_coded_sample = 24;

            break;

        case ID_DLOC:

            if (data_size < 4)

                return AVERROR_INVALIDDATA;

            st->codec->width  = avio_rb16(pb);

            st->codec->height = avio_rb16(pb);

            break;

        case ID_ANNO:

        case ID_TEXT:      metadata_tag = "comment";   break;

        case ID_AUTH:      metadata_tag = "artist";    break;

        case ID_COPYRIGHT: metadata_tag = "copyright"; break;

        case ID_NAME:      metadata_tag = "title";     break;

        }

        if (metadata_tag) {

            if ((res = get_metadata(s, metadata_tag, data_size)) < 0) {

                av_log(s, AV_LOG_ERROR, "cannot allocate metadata tag %s!\n", metadata_tag);

                return res;

            }

        }

        avio_skip(pb, data_size - (avio_tell(pb) - orig_pos) + (data_size & 1));

    }

    avio_seek(pb, iff->body_pos, SEEK_SET);

    switch(st->codec->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);

        if (st->codec->codec_tag == ID_16SV)

            st->codec->codec_id = AV_CODEC_ID_PCM_S16BE_PLANAR;

        else if (st->codec->codec_tag == ID_MAUD) {

            if (iff->maud_bits == 8 && !iff->maud_compression) {

                st->codec->codec_id = AV_CODEC_ID_PCM_U8;

            } else if (iff->maud_bits == 16 && !iff->maud_compression) {

                st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;

            } else if (iff->maud_bits ==  8 && iff->maud_compression == 2) {

                st->codec->codec_id = AV_CODEC_ID_PCM_ALAW;

            } else if (iff->maud_bits ==  8 && iff->maud_compression == 3) {

                st->codec->codec_id = AV_CODEC_ID_PCM_MULAW;

            } else {

                av_log_ask_for_sample(s, "unsupported compression %d and bit depth %d\n", iff->maud_compression, iff->maud_bits);

                return AVERROR_PATCHWELCOME;

            }

            st->codec->bits_per_coded_sample =

                av_get_bits_per_sample(st->codec->codec_id);

            st->codec->block_align =

                st->codec->bits_per_coded_sample * st->codec->channels / 8;

        } else {

        switch (iff->svx8_compression) {

        case COMP_NONE:

            st->codec->codec_id = AV_CODEC_ID_PCM_S8_PLANAR;

            break;

        case COMP_FIB:

            st->codec->codec_id = AV_CODEC_ID_8SVX_FIB;

            break;

        case COMP_EXP:

            st->codec->codec_id = AV_CODEC_ID_8SVX_EXP;

            break;

        default:

            av_log(s, AV_LOG_ERROR,

                   "Unknown SVX8 compression method '%d'\n", iff->svx8_compression);

            return -1;

        }

        }

        st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);

        st->codec->bit_rate = st->codec->channels * st->codec->sample_rate * st->codec->bits_per_coded_sample;

        st->codec->block_align = st->codec->channels * st->codec->bits_per_coded_sample;

        break;

    case AVMEDIA_TYPE_VIDEO:

        iff->bpp          = st->codec->bits_per_coded_sample;

        if ((screenmode & 0x800 /* Hold And Modify */) && iff->bpp <= 8) {

            iff->ham      = iff->bpp > 6 ? 6 : 4;

            st->codec->bits_per_coded_sample = 24;

        }

        iff->flags        = (screenmode & 0x80 /* Extra HalfBrite */) && iff->bpp <= 8;

        iff->masking      = masking;

        iff->transparency = transparency;

        if (!st->codec->extradata) {

            st->codec->extradata_size = IFF_EXTRA_VIDEO_SIZE;

            st->codec->extradata      = av_malloc(IFF_EXTRA_VIDEO_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!st->codec->extradata)

                return AVERROR(ENOMEM);

        }

        buf = st->codec->extradata;

        bytestream_put_be16(&buf, IFF_EXTRA_VIDEO_SIZE);

        bytestream_put_byte(&buf, iff->bitmap_compression);

        bytestream_put_byte(&buf, iff->bpp);

        bytestream_put_byte(&buf, iff->ham);

        bytestream_put_byte(&buf, iff->flags);

        bytestream_put_be16(&buf, iff->transparency);

        bytestream_put_byte(&buf, iff->masking);

        st->codec->codec_id = AV_CODEC_ID_IFF_ILBM;

        break;

    default:

        return -1;

    }

    return 0;

}


static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)

{

    int i, j, k;

    int scheme;

    int current_macroblock;

    int current_fragment;

    int coding_mode;

    int custom_mode_alphabet[CODING_MODE_COUNT];

    if (s->keyframe) {

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

            s->all_fragments[i].coding_method = MODE_INTRA;

    } else {

        /* fetch the mode coding scheme for this frame */

        scheme = get_bits(gb, 3);

        /* is it a custom coding scheme? */

        if (scheme == 0) {

                custom_mode_alphabet[get_bits(gb, 3)] = i;

        }

        /* iterate through all of the macroblocks that contain 1 or more

         * coded fragments */

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

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

                current_macroblock = s->superblock_macroblocks[i * 4 + j];

                if ((current_macroblock == -1) ||

                    (s->macroblock_coding[current_macroblock] == MODE_COPY))

                    continue;

                if (current_macroblock >= s->macroblock_count) {

                    av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_modes(): bad macroblock number (%d >= %d)\n",

                        current_macroblock, s->macroblock_count);

                    return 1;

                }

                /* mode 7 means get 3 bits for each coding mode */

                if (scheme == 7)

                    coding_mode = get_bits(gb, 3);

                else if(scheme == 0)

                    coding_mode = custom_mode_alphabet

                        [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];

                else

                    coding_mode = ModeAlphabet[scheme-1]

                        [get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];

                s->macroblock_coding[current_macroblock] = coding_mode;

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

                    current_fragment =

                        s->macroblock_fragments[current_macroblock * 6 + k];

                    if (current_fragment == -1)

                        continue;

                    if (current_fragment >= s->fragment_count) {

                        av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_modes(): bad fragment number (%d >= %d)\n",

                            current_fragment, s->fragment_count);

                        return 1;

                    }

                    if (s->all_fragments[current_fragment].coding_method !=

                        MODE_COPY)

                        s->all_fragments[current_fragment].coding_method =

                            coding_mode;

                }

            }

        }

    }

    return 0;

}


struct USBEndpoint *usb_ep_get(USBDevice *dev, int pid, int ep)

{

    struct USBEndpoint *eps = pid == USB_TOKEN_IN ? dev->ep_in : dev->ep_out;

    if (ep == 0) {

        return &dev->ep_ctl;

    }

    assert(pid == USB_TOKEN_IN || pid == USB_TOKEN_OUT);

    assert(ep > 0 && ep <= USB_MAX_ENDPOINTS);

    return eps + ep - 1;

}


static int vpx_decode(AVCodecContext *avctx,

                      void *data, int *got_frame, AVPacket *avpkt)

{

    VPxContext *ctx = avctx->priv_data;

    AVFrame *picture = data;

    const void *iter = NULL;

    const void *iter_alpha = NULL;

    struct vpx_image *img, *img_alpha;

    int ret;

    uint8_t *side_data = NULL;

    int side_data_size = 0;

    ret = decode_frame(avctx, &ctx->decoder, avpkt->data, avpkt->size);

    if (ret)

        return ret;

    side_data = av_packet_get_side_data(avpkt,

                                        AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,

                                        &side_data_size);

    if (side_data_size > 1) {

        const uint64_t additional_id = AV_RB64(side_data);

        side_data += 8;

        side_data_size -= 8;

        if (additional_id == 1) {  // 1 stands for alpha channel data.

            if (!ctx->has_alpha_channel) {

                ctx->has_alpha_channel = 1;

                ret = vpx_init(avctx,

#if CONFIG_LIBVPX_VP8_DECODER && CONFIG_LIBVPX_VP9_DECODER

                               (avctx->codec_id == AV_CODEC_ID_VP8) ?

                               &vpx_codec_vp8_dx_algo : &vpx_codec_vp9_dx_algo,

#elif CONFIG_LIBVPX_VP8_DECODER

                               &vpx_codec_vp8_dx_algo,

#else

                               &vpx_codec_vp9_dx_algo,

#endif

                               1);

                if (ret)

                    return ret;

            }

            ret = decode_frame(avctx, &ctx->decoder_alpha, side_data,

                               side_data_size);

            if (ret)

                return ret;

        }

    }

    if ((img = vpx_codec_get_frame(&ctx->decoder, &iter)) &&

        (!ctx->has_alpha_channel ||

         (img_alpha = vpx_codec_get_frame(&ctx->decoder_alpha, &iter_alpha)))) {

        uint8_t *planes[4];

        int linesizes[4];

        if (img->d_w > img->w || img->d_h > img->h) {

            av_log(avctx, AV_LOG_ERROR, "Display dimensions %dx%d exceed storage %dx%d\n",

                   img->d_w, img->d_h, img->w, img->h);

            return AVERROR_EXTERNAL;

        }

        if ((ret = set_pix_fmt(avctx, img, ctx->has_alpha_channel)) < 0) {

#ifdef VPX_IMG_FMT_HIGHBITDEPTH

            av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d) / bit_depth (%d)\n",

                   img->fmt, img->bit_depth);

#else

            av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d) / bit_depth (%d)\n",

                   img->fmt, 8);

#endif

            return ret;

        }

        if ((int) img->d_w != avctx->width || (int) img->d_h != avctx->height) {

            av_log(avctx, AV_LOG_INFO, "dimension change! %dx%d -> %dx%d\n",

                   avctx->width, avctx->height, img->d_w, img->d_h);

            ret = ff_set_dimensions(avctx, img->d_w, img->d_h);

            if (ret < 0)

                return ret;

        }

        if ((ret = ff_get_buffer(avctx, picture, 0)) < 0)

            return ret;

        planes[0] = img->planes[VPX_PLANE_Y];

        planes[1] = img->planes[VPX_PLANE_U];

        planes[2] = img->planes[VPX_PLANE_V];

        planes[3] =

            ctx->has_alpha_channel ? img_alpha->planes[VPX_PLANE_Y] : NULL;

        linesizes[0] = img->stride[VPX_PLANE_Y];

        linesizes[1] = img->stride[VPX_PLANE_U];

        linesizes[2] = img->stride[VPX_PLANE_V];

        linesizes[3] =

            ctx->has_alpha_channel ? img_alpha->stride[VPX_PLANE_Y] : 0;

        av_image_copy(picture->data, picture->linesize, (const uint8_t**)planes,

                      linesizes, avctx->pix_fmt, img->d_w, img->d_h);

        *got_frame           = 1;

    }

    return avpkt->size;

}


static int ipvideo_decode_block_opcode_0xB(IpvideoContext *s)

{

    int y;

    /* 64-color encoding (each pixel in block is a different color) */

    CHECK_STREAM_PTR(64);

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

        memcpy(s->pixel_ptr, s->stream_ptr, 8);

        s->stream_ptr += 8;

        s->pixel_ptr  += s->stride;

    }

    /* report success */

    return 0;

}


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

{

    int i;

    int width;

    int height;

    int64_t disp_transform[2];

    int display_matrix[3][3];

    AVStream *st;

    MOVStreamContext *sc;

    int version;

    int flags;

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

        return 0;

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

    sc = st->priv_data;

    version = avio_r8(pb);

    flags = avio_rb24(pb);

    st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;

    if (version == 1) {

        avio_rb64(pb);

        avio_rb64(pb);

    } else {

        avio_rb32(pb); /* creation time */

        avio_rb32(pb); /* modification time */

    }

    st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/

    avio_rb32(pb); /* reserved */

    /* highlevel (considering edits) duration in movie timebase */

    (version == 1) ? avio_rb64(pb) : avio_rb32(pb);

    avio_rb32(pb); /* reserved */

    avio_rb32(pb); /* reserved */

    avio_rb16(pb); /* layer */

    avio_rb16(pb); /* alternate group */

    avio_rb16(pb); /* volume */

    avio_rb16(pb); /* reserved */

    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)

    // they're kept in fixed point format through all calculations

    // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX

    // side data, but the scale factor is not needed to calculate aspect ratio

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

        display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point

        display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point

        display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point

    }

    width = avio_rb32(pb);       // 16.16 fixed point track width

    height = avio_rb32(pb);      // 16.16 fixed point track height

    sc->width = width >> 16;

    sc->height = height >> 16;

    // save the matrix when it is not the default identity

    if (display_matrix[0][0] != (1 << 16) ||

        display_matrix[1][1] != (1 << 16) ||

        display_matrix[2][2] != (1 << 30) ||

        display_matrix[0][1] || display_matrix[0][2] ||

        display_matrix[1][0] || display_matrix[1][2] ||

        display_matrix[2][0] || display_matrix[2][1]) {

        int i, j;

        av_freep(&sc->display_matrix);

        sc->display_matrix = av_malloc(sizeof(int32_t) * 9);

        if (!sc->display_matrix)

            return AVERROR(ENOMEM);

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

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

                sc->display_matrix[i * 3 + j] = display_matrix[j][i];

    }

    // transform the display width/height according to the matrix

    // skip this if the rotation angle is 0 degrees

    // to keep the same scale, use [width height 1<<16]

    if (width && height && sc->display_matrix &&

        av_display_rotation_get(sc->display_matrix) != 0.0f) {

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

            disp_transform[i] =

                (int64_t)  width  * display_matrix[0][i] +

                (int64_t)  height * display_matrix[1][i] +

                ((int64_t) display_matrix[2][i] << 16);

        //sample aspect ratio is new width/height divided by old width/height

        st->sample_aspect_ratio = av_d2q(

            ((double) disp_transform[0] * height) /

            ((double) disp_transform[1] * width), INT_MAX);

    }

    return 0;

}


uint8_t *av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type,

                                 int size)

{

    int elems = pkt->side_data_elems;

    if ((unsigned)elems + 1 > INT_MAX / sizeof(*pkt->side_data))

        return NULL;

    if ((unsigned)size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)

        return NULL;

    pkt->side_data = av_realloc(pkt->side_data,

                                (elems + 1) * sizeof(*pkt->side_data));

    if (!pkt->side_data)

        return NULL;

    pkt->side_data[elems].data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!pkt->side_data[elems].data)

        return NULL;

    pkt->side_data[elems].size = size;

    pkt->side_data[elems].type = type;

    pkt->side_data_elems++;

    return pkt->side_data[elems].data;

}


static void pointer_event(VncState *vs, int button_mask, int x, int y)

{

    static uint32_t bmap[INPUT_BUTTON_MAX] = {

        [INPUT_BUTTON_LEFT]       = 0x01,

        [INPUT_BUTTON_MIDDLE]     = 0x02,

        [INPUT_BUTTON_RIGHT]      = 0x04,

        [INPUT_BUTTON_WHEEL_UP]   = 0x08,

        [INPUT_BUTTON_WHEEL_DOWN] = 0x10,

    };

    QemuConsole *con = vs->vd->dcl.con;

    int width = surface_width(vs->vd->ds);

    int height = surface_height(vs->vd->ds);

    if (vs->last_bmask != button_mask) {

        qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);

        vs->last_bmask = button_mask;

    }

    if (vs->absolute) {

        qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);

        qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);

    } else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {

        qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);

        qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);

    } else {

        if (vs->last_x != -1) {

            qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);

            qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);

        }

        vs->last_x = x;

        vs->last_y = y;

    }

    qemu_input_event_sync();

}


void visit_type_uint16(Visitor *v, uint16_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (!error_is_set(errp)) {

        if (v->type_uint16) {

            v->type_uint16(v, obj, name, errp);

        } else {

            value = *obj;

            v->type_int(v, &value, name, errp);

            if (value < 0 || value > UINT16_MAX) {

                error_set(errp, QERR_INVALID_PARAMETER_VALUE, name ? name : "null",

                          "uint16_t");

                return;

            }

            *obj = value;

        }

    }

}


static void rtsp_parse_transport(RTSPMessageHeader *reply, const char *p)

{

    char transport_protocol[16];

    char profile[16];

    char lower_transport[16];

    char parameter[16];

    RTSPTransportField *th;

    char buf[256];

    reply->nb_transports = 0;

    for(;;) {

        skip_spaces(&p);

        if (*p == '\0')

            break;

        th = &reply->transports[reply->nb_transports];

        get_word_sep(transport_protocol, sizeof(transport_protocol),

                     "/", &p);

        if (!strcasecmp (transport_protocol, "rtp")) {

            get_word_sep(profile, sizeof(profile), "/;,", &p);

            lower_transport[0] = '\0';

            /* rtp/avp/<protocol> */

            if (*p == '/') {

                get_word_sep(lower_transport, sizeof(lower_transport),

                             ";,", &p);

            }

            th->transport = RTSP_TRANSPORT_RTP;

        } else if (!strcasecmp (transport_protocol, "x-pn-tng") ||

                   !strcasecmp (transport_protocol, "x-real-rdt")) {

            /* x-pn-tng/<protocol> */

            get_word_sep(lower_transport, sizeof(lower_transport), "/;,", &p);

            profile[0] = '\0';

            th->transport = RTSP_TRANSPORT_RDT;

        }

        if (!strcasecmp(lower_transport, "TCP"))

            th->lower_transport = RTSP_LOWER_TRANSPORT_TCP;

        else

            th->lower_transport = RTSP_LOWER_TRANSPORT_UDP;

        if (*p == ';')

            p++;

        /* get each parameter */

        while (*p != '\0' && *p != ',') {

            get_word_sep(parameter, sizeof(parameter), "=;,", &p);

            if (!strcmp(parameter, "port")) {

                if (*p == '=') {

                    p++;

                    rtsp_parse_range(&th->port_min, &th->port_max, &p);

                }

            } else if (!strcmp(parameter, "client_port")) {

                if (*p == '=') {

                    p++;

                    rtsp_parse_range(&th->client_port_min,

                                     &th->client_port_max, &p);

                }

            } else if (!strcmp(parameter, "server_port")) {

                if (*p == '=') {

                    p++;

                    rtsp_parse_range(&th->server_port_min,

                                     &th->server_port_max, &p);

                }

            } else if (!strcmp(parameter, "interleaved")) {

                if (*p == '=') {

                    p++;

                    rtsp_parse_range(&th->interleaved_min,

                                     &th->interleaved_max, &p);

                }

            } else if (!strcmp(parameter, "multicast")) {

                if (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP)

                    th->lower_transport = RTSP_LOWER_TRANSPORT_UDP_MULTICAST;

            } else if (!strcmp(parameter, "ttl")) {

                if (*p == '=') {

                    p++;

                    th->ttl = strtol(p, (char **)&p, 10);

                }

            } else if (!strcmp(parameter, "destination")) {

                struct in_addr ipaddr;

                if (*p == '=') {

                    p++;

                    get_word_sep(buf, sizeof(buf), ";,", &p);

                    if (inet_aton(buf, &ipaddr))

                        th->destination = ntohl(ipaddr.s_addr);

                }

            }

            while (*p != ';' && *p != '\0' && *p != ',')

                p++;

            if (*p == ';')

                p++;

        }

        if (*p == ',')

            p++;

        reply->nb_transports++;

    }

}


static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)

{

    offset_t pos = url_ftell(pb);

    put_be32(pb, 0);

    put_tag(pb, "avcC");

    if (track->vosLen > 6) {

        /* check for h264 start code */

        if (AV_RB32(track->vosData) == 0x00000001) {

            uint8_t *buf, *end;

            uint32_t sps_size=0, pps_size=0;

            uint8_t *sps=0, *pps=0;

            avc_parse_nal_units(&track->vosData, &track->vosLen);

            buf = track->vosData;

            end = track->vosData + track->vosLen;

            /* look for sps and pps */

            while (buf < end) {

                unsigned int size;

                uint8_t nal_type;

                size = AV_RB32(buf);

                nal_type = buf[4] & 0x1f;

                if (nal_type == 7) { /* SPS */

                    sps = buf + 4;

                    sps_size = size;

                } else if (nal_type == 8) { /* PPS */

                    pps = buf + 4;

                    pps_size = size;

                }

                buf += size + 4;

            }

            assert(sps);

            assert(pps);

            put_byte(pb, 1); /* version */

            put_byte(pb, sps[1]); /* profile */

            put_byte(pb, sps[2]); /* profile compat */

            put_byte(pb, sps[3]); /* level */

            put_byte(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */

            put_byte(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */

            put_be16(pb, sps_size);

            put_buffer(pb, sps, sps_size);

            put_byte(pb, 1); /* number of pps */

            put_be16(pb, pps_size);

            put_buffer(pb, pps, pps_size);

        } else {

            put_buffer(pb, track->vosData, track->vosLen);

        }

    }

    return updateSize(pb, pos);

}


static inline int compress_coeffs(int *coef, int order, int c_bits)

{

    int i, res = 0;

    const int low_idx   = c_bits ?  4 : 2;

    const int shift_val = c_bits ?  8 : 4;

    const int high_idx  = c_bits ? 11 : 5;

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

        if (coef[i] < low_idx || coef[i] > high_idx)

            res++;

    if (res == order)

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

            coef[i] -= (coef[i] > high_idx) ? shift_val : 0;

    return res == order;

}


static av_cold int indeo3_decode_end(AVCodecContext *avctx)
{
    Indeo3DecodeContext *s = avctx->priv_data;
    iv_free_func(s);
    return 0;
}


void qemu_iovec_destroy(QEMUIOVector *qiov)

{

    assert(qiov->nalloc != -1);

    g_free(qiov->iov);

}


bool virtio_blk_data_plane_create(VirtIODevice *vdev, VirtIOBlkConf *blk,
                                  VirtIOBlockDataPlane **dataplane)
{
    VirtIOBlockDataPlane *s;
    int fd;
    *dataplane = NULL;
    if (!blk->data_plane) {
        return true;
    if (blk->scsi) {
        error_report("device is incompatible with x-data-plane, use scsi=off");
    if (blk->config_wce) {
        error_report("device is incompatible with x-data-plane, "
                     "use config-wce=off");
    fd = raw_get_aio_fd(blk->conf.bs);
    if (fd < 0) {
        error_report("drive is incompatible with x-data-plane, "
                     "use format=raw,cache=none,aio=native");
    s = g_new0(VirtIOBlockDataPlane, 1);
    s->vdev = vdev;
    s->fd = fd;
    s->blk = blk;
    /* Prevent block operations that conflict with data plane thread */
    bdrv_set_in_use(blk->conf.bs, 1);
    *dataplane = s;
    return true;


void helper_sysexit(int dflag)

{

    int cpl;

    cpl = env->hflags & HF_CPL_MASK;

    if (env->sysenter_cs == 0 || cpl != 0) {

        raise_exception_err(EXCP0D_GPF, 0);

    }

    cpu_x86_set_cpl(env, 3);

#ifdef TARGET_X86_64

    if (dflag == 2) {

        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 32) & 0xfffc) | 3,

                               0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK | DESC_L_MASK);

        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 40) & 0xfffc) | 3,

                               0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_W_MASK | DESC_A_MASK);

    } else

#endif

    {

        cpu_x86_load_seg_cache(env, R_CS, ((env->sysenter_cs + 16) & 0xfffc) | 3,

                               0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK);

        cpu_x86_load_seg_cache(env, R_SS, ((env->sysenter_cs + 24) & 0xfffc) | 3,

                               0, 0xffffffff,

                               DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                               DESC_S_MASK | (3 << DESC_DPL_SHIFT) |

                               DESC_W_MASK | DESC_A_MASK);

    }

    ESP = ECX;

    EIP = EDX;

#ifdef CONFIG_KQEMU

    if (kqemu_is_ok(env)) {

        env->exception_index = -1;

        cpu_loop_exit();

    }

#endif

}


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

{

    printf("ECC: Unsupported write 0x" TARGET_FMT_plx " %02x\n",

           addr, val & 0xff);

}


static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,

                         const uint8_t *buf, int nb_sectors)

{

    int async_ret;

    BlockDriverAIOCB *acb;

    struct iovec iov;

    QEMUIOVector qiov;

    async_ret = NOT_DONE;

    iov.iov_base = (void *)buf;

    iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;

    qemu_iovec_init_external(&qiov, &iov, 1);

    acb = bs->drv->bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,

                                   bdrv_rw_em_cb, &async_ret);

    if (acb == NULL) {

        async_ret = -1;

        goto fail;

    }

    while (async_ret == NOT_DONE) {

        qemu_aio_wait();

    }

fail:

    return async_ret;

}


static uint32_t virtio_9p_get_features(VirtIODevice *vdev, uint32_t features)

{

    features |= 1 << VIRTIO_9P_MOUNT_TAG;

    return features;

}


static void restore_median_il(uint8_t *src, int step, int stride,

                              int width, int height, int slices, int rmode)

{

    int i, j, slice;

    int A, B, C;

    uint8_t *bsrc;

    int slice_start, slice_height;

    const int cmask   = ~(rmode ? 3 : 1);

    const int stride2 = stride << 1;

    for (slice = 0; slice < slices; slice++) {

        slice_start    = ((slice * height) / slices) & cmask;

        slice_height   = ((((slice + 1) * height) / slices) & cmask) -

                         slice_start;

        slice_height >>= 1;

        bsrc = src + slice_start * stride;

        // first line - left neighbour prediction

        bsrc[0] += 0x80;

        A        = bsrc[0];

        for (i = step; i < width * step; i += step) {

            bsrc[i] += A;

            A        = bsrc[i];

        }

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

            bsrc[stride + i] += A;

            A                 = bsrc[stride + i];

        }

        bsrc += stride2;

        if (slice_height == 1)

            continue;

        // second line - first element has top prediction, the rest uses median

        C        = bsrc[-stride2];

        bsrc[0] += C;

        A        = bsrc[0];

        for (i = step; i < width * step; i += step) {

            B        = bsrc[i - stride2];

            bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));

            C        = B;

            A        = bsrc[i];

        }

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

            B                 = bsrc[i - stride];

            bsrc[stride + i] += mid_pred(A, B, (uint8_t)(A + B - C));

            C                 = B;

            A                 = bsrc[stride + i];

        }

        bsrc += stride2;

        // the rest of lines use continuous median prediction

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

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

                B        = bsrc[i - stride2];

                bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));

                C        = B;

                A        = bsrc[i];

            }

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

                B                 = bsrc[i - stride];

                bsrc[i + stride] += mid_pred(A, B, (uint8_t)(A + B - C));

                C                 = B;

                A                 = bsrc[i + stride];

            }

            bsrc += stride2;

        }

    }

}


AVOpenCLExternalEnv *av_opencl_alloc_external_env(void)

{

    AVOpenCLExternalEnv *ext = av_mallocz(sizeof(AVOpenCLExternalEnv));

    if (!ext) {

        av_log(&openclutils, AV_LOG_ERROR,

         "Could not malloc external opencl environment data space\n");

    }

    return ext;

}


static uint64_t error_mem_read(void *opaque, target_phys_addr_t addr,

                               unsigned size)

{

    abort();

}


static void openpic_set_irq(void *opaque, int n_IRQ, int level)

{

    OpenPICState *opp = opaque;

    IRQSource *src;

    if (n_IRQ >= MAX_IRQ) {

        fprintf(stderr, "%s: IRQ %d out of range\n", __func__, n_IRQ);

        abort();

    }

    src = &opp->src[n_IRQ];

    DPRINTF("openpic: set irq %d = %d ivpr=0x%08x\n",

            n_IRQ, level, src->ivpr);

    if (src->level) {

        /* level-sensitive irq */

        src->pending = level;

        if (!level) {

            src->ivpr &= ~IVPR_ACTIVITY_MASK;

        }

    } else {

        /* edge-sensitive irq */

        if (level) {

            src->pending = 1;

        }

    }

    openpic_update_irq(opp, n_IRQ);

}


static int context_init(H264Context *h){

    CHECKED_ALLOCZ(h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t))

    CHECKED_ALLOCZ(h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t))

    return 0;

fail:

    return -1; // free_tables will clean up for us

}


void ff_snow_vertical_compose97i_mmx(DWTELEM *b0, DWTELEM *b1, DWTELEM *b2, DWTELEM *b3, DWTELEM *b4, DWTELEM *b5, int width){

    long i = width;

    while(i & 0x7)

    {

        i--;

        b4[i] -= (W_DM*(b3[i] + b5[i])+W_DO)>>W_DS;

        b3[i] -= (W_CM*(b2[i] + b4[i])+W_CO)>>W_CS;

        b2[i] += (W_BM*(b1[i] + b3[i])+4*b2[i]+W_BO)>>W_BS;

        b1[i] += (W_AM*(b0[i] + b2[i])+W_AO)>>W_AS;

    }

    asm volatile(

        "jmp 2f                                      \n\t"

        "1:                                          \n\t"

        "mov %6, %%"REG_a"                           \n\t"

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

        snow_vertical_compose_mmx_load(REG_S,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add(REG_a,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_move("mm0","mm2","mm4","mm6","mm1","mm3","mm5","mm7")

        snow_vertical_compose_mmx_r2r_add("mm0","mm2","mm4","mm6","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_r2r_add("mm1","mm3","mm5","mm7","mm0","mm2","mm4","mm6")

        "pcmpeqd %%mm1, %%mm1                        \n\t"

        "pslld $31, %%mm1                            \n\t"

        "psrld $29, %%mm1                            \n\t"

        "mov %5, %%"REG_a"                           \n\t"

        snow_vertical_compose_mmx_r2r_add("mm1","mm1","mm1","mm1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_sra("3","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_load(REG_a,"mm1","mm3","mm5","mm7")

        snow_vertical_compose_mmx_sub("mm0","mm2","mm4","mm6","mm1","mm3","mm5","mm7")

        snow_vertical_compose_mmx_store(REG_a,"mm1","mm3","mm5","mm7")

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

        snow_vertical_compose_mmx_load(REG_S,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add(REG_c,"mm1","mm3","mm5","mm7")

        snow_vertical_compose_mmx_sub("mm1","mm3","mm5","mm7","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_store(REG_S,"mm0","mm2","mm4","mm6")

        "mov %2, %%"REG_a"                           \n\t"

        snow_vertical_compose_mmx_add(REG_a,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_sra("2","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add(REG_c,"mm0","mm2","mm4","mm6")

        "pcmpeqd %%mm1, %%mm1                        \n\t"

        "pslld $31, %%mm1                            \n\t"

        "psrld $30, %%mm1                            \n\t"

        "mov %1, %%"REG_S"                           \n\t"

        snow_vertical_compose_mmx_r2r_add("mm1","mm1","mm1","mm1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_sra("2","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add(REG_c,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_store(REG_c,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add(REG_S,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_move("mm0","mm2","mm4","mm6","mm1","mm3","mm5","mm7")

        snow_vertical_compose_mmx_sra("1","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_r2r_add("mm1","mm3","mm5","mm7","mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_add(REG_a,"mm0","mm2","mm4","mm6")

        snow_vertical_compose_mmx_store(REG_a,"mm0","mm2","mm4","mm6")

        "2:                                          \n\t"

        "sub $8, %%"REG_d"                           \n\t"

        "jge 1b                                      \n\t"

        :"+d"(i)

        :

        "m"(b0),"m"(b1),"m"(b2),"m"(b3),"m"(b4),"m"(b5):

        "%"REG_a"","%"REG_S"","%"REG_c"");

}


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

{

    MXFPackage *package = arg;

    switch(tag) {

    case 0x4403:

        package->tracks_count = avio_rb32(pb);

        if (package->tracks_count >= UINT_MAX / sizeof(UID))

            return -1;

        package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));

        if (!package->tracks_refs)

            return -1;

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

        avio_read(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));

        break;

    }

    return 0;

}


static void rng_egd_finalize(Object *obj)

{

    RngEgd *s = RNG_EGD(obj);

    if (s->chr) {

        qemu_chr_add_handlers(s->chr, NULL, NULL, NULL, NULL);

        qemu_chr_fe_release(s->chr);

    }

    g_free(s->chr_name);

    rng_egd_free_requests(s);

}


static int cinepak_decode_strip (CinepakContext *s,
                                 cvid_strip_t *strip, uint8_t *data, int size)
{
    uint8_t *eod = (data + size);
    int      chunk_id, chunk_size;
    /* coordinate sanity checks */
    if (strip->x1 >= s->width  || strip->x2 > s->width  ||
        strip->y1 >= s->height || strip->y2 > s->height ||
        strip->x1 >= strip->x2 || strip->y1 >= strip->y2)
    while ((data + 4) <= eod) {
        chunk_id   = BE_16 (&data[0]);
        chunk_size = BE_16 (&data[2]) - 4;
        data      += 4;
        chunk_size = ((data + chunk_size) > eod) ? (eod - data) : chunk_size;
        switch (chunk_id) {
        case 0x2000:
        case 0x2100:
        case 0x2400:
        case 0x2500:
            cinepak_decode_codebook (strip->v4_codebook, chunk_id,
                chunk_size, data);
            break;
        case 0x2200:
        case 0x2300:
        case 0x2600:
        case 0x2700:
            cinepak_decode_codebook (strip->v1_codebook, chunk_id,
                chunk_size, data);
            break;
        case 0x3000:
        case 0x3100:
        case 0x3200:
            return cinepak_decode_vectors (s, strip, chunk_id,
                chunk_size, data);
        }
        data += chunk_size;
    }
}


void *av_realloc_array(void *ptr, size_t nmemb, size_t size)

{

    if (size <= 0 || nmemb >= INT_MAX / size)

        return NULL;

    return av_realloc(ptr, nmemb * size);

}


static inline void RENAME(vu9_to_vu12)(const uint8_t *src1, const uint8_t *src2,

			uint8_t *dst1, uint8_t *dst2,

			unsigned width, unsigned height,

			int srcStride1, int srcStride2,

			int dstStride1, int dstStride2)

{

    unsigned int y,x,h;

    int w;

    w=width/2; h=height/2;

#ifdef HAVE_MMX

    asm volatile(

	PREFETCH" %0\n\t"

	PREFETCH" %1\n\t"

	::"m"(*(src1+srcStride1)),"m"(*(src2+srcStride2)):"memory");

#endif

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

	const uint8_t* s1=src1+srcStride1*(y>>1);

	uint8_t* d=dst1+dstStride1*y;

	x=0;

#ifdef HAVE_MMX

	for(;x<w-31;x+=32)

	{

	    asm volatile(

		PREFETCH" 32%1\n\t"

	        "movq	%1, %%mm0\n\t"

	        "movq	8%1, %%mm2\n\t"

	        "movq	16%1, %%mm4\n\t"

	        "movq	24%1, %%mm6\n\t"

	        "movq	%%mm0, %%mm1\n\t"

	        "movq	%%mm2, %%mm3\n\t"

	        "movq	%%mm4, %%mm5\n\t"

	        "movq	%%mm6, %%mm7\n\t"

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

		"punpckhbw %%mm1, %%mm1\n\t"

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

		"punpckhbw %%mm3, %%mm3\n\t"

		"punpcklbw %%mm4, %%mm4\n\t"

		"punpckhbw %%mm5, %%mm5\n\t"

		"punpcklbw %%mm6, %%mm6\n\t"

		"punpckhbw %%mm7, %%mm7\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		MOVNTQ"	%%mm1, 8%0\n\t"

		MOVNTQ"	%%mm2, 16%0\n\t"

		MOVNTQ"	%%mm3, 24%0\n\t"

		MOVNTQ"	%%mm4, 32%0\n\t"

		MOVNTQ"	%%mm5, 40%0\n\t"

		MOVNTQ"	%%mm6, 48%0\n\t"

		MOVNTQ"	%%mm7, 56%0"

		:"=m"(d[2*x])

		:"m"(s1[x])

		:"memory");

	}

#endif

	for(;x<w;x++) d[2*x]=d[2*x+1]=s1[x];

    }

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

	const uint8_t* s2=src2+srcStride2*(y>>1);

	uint8_t* d=dst2+dstStride2*y;

	x=0;

#ifdef HAVE_MMX

	for(;x<w-31;x+=32)

	{

	    asm volatile(

		PREFETCH" 32%1\n\t"

	        "movq	%1, %%mm0\n\t"

	        "movq	8%1, %%mm2\n\t"

	        "movq	16%1, %%mm4\n\t"

	        "movq	24%1, %%mm6\n\t"

	        "movq	%%mm0, %%mm1\n\t"

	        "movq	%%mm2, %%mm3\n\t"

	        "movq	%%mm4, %%mm5\n\t"

	        "movq	%%mm6, %%mm7\n\t"

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

		"punpckhbw %%mm1, %%mm1\n\t"

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

		"punpckhbw %%mm3, %%mm3\n\t"

		"punpcklbw %%mm4, %%mm4\n\t"

		"punpckhbw %%mm5, %%mm5\n\t"

		"punpcklbw %%mm6, %%mm6\n\t"

		"punpckhbw %%mm7, %%mm7\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		MOVNTQ"	%%mm1, 8%0\n\t"

		MOVNTQ"	%%mm2, 16%0\n\t"

		MOVNTQ"	%%mm3, 24%0\n\t"

		MOVNTQ"	%%mm4, 32%0\n\t"

		MOVNTQ"	%%mm5, 40%0\n\t"

		MOVNTQ"	%%mm6, 48%0\n\t"

		MOVNTQ"	%%mm7, 56%0"

		:"=m"(d[2*x])

		:"m"(s2[x])

		:"memory");

	}

#endif

	for(;x<w;x++) d[2*x]=d[2*x+1]=s2[x];

    }

#ifdef HAVE_MMX

	asm(

		EMMS" \n\t"

		SFENCE" \n\t"

		::: "memory"

		);

#endif

}


int pic_read_irq(DeviceState *d)

{

    PICCommonState *s = DO_UPCAST(PICCommonState, dev.qdev, d);

    int irq, irq2, intno;

    irq = pic_get_irq(s);

    if (irq >= 0) {

        if (irq == 2) {

            irq2 = pic_get_irq(slave_pic);

            if (irq2 >= 0) {

                pic_intack(slave_pic, irq2);

            } else {

                /* spurious IRQ on slave controller */

                irq2 = 7;

            intno = slave_pic->irq_base + irq2;

        } else {

            intno = s->irq_base + irq;

        pic_intack(s, irq);

    } else {

        /* spurious IRQ on host controller */

        irq = 7;

        intno = s->irq_base + irq;

#if defined(DEBUG_PIC) || defined(DEBUG_IRQ_LATENCY)

    if (irq == 2) {

        irq = irq2 + 8;

#endif

#ifdef DEBUG_IRQ_LATENCY

    printf("IRQ%d latency=%0.3fus\n",

           irq,

           (double)(qemu_get_clock_ns(vm_clock) -

                    irq_time[irq]) * 1000000.0 / get_ticks_per_sec());

#endif

    DPRINTF("pic_interrupt: irq=%d\n", irq);

    return intno;


void memory_region_notify_one(IOMMUNotifier *notifier,

                              IOMMUTLBEntry *entry)

{

    IOMMUNotifierFlag request_flags;

    /*

     * Skip the notification if the notification does not overlap

     * with registered range.

     */

    if (notifier->start > entry->iova + entry->addr_mask + 1 ||

        notifier->end < entry->iova) {

        return;

    }

    if (entry->perm & IOMMU_RW) {

        request_flags = IOMMU_NOTIFIER_MAP;

    } else {

        request_flags = IOMMU_NOTIFIER_UNMAP;

    }

    if (notifier->notifier_flags & request_flags) {

        notifier->notify(notifier, entry);

    }

}


static void udp_chr_close(CharDriverState *chr)

{

    NetCharDriver *s = chr->opaque;

    if (s->tag) {

        g_source_remove(s->tag);

        s->tag = 0;

    }

    if (s->chan) {

        g_io_channel_unref(s->chan);

        closesocket(s->fd);

    }

    g_free(s);

    qemu_chr_be_event(chr, CHR_EVENT_CLOSED);

}