static int get_segment (CPUState *env, mmu_ctx_t *ctx,

                        target_ulong eaddr, int rw, int type)

{

    target_phys_addr_t sdr, hash, mask, sdr_mask, htab_mask;

    target_ulong sr, vsid, vsid_mask, pgidx, page_mask;

#if defined(TARGET_PPC64)

    int attr;

#endif

    int ds, nx, vsid_sh, sdr_sh;

    int ret, ret2;

#if defined(TARGET_PPC64)

    if (env->mmu_model == POWERPC_MMU_64B) {

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "Check SLBs\n");

        }

#endif

        ret = slb_lookup(env, eaddr, &vsid, &page_mask, &attr);

        if (ret < 0)

            return ret;

        ctx->key = ((attr & 0x40) && msr_pr == 1) ||

            ((attr & 0x80) && msr_pr == 0) ? 1 : 0;

        ds = 0;

        nx = attr & 0x20 ? 1 : 0;

        vsid_mask = 0x00003FFFFFFFFF80ULL;

        vsid_sh = 7;

        sdr_sh = 18;

        sdr_mask = 0x3FF80;

    } else

#endif /* defined(TARGET_PPC64) */

    {

        sr = env->sr[eaddr >> 28];

        page_mask = 0x0FFFFFFF;

        ctx->key = (((sr & 0x20000000) && msr_pr == 1) ||

                    ((sr & 0x40000000) && msr_pr == 0)) ? 1 : 0;

        ds = sr & 0x80000000 ? 1 : 0;

        nx = sr & 0x10000000 ? 1 : 0;

        vsid = sr & 0x00FFFFFF;

        vsid_mask = 0x01FFFFC0;

        vsid_sh = 6;

        sdr_sh = 16;

        sdr_mask = 0xFFC0;

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "Check segment v=0x" ADDRX " %d 0x" ADDRX

                    " nip=0x" ADDRX " lr=0x" ADDRX

                    " ir=%d dr=%d pr=%d %d t=%d\n",

                    eaddr, (int)(eaddr >> 28), sr, env->nip,

                    env->lr, msr_ir, msr_dr, msr_pr, rw, type);

        }

#endif

    }

#if defined (DEBUG_MMU)

    if (loglevel != 0) {

        fprintf(logfile, "pte segment: key=%d ds %d nx %d vsid " ADDRX "\n",

                ctx->key, ds, nx, vsid);

    }

#endif

    ret = -1;

    if (!ds) {

        /* Check if instruction fetch is allowed, if needed */

        if (type != ACCESS_CODE || nx == 0) {

            /* Page address translation */

            /* Primary table address */

            sdr = env->sdr1;

            pgidx = (eaddr & page_mask) >> TARGET_PAGE_BITS;

#if defined(TARGET_PPC64)

            if (env->mmu_model == POWERPC_MMU_64B) {

                htab_mask = 0x0FFFFFFF >> (28 - (sdr & 0x1F));

                /* XXX: this is false for 1 TB segments */

                hash = ((vsid ^ pgidx) << vsid_sh) & vsid_mask;

            } else

#endif

            {

                htab_mask = sdr & 0x000001FF;

                hash = ((vsid ^ pgidx) << vsid_sh) & vsid_mask;

            }

            mask = (htab_mask << sdr_sh) | sdr_mask;

#if defined (DEBUG_MMU)

            if (loglevel != 0) {

                fprintf(logfile, "sdr " PADDRX " sh %d hash " PADDRX " mask "

                        PADDRX " " ADDRX "\n", sdr, sdr_sh, hash, mask,

                        page_mask);

            }

#endif

            ctx->pg_addr[0] = get_pgaddr(sdr, sdr_sh, hash, mask);

            /* Secondary table address */

            hash = (~hash) & vsid_mask;

#if defined (DEBUG_MMU)

            if (loglevel != 0) {

                fprintf(logfile, "sdr " PADDRX " sh %d hash " PADDRX " mask "

                        PADDRX "\n", sdr, sdr_sh, hash, mask);

            }

#endif

            ctx->pg_addr[1] = get_pgaddr(sdr, sdr_sh, hash, mask);

#if defined(TARGET_PPC64)

            if (env->mmu_model == POWERPC_MMU_64B) {

                /* Only 5 bits of the page index are used in the AVPN */

                ctx->ptem = (vsid << 12) | ((pgidx >> 4) & 0x0F80);

            } else

#endif

            {

                ctx->ptem = (vsid << 7) | (pgidx >> 10);

            }

            /* Initialize real address with an invalid value */

            ctx->raddr = (target_ulong)-1;

            if (unlikely(env->mmu_model == POWERPC_MMU_SOFT_6xx ||

                         env->mmu_model == POWERPC_MMU_SOFT_74xx)) {

                /* Software TLB search */

                ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);

            } else {

#if defined (DEBUG_MMU)

                if (loglevel != 0) {

                    fprintf(logfile, "0 sdr1=0x" PADDRX " vsid=0x%06x "

                            "api=0x%04x hash=0x%07x pg_addr=0x" PADDRX "\n",

                            sdr, (uint32_t)vsid, (uint32_t)pgidx,

                            (uint32_t)hash, ctx->pg_addr[0]);

                }

#endif

                /* Primary table lookup */

                ret = find_pte(env, ctx, 0, rw);

                if (ret < 0) {

                    /* Secondary table lookup */

#if defined (DEBUG_MMU)

                    if (eaddr != 0xEFFFFFFF && loglevel != 0) {

                        fprintf(logfile,

                                "1 sdr1=0x" PADDRX " vsid=0x%06x api=0x%04x "

                                "hash=0x%05x pg_addr=0x" PADDRX "\n",

                                sdr, (uint32_t)vsid, (uint32_t)pgidx,

                                (uint32_t)hash, ctx->pg_addr[1]);

                    }

#endif

                    ret2 = find_pte(env, ctx, 1, rw);

                    if (ret2 != -1)

                        ret = ret2;

                }

            }

#if defined (DEBUG_MMU)

            if (loglevel != 0) {

                target_phys_addr_t curaddr;

                uint32_t a0, a1, a2, a3;

                fprintf(logfile,

                        "Page table: " PADDRX " len " PADDRX "\n",

                        sdr, mask + 0x80);

                for (curaddr = sdr; curaddr < (sdr + mask + 0x80);

                     curaddr += 16) {

                    a0 = ldl_phys(curaddr);

                    a1 = ldl_phys(curaddr + 4);

                    a2 = ldl_phys(curaddr + 8);

                    a3 = ldl_phys(curaddr + 12);

                    if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {

                        fprintf(logfile,

                                PADDRX ": %08x %08x %08x %08x\n",

                                curaddr, a0, a1, a2, a3);

                    }

                }

            }

#endif

        } else {

#if defined (DEBUG_MMU)

            if (loglevel != 0)

                fprintf(logfile, "No access allowed\n");

#endif

            ret = -3;

        }

    } else {

#if defined (DEBUG_MMU)

        if (loglevel != 0)

            fprintf(logfile, "direct store...\n");

#endif

        /* Direct-store segment : absolutely *BUGGY* for now */

        switch (type) {

        case ACCESS_INT:

            /* Integer load/store : only access allowed */

            break;

        case ACCESS_CODE:

            /* No code fetch is allowed in direct-store areas */

            return -4;

        case ACCESS_FLOAT:

            /* Floating point load/store */

            return -4;

        case ACCESS_RES:

            /* lwarx, ldarx or srwcx. */

            return -4;

        case ACCESS_CACHE:

            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */

            /* Should make the instruction do no-op.

             * As it already do no-op, it's quite easy :-)

             */

            ctx->raddr = eaddr;

            return 0;

        case ACCESS_EXT:

            /* eciwx or ecowx */

            return -4;

        default:

            if (logfile) {

                fprintf(logfile, "ERROR: instruction should not need "

                        "address translation\n");

            }

            return -4;

        }

        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {

            ctx->raddr = eaddr;

            ret = 2;

        } else {

            ret = -2;

        }

    }

    return ret;

}


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

{

    /* Device instance realize function for the GIC sysbus device */

    GICv3State *s = ARM_GICV3(dev);

    ARMGICv3Class *agc = ARM_GICV3_GET_CLASS(s);

    Error *local_err = NULL;

    agc->parent_realize(dev, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    gicv3_init_irqs_and_mmio(s, gicv3_set_irq, NULL);

}


static void build_append_notify_target(GArray *method, GArray *target_name,

                                       uint32_t value, int size)

{

    GArray *notify = build_alloc_array();

    uint8_t op = 0xA0; /* IfOp */

    build_append_byte(notify, 0x93); /* LEqualOp */

    build_append_byte(notify, 0x68); /* Arg0Op */

    build_append_value(notify, value, size);

    build_append_byte(notify, 0x86); /* NotifyOp */

    build_append_array(notify, target_name);

    build_append_byte(notify, 0x69); /* Arg1Op */

    /* Pack it up */

    build_package(notify, op, 1);

    build_append_array(method, notify);

    build_free_array(notify);

}


static void contextidr_write(CPUARMState *env, const ARMCPRegInfo *ri,

                             uint64_t value)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    if (env->cp15.contextidr_el1 != value && !arm_feature(env, ARM_FEATURE_MPU)

        && !extended_addresses_enabled(env)) {

        /* For VMSA (when not using the LPAE long descriptor page table

         * format) this register includes the ASID, so do a TLB flush.

         * For PMSA it is purely a process ID and no action is needed.

         */

        tlb_flush(CPU(cpu), 1);

    }

    env->cp15.contextidr_el1 = value;

}


static ram_addr_t qxl_rom_size(void)

{

    uint32_t required_rom_size = sizeof(QXLRom) + sizeof(QXLModes) +

                                 sizeof(qxl_modes);

    uint32_t rom_size = 8192; /* two pages */

    QEMU_BUILD_BUG_ON(required_rom_size > rom_size);

    return rom_size;

}


static NetSocketState *net_socket_fd_init(NetClientState *peer,

                                          const char *model, const char *name,

                                          int fd, int is_connected)

{

    int so_type = -1, optlen=sizeof(so_type);

    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,

        (socklen_t *)&optlen)< 0) {

        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n",

                fd);

        closesocket(fd);

        return NULL;

    }

    switch(so_type) {

    case SOCK_DGRAM:

        return net_socket_fd_init_dgram(peer, model, name, fd, is_connected);

    case SOCK_STREAM:

        return net_socket_fd_init_stream(peer, model, name, fd, is_connected);

    default:

        /* who knows ... this could be a eg. a pty, do warn and continue as stream */

        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);

        return net_socket_fd_init_stream(peer, model, name, fd, is_connected);

    }

    return NULL;

}


static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,

                               BdrvCheckMode fix, uint16_t **refcount_table,

                               int64_t *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t i;

    QCowSnapshot *sn;

    int ret;

    if (!*refcount_table) {

        *refcount_table = g_try_new0(uint16_t, *nb_clusters);

        if (*nb_clusters && *refcount_table == NULL) {

            res->check_errors++;

            return -ENOMEM;

        }

    }

    /* header */

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        0, s->cluster_size);

    if (ret < 0) {

        return ret;

    }

    /* current L1 table */

    ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                             s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);

    if (ret < 0) {

        return ret;

    }

    /* snapshots */

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

        sn = s->snapshots + i;

        ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                                 sn->l1_table_offset, sn->l1_size, 0);

        if (ret < 0) {

            return ret;

        }

    }

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        s->snapshots_offset, s->snapshots_size);

    if (ret < 0) {

        return ret;

    }

    /* refcount data */

    ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                        s->refcount_table_offset,

                        s->refcount_table_size * sizeof(uint64_t));

    if (ret < 0) {

        return ret;

    }

    return check_refblocks(bs, res, fix, refcount_table, nb_clusters);

}


long check_dcbzl_effect(void)

{

  register char *fakedata = (char*)av_malloc(1024);

  register char *fakedata_middle;

  register long zero = 0;

  register long i = 0;

  long count = 0;

  if (!fakedata)

  {

    return 0L;

  }

  fakedata_middle = (fakedata + 512);

  memset(fakedata, 0xFF, 1024);

  /* below the constraint "b" seems to mean "Address base register"

     in gcc-3.3 / RS/6000 speaks. seems to avoid using r0, so.... */

  asm volatile("dcbzl %0, %1" : : "b" (fakedata_middle), "r" (zero));

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

  {

    if (fakedata[i] == (char)0)

      count++;

  }

  av_free(fakedata);

  return count;

}


static void vga_update_display(void *opaque)

{

    VGACommonState *s = opaque;

    int full_update, graphic_mode;

    qemu_flush_coalesced_mmio_buffer();

    if (ds_get_bits_per_pixel(s->ds) == 0) {

        /* nothing to do */

    } else {

        full_update = 0;

        if (!(s->ar_index & 0x20)) {

            graphic_mode = GMODE_BLANK;

        } else {

            graphic_mode = s->gr[VGA_GFX_MISC] & VGA_GR06_GRAPHICS_MODE;

        }

        if (graphic_mode != s->graphic_mode) {

            s->graphic_mode = graphic_mode;

            s->cursor_blink_time = qemu_get_clock_ms(vm_clock);

            full_update = 1;

        }

        switch(graphic_mode) {

        case GMODE_TEXT:

            vga_draw_text(s, full_update);

            break;

        case GMODE_GRAPH:

            vga_draw_graphic(s, full_update);

            break;

        case GMODE_BLANK:

        default:

            vga_draw_blank(s, full_update);

            break;

        }

    }

}


static inline void comp_block(MadContext *t, int mb_x, int mb_y,

                              int j, int mv_x, int mv_y, int add)

{

    MpegEncContext *s = &t->s;

    if (j < 4) {

        comp(t->frame.data[0] + (mb_y*16 + ((j&2)<<2))*t->frame.linesize[0] + mb_x*16 + ((j&1)<<3),

             t->frame.linesize[0],

             t->last_frame.data[0] + (mb_y*16 + ((j&2)<<2) + mv_y)*t->last_frame.linesize[0] + mb_x*16 + ((j&1)<<3) + mv_x,

             t->last_frame.linesize[0], add);

    } else if (!(s->avctx->flags & CODEC_FLAG_GRAY)) {

        int index = j - 3;

        comp(t->frame.data[index] + (mb_y*8)*t->frame.linesize[index] + mb_x * 8,

             t->frame.linesize[index],

             t->last_frame.data[index] + (mb_y * 8 + (mv_y/2))*t->last_frame.linesize[index] + mb_x * 8 + (mv_x/2),

             t->last_frame.linesize[index], add);

    }

}


static inline int gen_intermediate_code_internal(CPUState *env,
                                                 TranslationBlock *tb,
                                                 int search_pc)
{
    DisasContext dc1, *dc = &dc1;
    uint16_t *gen_opc_end;
    int j, lj;
    target_ulong pc_start;
    uint32_t next_page_start;
    /* generate intermediate code */
    pc_start = tb->pc;
    dc->tb = tb;
    gen_opc_ptr = gen_opc_buf;
    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;
    gen_opparam_ptr = gen_opparam_buf;
    dc->is_jmp = DISAS_NEXT;
    dc->pc = pc_start;
    dc->singlestep_enabled = env->singlestep_enabled;
    dc->condjmp = 0;
    dc->thumb = env->thumb;
    dc->is_mem = 0;
#if !defined(CONFIG_USER_ONLY)
    dc->user = (env->uncached_cpsr & 0x1f) == ARM_CPU_MODE_USR;
#endif
    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;
    nb_gen_labels = 0;
    lj = -1;
    do {
        if (env->nb_breakpoints > 0) {
            for(j = 0; j < env->nb_breakpoints; j++) {
                if (env->breakpoints[j] == dc->pc) {
                    gen_op_movl_T0_im((long)dc->pc);
                    gen_op_movl_reg_TN[0][15]();
                    gen_op_debug();
                    dc->is_jmp = DISAS_JUMP;
                }
            }
        }
        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_instr_start[lj] = 1;
        }
        if (env->thumb)
          disas_thumb_insn(dc);
        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 enoutered.
         * Otherwise the subsequent code could get translated several times.
         * Also stop translation when a page boundary is reached.  This
         * ensures prefech aborts occur at the right place.  */
    } while (!dc->is_jmp && gen_opc_ptr < gen_opc_end &&
             !env->singlestep_enabled &&
             dc->pc < next_page_start);
    /* At this stage dc->condjmp will only be set when the skipped
     * instruction was a conditional branch, and the PC has already been
     * written.  */
    if (__builtin_expect(env->singlestep_enabled, 0)) {
        /* Make sure the pc is updated, and raise a debug exception.  */
        if (dc->condjmp) {
            gen_op_debug();
            gen_set_label(dc->condlabel);
        }
        if (dc->condjmp || !dc->is_jmp) {
            gen_op_movl_T0_im((long)dc->pc);
            gen_op_movl_reg_TN[0][15]();
            dc->condjmp = 0;
        }
        gen_op_debug();
    } else {
        switch(dc->is_jmp) {
        case DISAS_NEXT:
            gen_goto_tb(dc, 1, dc->pc);
        default:
        case DISAS_JUMP:
        case DISAS_UPDATE:
            /* indicate that the hash table must be used to find the next TB */
            gen_op_movl_T0_0();
            gen_op_exit_tb();
        case DISAS_TB_JUMP:
            /* nothing more to generate */
        }
        if (dc->condjmp) {
            gen_set_label(dc->condlabel);
            gen_goto_tb(dc, 1, dc->pc);
            dc->condjmp = 0;
        }
    }
    *gen_opc_ptr = INDEX_op_end;
#ifdef DEBUG_DISAS
    if (loglevel & CPU_LOG_TB_IN_ASM) {
        fprintf(logfile, "----------------\n");
        fprintf(logfile, "IN: %s\n", lookup_symbol(pc_start));
        target_disas(logfile, pc_start, dc->pc - pc_start, env->thumb);
        fprintf(logfile, "\n");
        if (loglevel & (CPU_LOG_TB_OP)) {
            fprintf(logfile, "OP:\n");
            dump_ops(gen_opc_buf, gen_opparam_buf);
            fprintf(logfile, "\n");
        }
    }
#endif
    if (search_pc) {
        j = gen_opc_ptr - gen_opc_buf;
        lj++;
        while (lj <= j)
            gen_opc_instr_start[lj++] = 0;
        tb->size = 0;
    } else {
        tb->size = dc->pc - pc_start;
    }
    return 0;
}


static always_inline void gen_op_arith_subf(DisasContext *ctx, TCGv ret, TCGv arg1, TCGv arg2,

                                            int add_ca, int compute_ca, int compute_ov)

{

    TCGv t0, t1;

    if ((!compute_ca && !compute_ov) ||

        (!TCGV_EQUAL(ret, arg1) && !TCGV_EQUAL(ret, arg2)))  {

        t0 = ret;

        t0 = tcg_temp_local_new();

    }

    if (add_ca) {

        t1 = tcg_temp_local_new();

        tcg_gen_andi_tl(t1, cpu_xer, (1 << XER_CA));

        tcg_gen_shri_tl(t1, t1, XER_CA);

    }

    if (compute_ca && compute_ov) {

        /* Start with XER CA and OV disabled, the most likely case */

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~((1 << XER_CA) | (1 << XER_OV)));

    } else if (compute_ca) {

        /* Start with XER CA disabled, the most likely case */

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~(1 << XER_CA));

    } else if (compute_ov) {

        /* Start with XER OV disabled, the most likely case */

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~(1 << XER_OV));

    }

    if (add_ca) {

        tcg_gen_not_tl(t0, arg1);

        tcg_gen_add_tl(t0, t0, arg2);

        gen_op_arith_compute_ca(ctx, t0, arg2, 0);

        tcg_gen_add_tl(t0, t0, t1);

        gen_op_arith_compute_ca(ctx, t0, t1, 0);

        tcg_temp_free(t1);

        tcg_gen_sub_tl(t0, arg2, arg1);

        if (compute_ca) {

            gen_op_arith_compute_ca(ctx, t0, arg2, 1);

        }

    }

    if (compute_ov) {

        gen_op_arith_compute_ov(ctx, t0, arg1, arg2, 1);

    }

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

        gen_set_Rc0(ctx, t0);

    if (!TCGV_EQUAL(t0, ret)) {

        tcg_gen_mov_tl(ret, t0);

        tcg_temp_free(t0);

    }

}


static uint64_t imx_ccm_read(void *opaque, target_phys_addr_t offset,

                                unsigned size)

{

    IMXCCMState *s = (IMXCCMState *)opaque;

    DPRINTF("read(offset=%x)", offset >> 2);

    switch (offset >> 2) {

    case 0: /* CCMR */

        DPRINTF(" ccmr = 0x%x\n", s->ccmr);

        return s->ccmr;

    case 1:

        DPRINTF(" pdr0 = 0x%x\n", s->pdr0);

        return s->pdr0;

    case 2:

        DPRINTF(" pdr1 = 0x%x\n", s->pdr1);

        return s->pdr1;

    case 4:

        DPRINTF(" mpctl = 0x%x\n", s->mpctl);

        return s->mpctl;

    case 6:

        DPRINTF(" spctl = 0x%x\n", s->spctl);

        return s->spctl;

    case 8:

        DPRINTF(" cgr0 = 0x%x\n", s->cgr[0]);

        return s->cgr[0];

    case 9:

        DPRINTF(" cgr1 = 0x%x\n", s->cgr[1]);

        return s->cgr[1];

    case 10:

        DPRINTF(" cgr2 = 0x%x\n", s->cgr[2]);

        return s->cgr[2];

    case 18: /* LTR1 */

        return 0x00004040;

    case 23:

        DPRINTF(" pcmr0 = 0x%x\n", s->pmcr0);

        return s->pmcr0;

    }

    DPRINTF(" return 0\n");

    return 0;

}


static void ne2000_receive(void *opaque, const uint8_t *buf, size_t size)

{

    NE2000State *s = opaque;

    uint8_t *p;

    unsigned int total_len, next, avail, len, index, mcast_idx;

    uint8_t buf1[60];

    static const uint8_t broadcast_macaddr[6] =

        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

#if defined(DEBUG_NE2000)

    printf("NE2000: received len=%d\n", size);

#endif

    if (s->cmd & E8390_STOP || ne2000_buffer_full(s))

        return;

    /* XXX: check this */

    if (s->rxcr & 0x10) {

        /* promiscuous: receive all */

    } else {

        if (!memcmp(buf,  broadcast_macaddr, 6)) {

            /* broadcast address */

            if (!(s->rxcr & 0x04))

                return;

        } else if (buf[0] & 0x01) {

            /* multicast */

            if (!(s->rxcr & 0x08))

                return;

            mcast_idx = compute_mcast_idx(buf);

            if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))))

                return;

        } else if (s->mem[0] == buf[0] &&

                   s->mem[2] == buf[1] &&

                   s->mem[4] == buf[2] &&

                   s->mem[6] == buf[3] &&

                   s->mem[8] == buf[4] &&

                   s->mem[10] == buf[5]) {

            /* match */

        } else {

            return;

        }

    }

    /* if too small buffer, then expand it */

    if (size < MIN_BUF_SIZE) {

        memcpy(buf1, buf, size);

        memset(buf1 + size, 0, MIN_BUF_SIZE - size);

        buf = buf1;

        size = MIN_BUF_SIZE;

    }

    index = s->curpag << 8;

    /* 4 bytes for header */

    total_len = size + 4;

    /* address for next packet (4 bytes for CRC) */

    next = index + ((total_len + 4 + 255) & ~0xff);

    if (next >= s->stop)

        next -= (s->stop - s->start);

    /* prepare packet header */

    p = s->mem + index;

    s->rsr = ENRSR_RXOK; /* receive status */

    /* XXX: check this */

    if (buf[0] & 0x01)

        s->rsr |= ENRSR_PHY;

    p[0] = s->rsr;

    p[1] = next >> 8;

    p[2] = total_len;

    p[3] = total_len >> 8;

    index += 4;

    /* write packet data */

    while (size > 0) {

        if (index <= s->stop)

            avail = s->stop - index;

        else

            avail = 0;

        len = size;

        if (len > avail)

            len = avail;

        memcpy(s->mem + index, buf, len);

        buf += len;

        index += len;

        if (index == s->stop)

            index = s->start;

        size -= len;

    }

    s->curpag = next >> 8;

    /* now we can signal we have received something */

    s->isr |= ENISR_RX;

    ne2000_update_irq(s);

}


int kvm_init(void)

{

    static const char upgrade_note[] =

        "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"

        "(see http://sourceforge.net/projects/kvm).\n";

    KVMState *s;

    const KVMCapabilityInfo *missing_cap;

    int ret;

    int i;

    int max_vcpus;

    s = g_malloc0(sizeof(KVMState));

    /*

     * On systems where the kernel can support different base page

     * sizes, host page size may be different from TARGET_PAGE_SIZE,

     * even with KVM.  TARGET_PAGE_SIZE is assumed to be the minimum

     * page size for the system though.

     */

    assert(TARGET_PAGE_SIZE <= getpagesize());

#ifdef KVM_CAP_SET_GUEST_DEBUG

    QTAILQ_INIT(&s->kvm_sw_breakpoints);

#endif

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

        s->slots[i].slot = i;

    }

    s->vmfd = -1;

    s->fd = qemu_open("/dev/kvm", O_RDWR);

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

        fprintf(stderr, "Could not access KVM kernel module: %m\n");

        ret = -errno;

        goto err;

    }

    ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);

    if (ret < KVM_API_VERSION) {

        if (ret > 0) {

            ret = -EINVAL;

        }

        fprintf(stderr, "kvm version too old\n");

        goto err;

    }

    if (ret > KVM_API_VERSION) {

        ret = -EINVAL;

        fprintf(stderr, "kvm version not supported\n");

        goto err;

    }

    max_vcpus = kvm_max_vcpus(s);

    if (smp_cpus > max_vcpus) {

        ret = -EINVAL;

        fprintf(stderr, "Number of SMP cpus requested (%d) exceeds max cpus "

                "supported by KVM (%d)\n", smp_cpus, max_vcpus);

        goto err;

    }

    if (max_cpus > max_vcpus) {

        ret = -EINVAL;

        fprintf(stderr, "Number of hotpluggable cpus requested (%d) exceeds max cpus "

                "supported by KVM (%d)\n", max_cpus, max_vcpus);

        goto err;

    }

    s->vmfd = kvm_ioctl(s, KVM_CREATE_VM, 0);

    if (s->vmfd < 0) {

#ifdef TARGET_S390X

        fprintf(stderr, "Please add the 'switch_amode' kernel parameter to "

                        "your host kernel command line\n");

#endif

        ret = s->vmfd;

        goto err;

    }

    missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);

    if (!missing_cap) {

        missing_cap =

            kvm_check_extension_list(s, kvm_arch_required_capabilities);

    }

    if (missing_cap) {

        ret = -EINVAL;

        fprintf(stderr, "kvm does not support %s\n%s",

                missing_cap->name, upgrade_note);

        goto err;

    }

    s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);

    s->broken_set_mem_region = 1;

    ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);

    if (ret > 0) {

        s->broken_set_mem_region = 0;

    }

#ifdef KVM_CAP_VCPU_EVENTS

    s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);

#endif

    s->robust_singlestep =

        kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);

#ifdef KVM_CAP_DEBUGREGS

    s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);

#endif

#ifdef KVM_CAP_XSAVE

    s->xsave = kvm_check_extension(s, KVM_CAP_XSAVE);

#endif

#ifdef KVM_CAP_XCRS

    s->xcrs = kvm_check_extension(s, KVM_CAP_XCRS);

#endif

#ifdef KVM_CAP_PIT_STATE2

    s->pit_state2 = kvm_check_extension(s, KVM_CAP_PIT_STATE2);

#endif

#ifdef KVM_CAP_IRQ_ROUTING

    s->direct_msi = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);

#endif

    s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);

    s->irq_set_ioctl = KVM_IRQ_LINE;

    if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {

        s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;

    }

#ifdef KVM_CAP_READONLY_MEM

    kvm_readonly_mem_allowed =

        (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);

#endif

    ret = kvm_arch_init(s);

    if (ret < 0) {

        goto err;

    }

    ret = kvm_irqchip_create(s);

    if (ret < 0) {

        goto err;

    }

    kvm_state = s;

    memory_listener_register(&kvm_memory_listener, &address_space_memory);

    memory_listener_register(&kvm_io_listener, &address_space_io);

    s->many_ioeventfds = kvm_check_many_ioeventfds();

    cpu_interrupt_handler = kvm_handle_interrupt;

    return 0;

err:

    if (s->vmfd >= 0) {

        close(s->vmfd);

    }

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

        close(s->fd);

    }

    g_free(s);

    return ret;

}


static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,

                         AVIOInterruptCB *int_cb)

{

    /* try relative path, we do not try the absolute because it can leak information about our

       system to an attacker */

    if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {

        char filename[1024];

        char *src_path;

        int i, l;

        /* find a source dir */

        src_path = strrchr(src, '/');

        if (src_path)

            src_path++;

        else

            src_path = src;

        /* find a next level down to target */

        for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)

            if (ref->path[l] == '/') {

                if (i == ref->nlvl_to - 1)

                    break;

                else

                    i++;

            }

        /* compose filename if next level down to target was found */

        if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {

            memcpy(filename, src, src_path - src);

            filename[src_path - src] = 0;

            for (i = 1; i < ref->nlvl_from; i++)

                av_strlcat(filename, "../", 1024);

            av_strlcat(filename, ref->path + l + 1, 1024);

            if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))

                return 0;

        }

    }

    return AVERROR(ENOENT);

}


static int mmu_translate_asce(CPUS390XState *env, target_ulong vaddr,

                              uint64_t asc, uint64_t asce, int level,

                              target_ulong *raddr, int *flags, int rw)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    uint64_t offs = 0;

    uint64_t origin;

    uint64_t new_asce;

    PTE_DPRINTF("%s: 0x%" PRIx64 "\n", __func__, asce);

    if (((level != _ASCE_TYPE_SEGMENT) && (asce & _REGION_ENTRY_INV)) ||

        ((level == _ASCE_TYPE_SEGMENT) && (asce & _SEGMENT_ENTRY_INV))) {

        /* XXX different regions have different faults */

        DPRINTF("%s: invalid region\n", __func__);

        trigger_page_fault(env, vaddr, PGM_SEGMENT_TRANS, asc, rw);

        return -1;

    }

    if ((level <= _ASCE_TYPE_MASK) && ((asce & _ASCE_TYPE_MASK) != level)) {

        trigger_page_fault(env, vaddr, PGM_TRANS_SPEC, asc, rw);

        return -1;

    }

    if (asce & _ASCE_REAL_SPACE) {

        /* direct mapping */

        *raddr = vaddr;

        return 0;

    }

    origin = asce & _ASCE_ORIGIN;

    switch (level) {

    case _ASCE_TYPE_REGION1 + 4:

        offs = (vaddr >> 50) & 0x3ff8;

        break;

    case _ASCE_TYPE_REGION1:

        offs = (vaddr >> 39) & 0x3ff8;

        break;

    case _ASCE_TYPE_REGION2:

        offs = (vaddr >> 28) & 0x3ff8;

        break;

    case _ASCE_TYPE_REGION3:

        offs = (vaddr >> 17) & 0x3ff8;

        break;

    case _ASCE_TYPE_SEGMENT:

        offs = (vaddr >> 9) & 0x07f8;

        origin = asce & _SEGMENT_ENTRY_ORIGIN;

        break;

    }

    /* XXX region protection flags */

    /* *flags &= ~PAGE_WRITE */

    new_asce = ldq_phys(cs->as, origin + offs);

    PTE_DPRINTF("%s: 0x%" PRIx64 " + 0x%" PRIx64 " => 0x%016" PRIx64 "\n",

                __func__, origin, offs, new_asce);

    if (level == _ASCE_TYPE_SEGMENT) {

        /* 4KB page */

        return mmu_translate_pte(env, vaddr, asc, new_asce, raddr, flags, rw);

    } else if (level - 4 == _ASCE_TYPE_SEGMENT &&

               (new_asce & _SEGMENT_ENTRY_FC) && (env->cregs[0] & CR0_EDAT)) {

        /* 1MB page */

        return mmu_translate_sfaa(env, vaddr, asc, new_asce, raddr, flags, rw);

    } else {

        /* yet another region */

        return mmu_translate_asce(env, vaddr, asc, new_asce, level - 4, raddr,

                                  flags, rw);

    }

}


bool iommu_dma_memory_valid(DMAContext *dma, dma_addr_t addr, dma_addr_t len,

                            DMADirection dir)

{

    target_phys_addr_t paddr, plen;

#ifdef DEBUG_IOMMU

    fprintf(stderr, "dma_memory_check context=%p addr=0x" DMA_ADDR_FMT

            " len=0x" DMA_ADDR_FMT " dir=%d\n", dma, addr, len, dir);

#endif

    while (len) {

        if (dma->translate(dma, addr, &paddr, &plen, dir) != 0) {

            return false;

        }

        /* The translation might be valid for larger regions. */

        if (plen > len) {

            plen = len;

        }

        len -= plen;

        addr += plen;

    }

    return true;

}


static void tm_put(QEMUFile *f, struct tm *tm) {

    qemu_put_be16(f, tm->tm_sec);

    qemu_put_be16(f, tm->tm_min);

    qemu_put_be16(f, tm->tm_hour);

    qemu_put_be16(f, tm->tm_mday);

    qemu_put_be16(f, tm->tm_min);

    qemu_put_be16(f, tm->tm_year);

}


uint64_t helper_fsqrt(CPUPPCState *env, uint64_t arg)

{

    CPU_DoubleU farg;

    farg.ll = arg;

    if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {

        /* Square root of a negative nonzero number */

        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSQRT);

    } else {

        if (unlikely(float64_is_signaling_nan(farg.d))) {

            /* sNaN square root */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

        }

        farg.d = float64_sqrt(farg.d, &env->fp_status);

    }

    return farg.ll;

}


static int kvm_handle_internal_error(CPUState *env, struct kvm_run *run)

{

    fprintf(stderr, "KVM internal error.");

    if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {

        int i;

        fprintf(stderr, " Suberror: %d\n", run->internal.suberror);

        for (i = 0; i < run->internal.ndata; ++i) {

            fprintf(stderr, "extra data[%d]: %"PRIx64"\n",

                    i, (uint64_t)run->internal.data[i]);

        }

    } else {

        fprintf(stderr, "\n");

    }

    if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {

        fprintf(stderr, "emulation failure\n");

        if (!kvm_arch_stop_on_emulation_error(env)) {

            cpu_dump_state(env, stderr, fprintf, CPU_DUMP_CODE);

            return 0;

        }

    }

    /* FIXME: Should trigger a qmp message to let management know

     * something went wrong.

     */

    return -1;

}


int virtio_get_block_size(void)

{

    return blk_cfg.blk_size;

}


void tlb_fill(target_ulong addr, int is_write, int mmu_idx, void *retaddr)

{

    tlb_set_page(cpu_single_env,

            addr & ~(TARGET_PAGE_SIZE - 1),

            addr & ~(TARGET_PAGE_SIZE - 1),

            PAGE_READ | PAGE_WRITE | PAGE_EXEC,

            mmu_idx, TARGET_PAGE_SIZE);

}


pp_context_t *pp_get_context(int width, int height, int cpuCaps){

	PPContext *c= memalign(32, sizeof(PPContext));

	int i;

	int stride= (width+15)&(~15); //assumed / will realloc if needed

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

	c->cpuCaps= cpuCaps;

	if(cpuCaps&PP_FORMAT){

		c->hChromaSubSample= cpuCaps&0x3;

		c->vChromaSubSample= (cpuCaps>>4)&0x3;

	}else{

		c->hChromaSubSample= 1;

		c->vChromaSubSample= 1;

	}

	reallocBuffers(c, width, height, stride);

	c->frameNum=-1;

	return c;

}


static gboolean gd_leave_event(GtkWidget *widget, GdkEventCrossing *crossing,

                               gpointer opaque)

{

    VirtualConsole *vc = opaque;

    GtkDisplayState *s = vc->s;

    if (!gd_is_grab_active(s) && gd_grab_on_hover(s)) {

        gd_ungrab_keyboard(s);

    }

    return TRUE;

}


static void vty_receive(void *opaque, const uint8_t *buf, int size)

{

    VIOsPAPRVTYDevice *dev = (VIOsPAPRVTYDevice *)opaque;

    int i;

    if ((dev->in == dev->out) && size) {

        /* toggle line to simulate edge interrupt */

        qemu_irq_pulse(dev->sdev.qirq);

    }

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

        assert((dev->in - dev->out) < VTERM_BUFSIZE);

        dev->buf[dev->in++ % VTERM_BUFSIZE] = buf[i];

    }

}


int kvm_arch_process_async_events(CPUState *env)

{

    return 0;

}


static void coroutine_fn stream_run(void *opaque)

{

    StreamBlockJob *s = opaque;

    StreamCompleteData *data;

    BlockBackend *blk = s->common.blk;

    BlockDriverState *bs = blk_bs(blk);

    BlockDriverState *base = s->base;

    int64_t sector_num = 0;

    int64_t end = -1;

    uint64_t delay_ns = 0;

    int error = 0;

    int ret = 0;

    int n = 0;

    void *buf;

    if (!bs->backing) {

        goto out;

    }

    s->common.len = bdrv_getlength(bs);

    if (s->common.len < 0) {

        ret = s->common.len;

        goto out;

    }

    end = s->common.len >> BDRV_SECTOR_BITS;

    buf = qemu_blockalign(bs, STREAM_BUFFER_SIZE);

    /* Turn on copy-on-read for the whole block device so that guest read

     * requests help us make progress.  Only do this when copying the entire

     * backing chain since the copy-on-read operation does not take base into

     * account.

     */

    if (!base) {

        bdrv_enable_copy_on_read(bs);

    }

    for (sector_num = 0; sector_num < end; sector_num += n) {

        bool copy;

        /* Note that even when no rate limit is applied we need to yield

         * with no pending I/O here so that bdrv_drain_all() returns.

         */

        block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);

        if (block_job_is_cancelled(&s->common)) {

            break;

        }

        copy = false;

        ret = bdrv_is_allocated(bs, sector_num,

                                STREAM_BUFFER_SIZE / BDRV_SECTOR_SIZE, &n);

        if (ret == 1) {

            /* Allocated in the top, no need to copy.  */

        } else if (ret >= 0) {

            /* Copy if allocated in the intermediate images.  Limit to the

             * known-unallocated area [sector_num, sector_num+n).  */

            ret = bdrv_is_allocated_above(backing_bs(bs), base,

                                          sector_num, n, &n);

            /* Finish early if end of backing file has been reached */

            if (ret == 0 && n == 0) {

                n = end - sector_num;

            }

            copy = (ret == 1);

        }

        trace_stream_one_iteration(s, sector_num * BDRV_SECTOR_SIZE,

                                   n * BDRV_SECTOR_SIZE, ret);

        if (copy) {

            ret = stream_populate(blk, sector_num * BDRV_SECTOR_SIZE,

                                  n * BDRV_SECTOR_SIZE, buf);

        }

        if (ret < 0) {

            BlockErrorAction action =

                block_job_error_action(&s->common, s->on_error, true, -ret);

            if (action == BLOCK_ERROR_ACTION_STOP) {

                n = 0;

                continue;

            }

            if (error == 0) {

                error = ret;

            }

            if (action == BLOCK_ERROR_ACTION_REPORT) {

                break;

            }

        }

        ret = 0;

        /* Publish progress */

        s->common.offset += n * BDRV_SECTOR_SIZE;

        if (copy && s->common.speed) {

            delay_ns = ratelimit_calculate_delay(&s->limit,

                                                 n * BDRV_SECTOR_SIZE);

        }

    }

    if (!base) {

        bdrv_disable_copy_on_read(bs);

    }

    /* Do not remove the backing file if an error was there but ignored.  */

    ret = error;

    qemu_vfree(buf);

out:

    /* Modify backing chain and close BDSes in main loop */

    data = g_malloc(sizeof(*data));

    data->ret = ret;

    block_job_defer_to_main_loop(&s->common, stream_complete, data);

}


static void palmte_onoff_gpios(void *opaque, int line, int level)

{

    switch (line) {

    case 0:

        printf("%s: current to MMC/SD card %sabled.\n",

                        __FUNCTION__, level ? "dis" : "en");

        break;

    case 1:

        printf("%s: internal speaker amplifier %s.\n",

                        __FUNCTION__, level ? "down" : "on");

        break;

    /* These LCD & Audio output signals have not been identified yet.  */

    case 2:

    case 3:

    case 4:

        printf("%s: LCD GPIO%i %s.\n",

                        __FUNCTION__, line - 1, level ? "high" : "low");

        break;

    case 5:

    case 6:

        printf("%s: Audio GPIO%i %s.\n",

                        __FUNCTION__, line - 4, level ? "high" : "low");

        break;

    }

}


static int ppc_hash64_check_prot(int prot, int rwx)

{

    int ret;

    if (rwx == 2) {

        if (prot & PAGE_EXEC) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else if (rwx == 1) {

        if (prot & PAGE_WRITE) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else {

        if (prot & PAGE_READ) {

            ret = 0;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static void exynos4210_pwm_write(void *opaque, target_phys_addr_t offset,

        uint64_t value, unsigned size)

{

    Exynos4210PWMState *s = (Exynos4210PWMState *)opaque;

    int index;

    uint32_t new_val;

    int i;

    switch (offset) {

    case TCFG0: case TCFG1:

        index = (offset - TCFG0) >> 2;

        s->reg_tcfg[index] = value;

        /* update timers frequencies */

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

            exynos4210_pwm_update_freq(s, s->timer[i].id);

        }

        break;

    case TCON:

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

            if ((value & TCON_TIMER_MANUAL_UPD(i)) >

            (s->reg_tcon & TCON_TIMER_MANUAL_UPD(i))) {

                /*

                 * TCNTB and TCMPB are loaded into TCNT and TCMP.

                 * Update timers.

                 */

                /* this will start timer to run, this ok, because

                 * during processing start bit timer will be stopped

                 * if needed */

                ptimer_set_count(s->timer[i].ptimer, s->timer[i].reg_tcntb);

                DPRINTF("set timer %d count to %x\n", i,

                        s->timer[i].reg_tcntb);

            }

            if ((value & TCON_TIMER_START(i)) >

            (s->reg_tcon & TCON_TIMER_START(i))) {

                /* changed to start */

                ptimer_run(s->timer[i].ptimer, 1);

                DPRINTF("run timer %d\n", i);

            }

            if ((value & TCON_TIMER_START(i)) <

                    (s->reg_tcon & TCON_TIMER_START(i))) {

                /* changed to stop */

                ptimer_stop(s->timer[i].ptimer);

                DPRINTF("stop timer %d\n", i);

            }

        }

        s->reg_tcon = value;

        break;

    case TCNTB0: case TCNTB1:

    case TCNTB2: case TCNTB3: case TCNTB4:

        index = (offset - TCNTB0) / 0xC;

        s->timer[index].reg_tcntb = value;

        break;

    case TCMPB0: case TCMPB1:

    case TCMPB2: case TCMPB3:

        index = (offset - TCMPB0) / 0xC;

        s->timer[index].reg_tcmpb = value;

        break;

    case TINT_CSTAT:

        new_val = (s->reg_tint_cstat & 0x3E0) + (0x1F & value);

        new_val &= ~(0x3E0 & value);

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

            if ((new_val & TINT_CSTAT_STATUS(i)) <

                    (s->reg_tint_cstat & TINT_CSTAT_STATUS(i))) {

                qemu_irq_lower(s->timer[i].irq);

            }

        }

        s->reg_tint_cstat = new_val;

        break;

    default:

        fprintf(stderr,

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

                offset);

        break;

    }

}


static void smbios_build_type_1_table(void)

{

    SMBIOS_BUILD_TABLE_PRE(1, 0x100, true); /* required */

    SMBIOS_TABLE_SET_STR(1, manufacturer_str, type1.manufacturer);

    SMBIOS_TABLE_SET_STR(1, product_name_str, type1.product);

    SMBIOS_TABLE_SET_STR(1, version_str, type1.version);

    SMBIOS_TABLE_SET_STR(1, serial_number_str, type1.serial);

    if (qemu_uuid_set) {

        smbios_encode_uuid(&t->uuid, qemu_uuid);

    } else {

        memset(&t->uuid, 0, 16);

    }

    t->wake_up_type = 0x06; /* power switch */

    SMBIOS_TABLE_SET_STR(1, sku_number_str, type1.sku);

    SMBIOS_TABLE_SET_STR(1, family_str, type1.family);

    SMBIOS_BUILD_TABLE_POST;

}


static int rv10_decode_frame(AVCodecContext *avctx,

                             void *data, int *got_frame,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MpegEncContext *s = avctx->priv_data;

    int i;

    AVFrame *pict = data;

    int slice_count;

    const uint8_t *slices_hdr = NULL;

    av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);

    /* no supplementary picture */

    if (buf_size == 0) {

        return 0;

    }

    if(!avctx->slice_count){

        slice_count = (*buf++) + 1;

        buf_size--;

        slices_hdr = buf + 4;

        buf += 8 * slice_count;

        buf_size -= 8 * slice_count;

        if (buf_size <= 0)

            return AVERROR_INVALIDDATA;

    }else

        slice_count = avctx->slice_count;

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

        unsigned offset = get_slice_offset(avctx, slices_hdr, i);

        int size, size2;

        if (offset >= buf_size)

            return AVERROR_INVALIDDATA;

        if(i+1 == slice_count)

            size= buf_size - offset;

        else

            size= get_slice_offset(avctx, slices_hdr, i+1) - offset;

        if(i+2 >= slice_count)

            size2= buf_size - offset;

        else

            size2= get_slice_offset(avctx, slices_hdr, i+2) - offset;

        if (size <= 0 || size2 <= 0 ||

            offset + FFMAX(size, size2) > buf_size)

            return AVERROR_INVALIDDATA;

        if(rv10_decode_packet(avctx, buf+offset, size, size2) > 8*size)

            i++;

    }

    if(s->current_picture_ptr != NULL && s->mb_y>=s->mb_height){

        ff_er_frame_end(s);

        ff_MPV_frame_end(s);

        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {

            *pict = s->current_picture_ptr->f;

        } else if (s->last_picture_ptr != NULL) {

            *pict = s->last_picture_ptr->f;

        }

        if(s->last_picture_ptr || s->low_delay){

            *got_frame = 1;

            ff_print_debug_info(s, pict);

        }

        s->current_picture_ptr= NULL; // so we can detect if frame_end was not called (find some nicer solution...)

    }

    return avpkt->size;

}


int css_do_rchp(uint8_t cssid, uint8_t chpid)

{

    uint8_t real_cssid;

    if (cssid > channel_subsys.max_cssid) {

        return -EINVAL;

    }

    if (channel_subsys.max_cssid == 0) {

        real_cssid = channel_subsys.default_cssid;

    } else {

        real_cssid = cssid;

    }

    if (!channel_subsys.css[real_cssid]) {

        return -EINVAL;

    }

    if (!channel_subsys.css[real_cssid]->chpids[chpid].in_use) {

        return -ENODEV;

    }

    if (!channel_subsys.css[real_cssid]->chpids[chpid].is_virtual) {

        fprintf(stderr,

                "rchp unsupported for non-virtual chpid %x.%02x!\n",

                real_cssid, chpid);

        return -ENODEV;

    }

    /* We don't really use a channel path, so we're done here. */

    css_queue_crw(CRW_RSC_CHP, CRW_ERC_INIT,

                  channel_subsys.max_cssid > 0 ? 1 : 0, chpid);

    if (channel_subsys.max_cssid > 0) {

        css_queue_crw(CRW_RSC_CHP, CRW_ERC_INIT, 0, real_cssid << 8);

    }

    return 0;

}


static void gen_swap_asi(DisasContext *dc, TCGv dst, TCGv src,

                         TCGv addr, int insn)

{

    TCGv_i32 r_asi, r_size, r_sign;

    TCGv_i64 s64, t64 = tcg_temp_new_i64();

    r_asi = gen_get_asi(dc, insn);

    r_size = tcg_const_i32(4);

    r_sign = tcg_const_i32(0);

    gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_size, r_sign);

    tcg_temp_free_i32(r_sign);

    s64 = tcg_temp_new_i64();

    tcg_gen_extu_tl_i64(s64, src);

    gen_helper_st_asi(cpu_env, addr, s64, r_asi, r_size);

    tcg_temp_free_i64(s64);

    tcg_temp_free_i32(r_size);

    tcg_temp_free_i32(r_asi);

    tcg_gen_trunc_i64_tl(dst, t64);

    tcg_temp_free_i64(t64);

}


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

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

                const char *kernel_filename, const char *kernel_cmdline,

                const char *initrd_filename, const char *cpu_model)

{

    spitz_common_init(ram_size, vga_ram_size, ds, kernel_filename,

                kernel_cmdline, initrd_filename, borzoi, 0x33f);

}


static struct addrinfo *inet_parse_connect_opts(QemuOpts *opts, Error **errp)

{

    struct addrinfo ai, *res;

    int rc;

    const char *addr;

    const char *port;

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

    ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_STREAM;

    addr = qemu_opt_get(opts, "host");

    port = qemu_opt_get(opts, "port");

    if (addr == NULL || port == NULL) {

        error_setg(errp, "host and/or port not specified");

        return NULL;

    }

    if (qemu_opt_get_bool(opts, "ipv4", 0)) {

        ai.ai_family = PF_INET;

    }

    if (qemu_opt_get_bool(opts, "ipv6", 0)) {

        ai.ai_family = PF_INET6;

    }

    /* lookup */

    rc = getaddrinfo(addr, port, &ai, &res);

    if (rc != 0) {

        error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,

                   gai_strerror(rc));

        return NULL;

    }

    return res;

}


static int arm_gic_init(SysBusDevice *dev)

{

    /* Device instance init function for the GIC sysbus device */

    int i;

    GICState *s = FROM_SYSBUS(GICState, dev);

    ARMGICClass *agc = ARM_GIC_GET_CLASS(s);

    agc->parent_init(dev);

    gic_init_irqs_and_distributor(s, s->num_irq);

    /* Memory regions for the CPU interfaces (NVIC doesn't have these):

     * a region for "CPU interface for this core", then a region for

     * "CPU interface for core 0", "for core 1", ...

     * NB that the memory region size of 0x100 applies for the 11MPCore

     * and also cores following the GIC v1 spec (ie A9).

     * GIC v2 defines a larger memory region (0x1000) so this will need

     * to be extended when we implement A15.

     */

    memory_region_init_io(&s->cpuiomem[0], &gic_thiscpu_ops, s,

                          "gic_cpu", 0x100);

    for (i = 0; i < NUM_CPU(s); i++) {

        s->backref[i] = s;

        memory_region_init_io(&s->cpuiomem[i+1], &gic_cpu_ops, &s->backref[i],

                              "gic_cpu", 0x100);

    }

    /* Distributor */

    sysbus_init_mmio(dev, &s->iomem);

    /* cpu interfaces (one for "current cpu" plus one per cpu) */

    for (i = 0; i <= NUM_CPU(s); i++) {

        sysbus_init_mmio(dev, &s->cpuiomem[i]);

    }

    return 0;

}


static bool addrrange_intersects(AddrRange r1, AddrRange r2)

{

    return (r1.start >= r2.start && r1.start < r2.start + r2.size)

        || (r2.start >= r1.start && r2.start < r1.start + r1.size);

}


static void network_to_result(RDMARegisterResult *result)

{

    result->rkey = ntohl(result->rkey);

    result->host_addr = ntohll(result->host_addr);

};


static inline void RENAME(bgr24ToY_mmx)(uint8_t *dst, const uint8_t *src, int width, enum PixelFormat srcFormat)

{

    if(srcFormat == PIX_FMT_BGR24) {

        __asm__ volatile(

            "movq  "MANGLE(ff_bgr24toY1Coeff)", %%mm5       \n\t"

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

            :

        );

    } else {

        __asm__ volatile(

            "movq  "MANGLE(ff_rgb24toY1Coeff)", %%mm5       \n\t"

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

            :

        );

    }

    __asm__ volatile(

        "movq  "MANGLE(ff_bgr24toYOffset)", %%mm4   \n\t"

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

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

        "1:                                         \n\t"

        PREFETCH"               64(%0)              \n\t"

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

        "movd                    2(%0), %%mm1       \n\t"

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

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

        "add                       $12, %0          \n\t"

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

        "punpcklbw               %%mm7, %%mm1       \n\t"

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

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

        "pmaddwd                 %%mm5, %%mm0       \n\t"

        "pmaddwd                 %%mm6, %%mm1       \n\t"

        "pmaddwd                 %%mm5, %%mm2       \n\t"

        "pmaddwd                 %%mm6, %%mm3       \n\t"

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

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

        "paddd                   %%mm4, %%mm0       \n\t"

        "paddd                   %%mm4, %%mm2       \n\t"

        "psrad                     $15, %%mm0       \n\t"

        "psrad                     $15, %%mm2       \n\t"

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

        "packuswb                %%mm0, %%mm0       \n\t"

        "movd                %%mm0, (%1, %%"REG_a") \n\t"

        "add                        $4, %%"REG_a"   \n\t"

        " js                        1b              \n\t"

    : "+r" (src)

    : "r" (dst+width), "g" ((x86_reg)-width)

    : "%"REG_a

    );

}


static int xvid_ff_2pass_after(struct xvid_context *ref,

                                xvid_plg_data_t *param) {

    char *log = ref->twopassbuffer;

    const char *frame_types = " ipbs";

    char frame_type;

    /* Quick bounds check */

    if( log == NULL )

        return XVID_ERR_FAIL;

    /* Convert the type given to us into a character */

    if( param->type < 5 && param->type > 0 ) {

        frame_type = frame_types[param->type];

    } else {

        return XVID_ERR_FAIL;

    }

    snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),

        "%c %d %d %d %d %d %d\n",

        frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,

        param->stats.ublks, param->stats.length, param->stats.hlength);

    return 0;

}


int ff_vdpau_common_end_frame(AVCodecContext *avctx, AVFrame *frame,

                              struct vdpau_picture_context *pic_ctx)

{

    VDPAUContext *vdctx = avctx->internal->hwaccel_priv_data;

    AVVDPAUContext *hwctx = avctx->hwaccel_context;

    VdpVideoSurface surf = ff_vdpau_get_surface_id(frame);

    VdpStatus status;

    int val;

    val = ff_vdpau_common_reinit(avctx);

    if (val < 0)

        return val;

#if FF_API_BUFS_VDPAU

FF_DISABLE_DEPRECATION_WARNINGS

    hwctx->info = pic_ctx->info;

    hwctx->bitstream_buffers = pic_ctx->bitstream_buffers;

    hwctx->bitstream_buffers_used = pic_ctx->bitstream_buffers_used;

    hwctx->bitstream_buffers_allocated = pic_ctx->bitstream_buffers_allocated;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (!hwctx->render) {

        status = hwctx->render2(avctx, frame, (void *)&pic_ctx->info,

                                pic_ctx->bitstream_buffers_used, pic_ctx->bitstream_buffers);

    } else

    status = vdctx->render(vdctx->decoder, surf, (void *)&pic_ctx->info,

                           pic_ctx->bitstream_buffers_used,

                           pic_ctx->bitstream_buffers);

    av_freep(&pic_ctx->bitstream_buffers);

#if FF_API_BUFS_VDPAU

FF_DISABLE_DEPRECATION_WARNINGS

    hwctx->bitstream_buffers = NULL;

    hwctx->bitstream_buffers_used = 0;

    hwctx->bitstream_buffers_allocated = 0;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    return vdpau_error(status);

}


static CheckasmFunc *get_func(const char *name, int length)

{

    CheckasmFunc *f, **f_ptr = &state.funcs;

    /* Search the tree for a matching node */

    while ((f = *f_ptr)) {

        int cmp = cmp_func_names(name, f->name);

        if (!cmp)

            return f;

        f_ptr = &f->child[(cmp > 0)];

    }

    /* Allocate and insert a new node into the tree */

    f = *f_ptr = checkasm_malloc(sizeof(CheckasmFunc) + length);

    memcpy(f->name, name, length+1);

    return f;

}


static void unref_picture(H264Context *h, Picture *pic)

{

    int off = offsetof(Picture, tf) + sizeof(pic->tf);

    int i;

    if (!pic->f.data[0])

        return;

    ff_thread_release_buffer(h->avctx, &pic->tf);

    av_buffer_unref(&pic->hwaccel_priv_buf);

    av_buffer_unref(&pic->qscale_table_buf);

    av_buffer_unref(&pic->mb_type_buf);

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

        av_buffer_unref(&pic->motion_val_buf[i]);

        av_buffer_unref(&pic->ref_index_buf[i]);

    }

    memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);

}


void ff_free_parser_state(AVFormatContext *s, AVParserState *state)

{

    int i;

    AVParserStreamState *ss;

    if (!state)

        return;

    for (i = 0; i < state->nb_streams; i++) {

        ss = &state->stream_states[i];

        if (ss->parser)

            av_parser_close(ss->parser);

        av_free_packet(&ss->cur_pkt);

    }

    free_packet_list(state->packet_buffer);

    free_packet_list(state->raw_packet_buffer);

    av_free(state->stream_states);

    av_free(state);

}


static int mjpeg_decode_com(MJpegDecodeContext *s)

{

    /* XXX: verify len field validity */

    int len = get_bits(&s->gb, 16);

    if (len >= 2 && len < 32768) {

	/* XXX: any better upper bound */

	uint8_t *cbuf = av_malloc(len - 1);

	if (cbuf) {

	    int i;

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

		cbuf[i] = get_bits(&s->gb, 8);

	    if (i > 0 && cbuf[i-1] == '\n')

		cbuf[i-1] = 0;

	    else

		cbuf[i] = 0;

            if(s->avctx->debug & FF_DEBUG_PICT_INFO)

                av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);

	    /* buggy avid, it puts EOI only at every 10th frame */

	    if (!strcmp(cbuf, "AVID"))

	    {

		s->buggy_avid = 1;

		//	if (s->first_picture)

		//	    printf("mjpeg: workarounding buggy AVID\n");

	    }

            else if(!strcmp(cbuf, "CS=ITU601")){

                s->cs_itu601= 1;

            }

	    av_free(cbuf);

	}

    }

    return 0;

}


static void xhci_runtime_write(void *ptr, hwaddr reg,

                               uint64_t val, unsigned size)

{

    XHCIState *xhci = ptr;

    int v = (reg - 0x20) / 0x20;

    XHCIInterrupter *intr = &xhci->intr[v];

    trace_usb_xhci_runtime_write(reg, val);

    if (reg < 0x20) {

        trace_usb_xhci_unimplemented("runtime write", reg);

        return;

    switch (reg & 0x1f) {

    case 0x00: /* IMAN */

        if (val & IMAN_IP) {

            intr->iman &= ~IMAN_IP;

        intr->iman &= ~IMAN_IE;

        intr->iman |= val & IMAN_IE;

        if (v == 0) {

            xhci_intx_update(xhci);

        xhci_msix_update(xhci, v);

        break;

    case 0x04: /* IMOD */

        intr->imod = val;

        break;

    case 0x08: /* ERSTSZ */

        intr->erstsz = val & 0xffff;

        break;

    case 0x10: /* ERSTBA low */

        /* XXX NEC driver bug: it doesn't align this to 64 bytes

        intr->erstba_low = val & 0xffffffc0; */

        intr->erstba_low = val & 0xfffffff0;

        break;

    case 0x14: /* ERSTBA high */

        intr->erstba_high = val;

        xhci_er_reset(xhci, v);

        break;

    case 0x18: /* ERDP low */

            intr->erdp_low &= ~ERDP_EHB;

        intr->erdp_low = (val & ~ERDP_EHB) | (intr->erdp_low & ERDP_EHB);

        break;

    case 0x1c: /* ERDP high */

        intr->erdp_high = val;

        xhci_events_update(xhci, v);

        break;

    default:

        trace_usb_xhci_unimplemented("oper write", reg);


static void test_ide_none(void)

{

    char *argv[256];

    setup_common(argv, ARRAY_SIZE(argv));

    qtest_start(g_strjoinv(" ", argv));

    test_cmos();

    qtest_end();

}


int ff_dca_xll_decode_audio(DCAContext *s, AVFrame *frame)

{

    /* FIXME: Decodes only the first frequency band. */

    int seg, chset_i;

    /* Coding parameters for each channel set. */

    struct coding_params {

        int seg_type;

        int rice_code_flag[16];

        int pancAuxABIT[16];

        int pancABIT0[16];  /* Not sure what this is */

        int pancABIT[16];   /* Not sure what this is */

        int nSamplPart0[16];

    } param_state[16];

    GetBitContext *gb = &s->xll_navi.gb;

    int *history;

    /* Layout: First the sample buffer for one segment per channel,

     * followed by history buffers of DCA_XLL_AORDER_MAX samples for

     * each channel. */

    av_fast_malloc(&s->xll_sample_buf, &s->xll_sample_buf_size,

                   (s->xll_smpl_in_seg + DCA_XLL_AORDER_MAX) *

                   s->xll_channels * sizeof(*s->xll_sample_buf));

    if (!s->xll_sample_buf)

        return AVERROR(ENOMEM);

    history = s->xll_sample_buf + s->xll_smpl_in_seg * s->xll_channels;

    for (seg = 0; seg < s->xll_segments; seg++) {

        unsigned in_channel;

        for (chset_i = in_channel = 0; chset_i < s->xll_nch_sets; chset_i++) {

            /* The spec isn't very explicit, but I think the NAVI sizes are in bytes. */

            int end_pos = get_bits_count(gb) +

                          8 * s->xll_navi.chset_size[0][seg][chset_i];

            int i, j;

            struct coding_params *params = &param_state[chset_i];

            /* I think this flag means that we should keep seg_type and

             * other parameters from the previous segment. */

            int use_seg_state_code_param;

            XllChSetSubHeader *chset = &s->xll_chsets[chset_i];

            if (in_channel >= s->avctx->channels)

                /* FIXME: Could go directly to next segment */

                goto next_chset;

            if (s->avctx->sample_rate != chset->sampling_frequency) {

                av_log(s->avctx, AV_LOG_WARNING,

                       "XLL: unexpected chset sample rate %d, expected %d\n",

                       chset->sampling_frequency, s->avctx->sample_rate);

                goto next_chset;

            }

            if (seg != 0)

                use_seg_state_code_param = get_bits(gb, 1);

            else

                use_seg_state_code_param = 0;

            if (!use_seg_state_code_param) {

                int num_param_sets, i;

                unsigned bits4ABIT;

                params->seg_type = get_bits(gb, 1);

                num_param_sets   = params->seg_type ? 1 : chset->channels;

                if (chset->bit_width > 16) {

                    bits4ABIT = 5;

                } else {

                    if (chset->bit_width > 8)

                        bits4ABIT = 4;

                    else

                        bits4ABIT = 3;

                    if (s->xll_nch_sets > 1)

                        bits4ABIT++;

                }

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

                    params->rice_code_flag[i] = get_bits(gb, 1);

                    if (!params->seg_type && params->rice_code_flag[i] && get_bits(gb, 1))

                        params->pancAuxABIT[i] = get_bits(gb, bits4ABIT) + 1;

                    else

                        params->pancAuxABIT[i] = 0;

                }

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

                    if (!seg) {

                        /* Parameters for part 1 */

                        params->pancABIT0[i] = get_bits(gb, bits4ABIT);

                        if (params->rice_code_flag[i] == 0 && params->pancABIT0[i] > 0)

                            /* For linear code */

                            params->pancABIT0[i]++;

                        /* NOTE: In the spec, not indexed by band??? */

                        if (params->seg_type == 0)

                            params->nSamplPart0[i] = chset->adapt_order[0][i];

                        else

                            params->nSamplPart0[i] = chset->adapt_order_max[0];

                    } else

                        params->nSamplPart0[i] = 0;

                    /* Parameters for part 2 */

                    params->pancABIT[i] = get_bits(gb, bits4ABIT);

                    if (params->rice_code_flag[i] == 0 && params->pancABIT[i] > 0)

                        /* For linear code */

                        params->pancABIT[i]++;

                }

            }

            for (i = 0; i < chset->channels; i++) {

                int param_index = params->seg_type ? 0 : i;

                int bits        = params->pancABIT0[param_index];

                int part0       = params->nSamplPart0[param_index];

                int *sample_buf = s->xll_sample_buf +

                                  (in_channel + i) * s->xll_smpl_in_seg;

                if (!params->rice_code_flag[param_index]) {

                    /* Linear code */

                    if (bits)

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

                            sample_buf[j] = get_bits_sm(gb, bits);

                    else

                        memset(sample_buf, 0, part0 * sizeof(sample_buf[0]));

                    /* Second part */

                    bits = params->pancABIT[param_index];

                    if (bits)

                        for (j = part0; j < s->xll_smpl_in_seg; j++)

                            sample_buf[j] = get_bits_sm(gb, bits);

                    else

                        memset(sample_buf + part0, 0,

                               (s->xll_smpl_in_seg - part0) * sizeof(sample_buf[0]));

                } else {

                    int aux_bits = params->pancAuxABIT[param_index];

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

                        /* FIXME: Is this identical to Golomb code? */

                        int t = get_unary(gb, 1, 33) << bits;

                        /* FIXME: Could move this test outside of the loop, for efficiency. */

                        if (bits)

                            t |= get_bits(gb, bits);

                        sample_buf[j] = (t & 1) ? -(t >> 1) - 1 : (t >> 1);

                    }

                    /* Second part */

                    bits = params->pancABIT[param_index];

                    /* Follow the spec's suggestion of using the

                     * buffer also to store the hybrid-rice flags. */

                    memset(sample_buf + part0, 0,

                           (s->xll_smpl_in_seg - part0) * sizeof(sample_buf[0]));

                    if (aux_bits > 0) {

                        /* For hybrid rice encoding, some samples are linearly

                         * coded. According to the spec, "nBits4SamplLoci" bits

                         * are used for each index, but this value is not

                         * defined. I guess we should use log2(xll_smpl_in_seg)

                         * bits. */

                        int count = get_bits(gb, s->xll_log_smpl_in_seg);

                        av_log(s->avctx, AV_LOG_DEBUG, "aux count %d (bits %d)\n",

                               count, s->xll_log_smpl_in_seg);

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

                            sample_buf[get_bits(gb, s->xll_log_smpl_in_seg)] = 1;

                    }

                    for (j = part0; j < s->xll_smpl_in_seg; j++) {

                        if (!sample_buf[j]) {

                            int t = get_unary(gb, 1, 33);

                            if (bits)

                                t = (t << bits) | get_bits(gb, bits);

                            sample_buf[j] = (t & 1) ? -(t >> 1) - 1 : (t >> 1);

                        } else

                            sample_buf[j] = get_bits_sm(gb, aux_bits);

                    }

                }

            }

            for (i = 0; i < chset->channels; i++) {

                unsigned adapt_order = chset->adapt_order[0][i];

                int *sample_buf = s->xll_sample_buf +

                                  (in_channel + i) * s->xll_smpl_in_seg;

                int *prev = history + (in_channel + i) * DCA_XLL_AORDER_MAX;

                if (!adapt_order) {

                    unsigned order;

                    for (order = chset->fixed_order[0][i]; order > 0; order--) {

                        unsigned j;

                        for (j = 1; j < s->xll_smpl_in_seg; j++)

                            sample_buf[j] += sample_buf[j - 1];

                    }

                } else

                    /* Inverse adaptive prediction, in place. */

                    dca_xll_inv_adapt_pred(sample_buf, s->xll_smpl_in_seg,

                                           adapt_order, seg ? prev : NULL,

                                           chset->lpc_refl_coeffs_q_ind[0][i]);

                memcpy(prev, sample_buf + s->xll_smpl_in_seg - DCA_XLL_AORDER_MAX,

                       DCA_XLL_AORDER_MAX * sizeof(*prev));

            }

            for (i = 1; i < chset->channels; i += 2) {

                int coeff = chset->pw_ch_pairs_coeffs[0][i / 2];

                if (coeff != 0) {

                    int *sample_buf = s->xll_sample_buf +

                                      (in_channel + i) * s->xll_smpl_in_seg;

                    int *prev = sample_buf - s->xll_smpl_in_seg;

                    unsigned j;

                    for (j = 0; j < s->xll_smpl_in_seg; j++)

                        /* Shift is unspecified, but should apparently be 3. */

                        sample_buf[j] += ((int64_t) coeff * prev[j] + 4) >> 3;

                }

            }

            if (s->xll_scalable_lsb) {

                int lsb_start = end_pos - 8 * chset->lsb_fsize[0] -

                                8 * (s->xll_banddata_crc & 2);

                int done;

                i = get_bits_count(gb);

                if (i > lsb_start) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "chset data lsb exceeds NAVI size, end_pos %d, lsb_start %d, pos %d\n",

                           end_pos, lsb_start, i);

                    return AVERROR_INVALIDDATA;

                }

                if (i < lsb_start)

                    skip_bits_long(gb, lsb_start - i);

                for (i = done = 0; i < chset->channels; i++) {

                    int bits = chset->scalable_lsbs[0][i];

                    if (bits > 0) {

                        /* The channel reordering is conceptually done

                         * before adding the lsb:s, so we need to do

                         * the inverse permutation here. */

                        unsigned pi = chset->orig_chan_order_inv[0][i];

                        int *sample_buf = s->xll_sample_buf +

                                          (in_channel + pi) * s->xll_smpl_in_seg;

                        int adj = chset->bit_width_adj_per_ch[0][i];

                        int msb_shift = bits;

                        unsigned j;

                        if (adj > 0)

                            msb_shift += adj - 1;

                        for (j = 0; j < s->xll_smpl_in_seg; j++)

                            sample_buf[j] = (sample_buf[j] << msb_shift) +

                                            (get_bits(gb, bits) << adj);

                        done += bits * s->xll_smpl_in_seg;

                    }

                }

                if (done > 8 * chset->lsb_fsize[0]) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "chset lsb exceeds lsb_size\n");

                    return AVERROR_INVALIDDATA;

                }

            }

            /* Store output. */

            for (i = 0; i < chset->channels; i++) {

                int *sample_buf = s->xll_sample_buf +

                                  (in_channel + i) * s->xll_smpl_in_seg;

                int shift = 1 - chset->bit_resolution;

                int out_channel = chset->orig_chan_order[0][i];

                float *out;

                /* XLL uses the channel order C, L, R, and we want L,

                 * R, C. FIXME: Generalize. */

                if (chset->ch_mask_enabled &&

                    (chset->ch_mask & 7) == 7 && out_channel < 3)

                    out_channel = out_channel ? out_channel - 1 : 2;

                out_channel += in_channel;

                if (out_channel >= s->avctx->channels)

                    continue;

                out  = (float *) frame->extended_data[out_channel];

                out += seg * s->xll_smpl_in_seg;

                /* NOTE: A one bit means residual encoding is *not* used. */

                if ((chset->residual_encode >> i) & 1) {

                    /* Replace channel samples.

                     * FIXME: Most likely not the right thing to do. */

                    for (j = 0; j < s->xll_smpl_in_seg; j++)

                        out[j] = ldexpf(sample_buf[j], shift);

                } else {

                    /* Add residual signal to core channel */

                    for (j = 0; j < s->xll_smpl_in_seg; j++)

                        out[j] += ldexpf(sample_buf[j], shift);

                }

            }

            if (chset->downmix_coeff_code_embedded &&

                !chset->primary_ch_set && chset->hier_chset) {

                /* Undo hierarchical downmix of earlier channels. */

                unsigned mix_channel;

                for (mix_channel = 0; mix_channel < in_channel; mix_channel++) {

                    float *mix_buf;

                    const int *col;

                    float coeff;

                    unsigned row;

                    /* Similar channel reorder C, L, R vs L, R, C reorder. */

                    if (chset->ch_mask_enabled &&

                        (chset->ch_mask & 7) == 7 && mix_channel < 3)

                        mix_buf = (float *) frame->extended_data[mix_channel ? mix_channel - 1 : 2];

                    else

                        mix_buf = (float *) frame->extended_data[mix_channel];

                    mix_buf += seg * s->xll_smpl_in_seg;

                    col = &chset->downmix_coeffs[mix_channel * (chset->channels + 1)];

                    /* Scale */

                    coeff = ldexpf(col[0], -16);

                    for (j = 0; j < s->xll_smpl_in_seg; j++)

                        mix_buf[j] *= coeff;

                    for (row = 0;

                         row < chset->channels && in_channel + row < s->avctx->channels;

                         row++)

                        if (col[row + 1]) {

                            const float *new_channel =

                                (const float *) frame->extended_data[in_channel + row];

                            new_channel += seg * s->xll_smpl_in_seg;

                            coeff        = ldexpf(col[row + 1], -15);

                            for (j = 0; j < s->xll_smpl_in_seg; j++)

                                mix_buf[j] -= coeff * new_channel[j];

                        }

                }

            }

next_chset:

            in_channel += chset->channels;

            /* Skip to next channel set using the NAVI info. */

            i = get_bits_count(gb);

            if (i > end_pos) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "chset data exceeds NAVI size\n");

                return AVERROR_INVALIDDATA;

            }

            if (i < end_pos)

                skip_bits_long(gb, end_pos - i);

        }

    }

    return 0;

}


static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,

                        int width, int height, int bandpos, int lev)

{

    int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;

    int64_t wmsedec = 0;

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

        memset(t1->flags[y], 0, (width+2)*sizeof(int));

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

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

            if (t1->data[y][x] < 0){

                t1->flags[y+1][x+1] |= JPEG2000_T1_SGN;

                t1->data[y][x] = -t1->data[y][x];

            }

            max = FFMAX(max, t1->data[y][x]);

        }

    }

    if (max == 0){

        cblk->nonzerobits = 0;

        bpno = 0;

    } else{

        cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;

        bpno = cblk->nonzerobits - 1;

    }

    ff_mqc_initenc(&t1->mqc, cblk->data);

    for (passno = 0; bpno >= 0; passno++){

        nmsedec=0;

        switch(pass_t){

            case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);

                    break;

            case 1: encode_refpass(t1, width, height, &nmsedec, bpno);

                    break;

            case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);

                    break;

        }

        cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);

        wmsedec += (int64_t)nmsedec << (2*bpno);

        cblk->passes[passno].disto = wmsedec;

        if (++pass_t == 3){

            pass_t = 0;

            bpno--;

        }

    }

    cblk->npasses = passno;

    cblk->ninclpasses = passno;

    cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);

}


void cpu_disable_ticks(void)

{

    /* Here, the really thing protected by seqlock is cpu_clock_offset. */

    seqlock_write_lock(&timers_state.vm_clock_seqlock);

    if (timers_state.cpu_ticks_enabled) {

        timers_state.cpu_ticks_offset = cpu_get_ticks();

        timers_state.cpu_clock_offset = cpu_get_clock_locked();

        timers_state.cpu_ticks_enabled = 0;

    }

    seqlock_write_unlock(&timers_state.vm_clock_seqlock);

}


static inline void RENAME(yv12toyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

	unsigned int width, unsigned int height,

	int lumStride, int chromStride, int dstStride)

{

	//FIXME interpolate chroma

	RENAME(yuvPlanartoyuy2)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2);

}


static int decode_residuals(FLACContext *s, int channel, int pred_order)

{

    int i, tmp, partition, method_type, rice_order;

    int sample = 0, samples;

    method_type = get_bits(&s->gb, 2);

    if (method_type > 1) {

        av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",

               method_type);

        return -1;

    }

    rice_order = get_bits(&s->gb, 4);

    samples= s->blocksize >> rice_order;

    if (pred_order > samples) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",

               pred_order, samples);

        return -1;

    }

    sample=

    i= pred_order;

    for (partition = 0; partition < (1 << rice_order); partition++) {

        tmp = get_bits(&s->gb, method_type == 0 ? 4 : 5);

        if (tmp == (method_type == 0 ? 15 : 31)) {

            tmp = get_bits(&s->gb, 5);

            for (; i < samples; i++, sample++)

                s->decoded[channel][sample] = get_sbits_long(&s->gb, tmp);

        } else {

            for (; i < samples; i++, sample++) {

                s->decoded[channel][sample] = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);

            }

        }

        i= 0;

    }

    return 0;

}


static int print_device_sinks(AVOutputFormat *fmt, AVDictionary *opts)

{

    int ret, i;

    AVFormatContext *dev = NULL;

    AVDeviceInfoList *device_list = NULL;

    AVDictionary *tmp_opts = NULL;

    if (!fmt || !fmt->priv_class  || !AV_IS_OUTPUT_DEVICE(fmt->priv_class->category))

        return AVERROR(EINVAL);

    printf("Audo-detected sinks for %s:\n", fmt->name);

    if (!fmt->get_device_list) {

        ret = AVERROR(ENOSYS);

        printf("Cannot list sinks. Not implemented.\n");

        goto fail;

    }

    if ((ret = avformat_alloc_output_context2(&dev, fmt, NULL, NULL)) < 0) {

        printf("Cannot open device: %s.\n", fmt->name);

        goto fail;

    }

    av_dict_copy(&tmp_opts, opts, 0);

    av_opt_set_dict2(dev, &tmp_opts, AV_OPT_SEARCH_CHILDREN);

    if ((ret = avdevice_list_devices(dev, &device_list)) < 0) {

        printf("Cannot list sinks.\n");

        goto fail;

    }

    for (i = 0; i < device_list->nb_devices; i++) {

        printf("%s %s [%s]\n", device_list->default_device == i ? "*" : " ",

               device_list->devices[i]->device_name, device_list->devices[i]->device_description);

    }

  fail:

    av_dict_free(&tmp_opts);

    avdevice_free_list_devices(&device_list);

    avformat_free_context(dev);

    return ret;

}


static int bmp_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    BMPContext *s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame *p = &s->picture;

    unsigned int fsize, hsize;

    int width, height;

    unsigned int depth;

    BiCompression comp;

    unsigned int ihsize;

    int i, j, n, linesize;

    uint32_t rgb[3];

    uint8_t *ptr;

    int dsize;

    uint8_t *buf0 = buf;

    if(buf_size < 14){

        av_log(avctx, AV_LOG_ERROR, "buf size too small (%d)\n", buf_size);

        return -1;

    }

    if(bytestream_get_byte(&buf) != 'B' ||

       bytestream_get_byte(&buf) != 'M') {

        av_log(avctx, AV_LOG_ERROR, "bad magic number\n");

        return -1;

    }

    fsize = bytestream_get_le32(&buf);

    if(buf_size < fsize){

        av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n",

               buf_size, fsize);

        return -1;

    }

    buf += 2; /* reserved1 */

    buf += 2; /* reserved2 */

    hsize = bytestream_get_le32(&buf); /* header size */

    if(fsize <= hsize){

        av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n",

               fsize, hsize);

        return -1;

    }

    ihsize = bytestream_get_le32(&buf);       /* more header size */

    if(ihsize + 14 > hsize){

        av_log(avctx, AV_LOG_ERROR, "invalid header size %d\n", hsize);

        return -1;

    }

    width = bytestream_get_le32(&buf);

    height = bytestream_get_le32(&buf);

    if(bytestream_get_le16(&buf) != 1){ /* planes */

        av_log(avctx, AV_LOG_ERROR, "invalid BMP header\n");

        return -1;

    }

    depth = bytestream_get_le16(&buf);

    if(ihsize > 16)

        comp = bytestream_get_le32(&buf);

    else

        comp = BMP_RGB;

    if(comp != BMP_RGB && comp != BMP_BITFIELDS){

        av_log(avctx, AV_LOG_ERROR, "BMP coding %d not supported\n", comp);

        return -1;

    }

    if(comp == BMP_BITFIELDS){

        buf += 20;

        rgb[0] = bytestream_get_le32(&buf);

        rgb[1] = bytestream_get_le32(&buf);

        rgb[2] = bytestream_get_le32(&buf);

    }

    avctx->codec_id = CODEC_ID_BMP;

    avctx->width = width;

    avctx->height = height > 0? height: -height;

    avctx->pix_fmt = PIX_FMT_NONE;

    switch(depth){

    case 32:

        if(comp == BMP_BITFIELDS){

            rgb[0] = (rgb[0] >> 15) & 3;

            rgb[1] = (rgb[1] >> 15) & 3;

            rgb[2] = (rgb[2] >> 15) & 3;

            if(rgb[0] + rgb[1] + rgb[2] != 3 ||

               rgb[0] == rgb[1] || rgb[0] == rgb[2] || rgb[1] == rgb[2]){

                break;

            }

        } else {

            rgb[0] = 2;

            rgb[1] = 1;

            rgb[2] = 0;

        }

        avctx->pix_fmt = PIX_FMT_BGR24;

        break;

    case 24:

        avctx->pix_fmt = PIX_FMT_BGR24;

        break;

    case 16:

        if(comp == BMP_RGB)

            avctx->pix_fmt = PIX_FMT_RGB555;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "depth %d not supported\n", depth);

        return -1;

    }

    if(avctx->pix_fmt == PIX_FMT_NONE){

        av_log(avctx, AV_LOG_ERROR, "unsupported pixel format\n");

        return -1;

    }

    if(p->data[0])

        avctx->release_buffer(avctx, p);

    p->reference = 0;

    if(avctx->get_buffer(avctx, p) < 0){

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return -1;

    }

    p->pict_type = FF_I_TYPE;

    p->key_frame = 1;

    buf = buf0 + hsize;

    dsize = buf_size - hsize;

    /* Line size in file multiple of 4 */

    n = (avctx->width * (depth / 8) + 3) & ~3;

    if(n * avctx->height > dsize){

        av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n",

               dsize, n * avctx->height);

        return -1;

    }

    if(height > 0){

        ptr = p->data[0] + (avctx->height - 1) * p->linesize[0];

        linesize = -p->linesize[0];

    } else {

        ptr = p->data[0];

        linesize = p->linesize[0];

    }

    switch(depth){

    case 24:

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

            memcpy(ptr, buf, n);

            buf += n;

            ptr += linesize;

        }

        break;

    case 16:

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

            uint16_t *src = (uint16_t *) buf;

            uint16_t *dst = (uint16_t *) ptr;

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

                *dst++ = le2me_16(*src++);

            buf += n;

            ptr += linesize;

        }

        break;

    case 32:

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

            uint8_t *src = buf;

            uint8_t *dst = ptr;

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

                dst[0] = src[rgb[2]];

                dst[1] = src[rgb[1]];

                dst[2] = src[rgb[0]];

                dst += 3;

                src += 4;

            }

            buf += n;

            ptr += linesize;

        }

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "BMP decoder is broken\n");

        return -1;

    }

    *picture = s->picture;

    *data_size = sizeof(AVPicture);

    return buf_size;

}


void HELPER(stfl)(CPUS390XState *env)

{

    uint64_t words[MAX_STFL_WORDS];

    do_stfle(env, words);

    cpu_stl_data(env, 200, words[0] >> 32);

}


static QDict *qmp_check_input_obj(QObject *input_obj)

{

    const QDictEntry *ent;

    int has_exec_key = 0;

    QDict *input_dict;

    if (qobject_type(input_obj) != QTYPE_QDICT) {

        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");

        return NULL;

    }

    input_dict = qobject_to_qdict(input_obj);

    for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){

        const char *arg_name = qdict_entry_key(ent);

        const QObject *arg_obj = qdict_entry_value(ent);

        if (!strcmp(arg_name, "execute")) {

            if (qobject_type(arg_obj) != QTYPE_QSTRING) {

                qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",

                              "string");

                return NULL;

            }

            has_exec_key = 1;

        } else if (!strcmp(arg_name, "arguments")) {

            if (qobject_type(arg_obj) != QTYPE_QDICT) {

                qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "arguments",

                              "object");

                return NULL;

            }

        } else if (!strcmp(arg_name, "id")) {

            /* FIXME: check duplicated IDs for async commands */

        } else {

            qerror_report(QERR_QMP_EXTRA_MEMBER, arg_name);

            return NULL;

        }

    }

    if (!has_exec_key) {

        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");

        return NULL;

    }

    return input_dict;

}


static void add_pixels_clamped4_c(const DCTELEM *block, uint8_t *restrict pixels,

                          int line_size)

{

    int i;

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    /* read the pixels */

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

        pixels[0] = cm[pixels[0] + block[0]];

        pixels[1] = cm[pixels[1] + block[1]];

        pixels[2] = cm[pixels[2] + block[2]];

        pixels[3] = cm[pixels[3] + block[3]];

        pixels += line_size;

        block += 8;

    }

}


static void msmpeg4_encode_dc(MpegEncContext * s, int level, int n, int *dir_ptr)

{

    int sign, code;

    int pred, extquant;

    int extrabits = 0;

    int16_t *dc_val;

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

    /* update predictor */

    if (n < 4) {

        *dc_val = level * s->y_dc_scale;

    } else {

        *dc_val = level * s->c_dc_scale;

    }

    /* do the prediction */

    level -= pred;

    if(s->msmpeg4_version<=2){

        if (n < 4) {

            put_bits(&s->pb,

                     ff_v2_dc_lum_table[level + 256][1],

                     ff_v2_dc_lum_table[level + 256][0]);

        }else{

            put_bits(&s->pb,

                     ff_v2_dc_chroma_table[level + 256][1],

                     ff_v2_dc_chroma_table[level + 256][0]);

        }

    }else{

        sign = 0;

        if (level < 0) {

            level = -level;

            sign = 1;

        }

        code = level;

        if (code > DC_MAX)

            code = DC_MAX;

        else if( s->msmpeg4_version>=6 ) {

            if( s->qscale == 1 ) {

                extquant = (level + 3) & 0x3;

                code  = ((level+3)>>2);

            } else if( s->qscale == 2 ) {

                extquant = (level + 1) & 0x1;

                code  = ((level+1)>>1);

            }

        }

        if (s->dc_table_index == 0) {

            if (n < 4) {

                put_bits(&s->pb, ff_table0_dc_lum[code][1], ff_table0_dc_lum[code][0]);

            } else {

                put_bits(&s->pb, ff_table0_dc_chroma[code][1], ff_table0_dc_chroma[code][0]);

            }

        } else {

            if (n < 4) {

                put_bits(&s->pb, ff_table1_dc_lum[code][1], ff_table1_dc_lum[code][0]);

            } else {

                put_bits(&s->pb, ff_table1_dc_chroma[code][1], ff_table1_dc_chroma[code][0]);

            }

        }

        if(s->msmpeg4_version>=6 && s->qscale<=2)

            extrabits = 3 - s->qscale;

        if (code == DC_MAX)

            put_bits(&s->pb, 8 + extrabits, level);

        else if(extrabits > 0)//== VC1 && s->qscale<=2

            put_bits(&s->pb, extrabits, extquant);

        if (level != 0) {

            put_bits(&s->pb, 1, sign);

        }

    }

}