static void rocker_io_writel(void *opaque, hwaddr addr, uint32_t val)

{

    Rocker *r = opaque;

    if (rocker_addr_is_desc_reg(r, addr)) {

        unsigned index = ROCKER_RING_INDEX(addr);

        unsigned offset = addr & ROCKER_DMA_DESC_MASK;

        switch (offset) {

        case ROCKER_DMA_DESC_ADDR_OFFSET:

            r->lower32 = (uint64_t)val;

            break;

        case ROCKER_DMA_DESC_ADDR_OFFSET + 4:

            desc_ring_set_base_addr(r->rings[index],

                                    ((uint64_t)val) << 32 | r->lower32);

            r->lower32 = 0;

            break;

        case ROCKER_DMA_DESC_SIZE_OFFSET:

            desc_ring_set_size(r->rings[index], val);

            break;

        case ROCKER_DMA_DESC_HEAD_OFFSET:

            if (desc_ring_set_head(r->rings[index], val)) {

                rocker_msix_irq(r, desc_ring_get_msix_vector(r->rings[index]));

            }

            break;

        case ROCKER_DMA_DESC_CTRL_OFFSET:

            desc_ring_set_ctrl(r->rings[index], val);

            break;

        case ROCKER_DMA_DESC_CREDITS_OFFSET:

            if (desc_ring_ret_credits(r->rings[index], val)) {

                rocker_msix_irq(r, desc_ring_get_msix_vector(r->rings[index]));

            }

            break;

        default:

            DPRINTF("not implemented dma reg write(l) addr=0x" TARGET_FMT_plx

                    " val=0x%08x (ring %d, addr=0x%02x)\n",

                    addr, val, index, offset);

            break;

        }

        return;

    }

    switch (addr) {

    case ROCKER_TEST_REG:

        r->test_reg = val;

        break;

    case ROCKER_TEST_REG64:

    case ROCKER_TEST_DMA_ADDR:

    case ROCKER_PORT_PHYS_ENABLE:

        r->lower32 = (uint64_t)val;

        break;

    case ROCKER_TEST_REG64 + 4:

        r->test_reg64 = ((uint64_t)val) << 32 | r->lower32;

        r->lower32 = 0;

        break;

    case ROCKER_TEST_IRQ:

        rocker_msix_irq(r, val);

        break;

    case ROCKER_TEST_DMA_SIZE:

        r->test_dma_size = val;

        break;

    case ROCKER_TEST_DMA_ADDR + 4:

        r->test_dma_addr = ((uint64_t)val) << 32 | r->lower32;

        r->lower32 = 0;

        break;

    case ROCKER_TEST_DMA_CTRL:

        rocker_test_dma_ctrl(r, val);

        break;

    case ROCKER_CONTROL:

        rocker_control(r, val);

        break;

    case ROCKER_PORT_PHYS_ENABLE + 4:

        rocker_port_phys_enable_write(r, ((uint64_t)val) << 32 | r->lower32);

        r->lower32 = 0;

        break;

    default:

        DPRINTF("not implemented write(l) addr=0x" TARGET_FMT_plx

                " val=0x%08x\n", addr, val);

        break;

    }

}


build_rsdt(GArray *table_data, GArray *linker, GArray *table_offsets)

{

    AcpiRsdtDescriptorRev1 *rsdt;

    size_t rsdt_len;

    int i;

    const int table_data_len = (sizeof(uint32_t) * table_offsets->len);

    rsdt_len = sizeof(*rsdt) + table_data_len;

    rsdt = acpi_data_push(table_data, rsdt_len);

    memcpy(rsdt->table_offset_entry, table_offsets->data, table_data_len);

    for (i = 0; i < table_offsets->len; ++i) {

        /* rsdt->table_offset_entry to be filled by Guest linker */

        bios_linker_loader_add_pointer(linker,

                                       ACPI_BUILD_TABLE_FILE,

                                       ACPI_BUILD_TABLE_FILE,

                                       table_data, &rsdt->table_offset_entry[i],

                                       sizeof(uint32_t));

    }

    build_header(linker, table_data,

                 (void *)rsdt, "RSDT", rsdt_len, 1, NULL, NULL);

}


int nbd_client_session_co_writev(NbdClientSession *client, int64_t sector_num,

                                 int nb_sectors, QEMUIOVector *qiov)

{

    int offset = 0;

    int ret;

    while (nb_sectors > NBD_MAX_SECTORS) {

        ret = nbd_co_writev_1(client, sector_num,

                              NBD_MAX_SECTORS, qiov, offset);

        if (ret < 0) {

            return ret;

        }

        offset += NBD_MAX_SECTORS * 512;

        sector_num += NBD_MAX_SECTORS;

        nb_sectors -= NBD_MAX_SECTORS;

    }

    return nbd_co_writev_1(client, sector_num, nb_sectors, qiov, offset);

}


static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)

{

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

    uint64_t nb_sectors;

    bool dbd;

    int page, buflen, ret, page_control;

    uint8_t *p;

    uint8_t dev_specific_param;

    dbd = (r->req.cmd.buf[1] & 0x8) != 0;

    page = r->req.cmd.buf[2] & 0x3f;

    page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;

    DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",

        (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);

    memset(outbuf, 0, r->req.cmd.xfer);

    p = outbuf;

    if (s->qdev.type == TYPE_DISK) {

        dev_specific_param = s->features & (1 << SCSI_DISK_F_DPOFUA) ? 0x10 : 0;

        if (bdrv_is_read_only(s->qdev.conf.bs)) {

            dev_specific_param |= 0x80; /* Readonly.  */

        }

    } else {

        /* MMC prescribes that CD/DVD drives have no block descriptors,

         * and defines no device-specific parameter.  */

        dev_specific_param = 0x00;

        dbd = true;

    }

    if (r->req.cmd.buf[0] == MODE_SENSE) {

        p[1] = 0; /* Default media type.  */

        p[2] = dev_specific_param;

        p[3] = 0; /* Block descriptor length.  */

        p += 4;

    } else { /* MODE_SENSE_10 */

        p[2] = 0; /* Default media type.  */

        p[3] = dev_specific_param;

        p[6] = p[7] = 0; /* Block descriptor length.  */

        p += 8;

    }

    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

    if (!dbd && nb_sectors) {

        if (r->req.cmd.buf[0] == MODE_SENSE) {

            outbuf[3] = 8; /* Block descriptor length  */

        } else { /* MODE_SENSE_10 */

            outbuf[7] = 8; /* Block descriptor length  */

        }

        nb_sectors /= (s->qdev.blocksize / 512);

        if (nb_sectors > 0xffffff) {

            nb_sectors = 0;

        }

        p[0] = 0; /* media density code */

        p[1] = (nb_sectors >> 16) & 0xff;

        p[2] = (nb_sectors >> 8) & 0xff;

        p[3] = nb_sectors & 0xff;

        p[4] = 0; /* reserved */

        p[5] = 0; /* bytes 5-7 are the sector size in bytes */

        p[6] = s->qdev.blocksize >> 8;

        p[7] = 0;

        p += 8;

    }

    if (page_control == 3) {

        /* Saved Values */

        scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));

        return -1;

    }

    if (page == 0x3f) {

        for (page = 0; page <= 0x3e; page++) {

            mode_sense_page(s, page, &p, page_control);

        }

    } else {

        ret = mode_sense_page(s, page, &p, page_control);

        if (ret == -1) {

            return -1;

        }

    }

    buflen = p - outbuf;

    /*

     * The mode data length field specifies the length in bytes of the

     * following data that is available to be transferred. The mode data

     * length does not include itself.

     */

    if (r->req.cmd.buf[0] == MODE_SENSE) {

        outbuf[0] = buflen - 1;

    } else { /* MODE_SENSE_10 */

        outbuf[0] = ((buflen - 2) >> 8) & 0xff;

        outbuf[1] = (buflen - 2) & 0xff;

    }

    return buflen;

}


static void qemu_chr_parse_pipe(QemuOpts *opts, ChardevBackend *backend,

                                Error **errp)

{

    const char *device = qemu_opt_get(opts, "path");

    ChardevHostdev *dev;

    if (device == NULL) {

        error_setg(errp, "chardev: pipe: no device path given");

        return;

    }

    dev = backend->u.pipe = g_new0(ChardevHostdev, 1);

    qemu_chr_parse_common(opts, qapi_ChardevHostdev_base(dev));

    dev->device = g_strdup(device);

}


static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

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

    MOVStreamContext *sc = st->priv_data;

    unsigned int i, entries;

    int64_t duration=0;

    int64_t total_sample_count=0;

    get_byte(pb); /* version */

    get_be24(pb); /* flags */

    entries = get_be32(pb);

    dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);

    if(entries >= UINT_MAX / sizeof(*sc->stts_data))

        return -1;

    sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));

    if (!sc->stts_data)

        return AVERROR(ENOMEM);

    sc->stts_count = entries;

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

        int sample_duration;

        int sample_count;

        sample_count=get_be32(pb);

        sample_duration = get_be32(pb);

        sc->stts_data[i].count= sample_count;

        sc->stts_data[i].duration= sample_duration;

        dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);

        duration+=(int64_t)sample_duration*sample_count;

        total_sample_count+=sample_count;

    }

    st->nb_frames= total_sample_count;

    if(duration)

        st->duration= duration;

    return 0;

}


static void bt_submit_sco(struct HCIInfo *info,

                const uint8_t *data, int length)

{

    struct bt_hci_s *hci = hci_from_info(info);

    uint16_t handle;

    int datalen;

    if (length < 3)

        return;

    handle = acl_handle((data[1] << 8) | data[0]);

    datalen = data[2];

    length -= 3;

    if (bt_hci_handle_bad(hci, handle)) {

        fprintf(stderr, "%s: invalid SCO handle %03x\n",

                        __FUNCTION__, handle);

        return;

    }

    if (datalen > length) {

        fprintf(stderr, "%s: SCO packet too short (%iB < %iB)\n",

                        __FUNCTION__, length, datalen);

        return;

    }

    /* TODO */

    /* TODO: increase counter and send EVT_NUM_COMP_PKTS if synchronous

     * Flow Control is enabled.

     * (See Read/Write_Synchronous_Flow_Control_Enable on page 513 and

     * page 514.)  */

}


static void do_v7m_exception_exit(ARMCPU *cpu)

{

    CPUARMState *env = &cpu->env;

    uint32_t type;

    uint32_t xpsr;

    bool ufault = false;

    bool return_to_sp_process = false;

    bool return_to_handler = false;

    bool rettobase = false;

    /* We can only get here from an EXCP_EXCEPTION_EXIT, and

     * gen_bx_excret() enforces the architectural rule

     * that jumps to magic addresses don't have magic behaviour unless

     * we're in Handler mode (compare pseudocode BXWritePC()).

     */

    assert(arm_v7m_is_handler_mode(env));

    /* In the spec pseudocode ExceptionReturn() is called directly

     * from BXWritePC() and gets the full target PC value including

     * bit zero. In QEMU's implementation we treat it as a normal

     * jump-to-register (which is then caught later on), and so split

     * the target value up between env->regs[15] and env->thumb in

     * gen_bx(). Reconstitute it.

     */

    type = env->regs[15];

    if (env->thumb) {

        type |= 1;

    }

    qemu_log_mask(CPU_LOG_INT, "Exception return: magic PC %" PRIx32

                  " previous exception %d\n",

                  type, env->v7m.exception);

    if (extract32(type, 5, 23) != extract32(-1, 5, 23)) {

        qemu_log_mask(LOG_GUEST_ERROR, "M profile: zero high bits in exception "

                      "exit PC value 0x%" PRIx32 " are UNPREDICTABLE\n", type);

    }

    if (env->v7m.exception != ARMV7M_EXCP_NMI) {

        /* Auto-clear FAULTMASK on return from other than NMI.

         * If the security extension is implemented then this only

         * happens if the raw execution priority is >= 0; the

         * value of the ES bit in the exception return value indicates

         * which security state's faultmask to clear. (v8M ARM ARM R_KBNF.)

         */

        if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {

            int es = type & 1;

            if (armv7m_nvic_raw_execution_priority(env->nvic) >= 0) {

                env->v7m.faultmask[es] = 0;

            }

        } else {

            env->v7m.faultmask[M_REG_NS] = 0;

        }

    }

    switch (armv7m_nvic_complete_irq(env->nvic, env->v7m.exception)) {

    case -1:

        /* attempt to exit an exception that isn't active */

        ufault = true;

        break;

    case 0:

        /* still an irq active now */

        break;

    case 1:

        /* we returned to base exception level, no nesting.

         * (In the pseudocode this is written using "NestedActivation != 1"

         * where we have 'rettobase == false'.)

         */

        rettobase = true;

        break;

    default:

        g_assert_not_reached();

    }

    switch (type & 0xf) {

    case 1: /* Return to Handler */

        return_to_handler = true;

        break;

    case 13: /* Return to Thread using Process stack */

        return_to_sp_process = true;

        /* fall through */

    case 9: /* Return to Thread using Main stack */

        if (!rettobase &&

            !(env->v7m.ccr[env->v7m.secure] & R_V7M_CCR_NONBASETHRDENA_MASK)) {

            ufault = true;

        }

        break;

    default:

        ufault = true;

    }

    if (ufault) {

        /* Bad exception return: instead of popping the exception

         * stack, directly take a usage fault on the current stack.

         */

        env->v7m.cfsr |= R_V7M_CFSR_INVPC_MASK;

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);

        v7m_exception_taken(cpu, type | 0xf0000000);

        qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on existing "

                      "stackframe: failed exception return integrity check\n");

        return;

    }

    /* Switch to the target stack.  */

    switch_v7m_sp(env, return_to_sp_process);

    /* Pop registers.  */

    env->regs[0] = v7m_pop(env);

    env->regs[1] = v7m_pop(env);

    env->regs[2] = v7m_pop(env);

    env->regs[3] = v7m_pop(env);

    env->regs[12] = v7m_pop(env);

    env->regs[14] = v7m_pop(env);

    env->regs[15] = v7m_pop(env);

    if (env->regs[15] & 1) {

        qemu_log_mask(LOG_GUEST_ERROR,

                      "M profile return from interrupt with misaligned "

                      "PC is UNPREDICTABLE\n");

        /* Actual hardware seems to ignore the lsbit, and there are several

         * RTOSes out there which incorrectly assume the r15 in the stack

         * frame should be a Thumb-style "lsbit indicates ARM/Thumb" value.

         */

        env->regs[15] &= ~1U;

    }

    xpsr = v7m_pop(env);

    xpsr_write(env, xpsr, ~XPSR_SPREALIGN);

    /* Undo stack alignment.  */

    if (xpsr & XPSR_SPREALIGN) {

        env->regs[13] |= 4;

    }

    /* The restored xPSR exception field will be zero if we're

     * resuming in Thread mode. If that doesn't match what the

     * exception return type specified then this is a UsageFault.

     */

    if (return_to_handler != arm_v7m_is_handler_mode(env)) {

        /* Take an INVPC UsageFault by pushing the stack again. */

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);

        env->v7m.cfsr |= R_V7M_CFSR_INVPC_MASK;

        v7m_push_stack(cpu);

        v7m_exception_taken(cpu, type | 0xf0000000);

        qemu_log_mask(CPU_LOG_INT, "...taking UsageFault on new stackframe: "

                      "failed exception return integrity check\n");

        return;

    }

    /* Otherwise, we have a successful exception exit. */

    qemu_log_mask(CPU_LOG_INT, "...successful exception return\n");

}


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

    uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,

    int flags)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l2_table, l2_entry;

    uint64_t next_contiguous_offset = 0;

    int i, l2_size, nb_csectors;

    /* Read L2 table from disk */

    l2_size = s->l2_size * sizeof(uint64_t);

    l2_table = g_malloc(l2_size);

    if (bdrv_pread(bs->file, l2_offset, l2_table, l2_size) != l2_size)

        goto fail;

    /* Do the actual checks */

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

        l2_entry = be64_to_cpu(l2_table[i]);

        switch (qcow2_get_cluster_type(l2_entry)) {

        case QCOW2_CLUSTER_COMPRESSED:

            /* Compressed clusters don't have QCOW_OFLAG_COPIED */

            if (l2_entry & QCOW_OFLAG_COPIED) {

                fprintf(stderr, "ERROR: cluster %" PRId64 ": "

                    "copied flag must never be set for compressed "

                    "clusters\n", l2_entry >> s->cluster_bits);

                l2_entry &= ~QCOW_OFLAG_COPIED;

                res->corruptions++;

            }

            /* Mark cluster as used */

            nb_csectors = ((l2_entry >> s->csize_shift) &

                           s->csize_mask) + 1;

            l2_entry &= s->cluster_offset_mask;

            inc_refcounts(bs, res, refcount_table, refcount_table_size,

                l2_entry & ~511, nb_csectors * 512);

            if (flags & CHECK_FRAG_INFO) {

                res->bfi.allocated_clusters++;

                res->bfi.compressed_clusters++;

                /* Compressed clusters are fragmented by nature.  Since they

                 * take up sub-sector space but we only have sector granularity

                 * I/O we need to re-read the same sectors even for adjacent

                 * compressed clusters.

                 */

                res->bfi.fragmented_clusters++;

            }

            break;

        case QCOW2_CLUSTER_ZERO:

            if ((l2_entry & L2E_OFFSET_MASK) == 0) {

                break;

            }

            /* fall through */

        case QCOW2_CLUSTER_NORMAL:

        {

            uint64_t offset = l2_entry & L2E_OFFSET_MASK;

            if (flags & CHECK_FRAG_INFO) {

                res->bfi.allocated_clusters++;

                if (next_contiguous_offset &&

                    offset != next_contiguous_offset) {

                    res->bfi.fragmented_clusters++;

                }

                next_contiguous_offset = offset + s->cluster_size;

            }

            /* Mark cluster as used */

            inc_refcounts(bs, res, refcount_table,refcount_table_size,

                offset, s->cluster_size);

            /* Correct offsets are cluster aligned */

            if (offset_into_cluster(s, offset)) {

                fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "

                    "properly aligned; L2 entry corrupted.\n", offset);

                res->corruptions++;

            }

            break;

        }

        case QCOW2_CLUSTER_UNALLOCATED:

            break;

        default:

            abort();

        }

    }

    g_free(l2_table);

    return 0;

fail:

    fprintf(stderr, "ERROR: I/O error in check_refcounts_l2\n");

    g_free(l2_table);

    return -EIO;

}


static inline void gen_op_fcmpq(int fccno)

{

    switch (fccno) {

    case 0:

        gen_helper_fcmpq(cpu_env);

        break;

    case 1:

        gen_helper_fcmpq_fcc1(cpu_env);

        break;

    case 2:

        gen_helper_fcmpq_fcc2(cpu_env);

        break;

    case 3:

        gen_helper_fcmpq_fcc3(cpu_env);

        break;

    }

}


static int proxy_closedir(FsContext *ctx, V9fsFidOpenState *fs)

{

    return closedir(fs->dir);

}


static int ne2000_can_receive(void *opaque)

{

    NE2000State *s = opaque;

    int avail, index, boundary;

    if (s->cmd & E8390_STOP)

        return 0;

    index = s->curpag << 8;

    boundary = s->boundary << 8;

    if (index < boundary)

        avail = boundary - index;

    else

        avail = (s->stop - s->start) - (index - boundary);

    if (avail < (MAX_ETH_FRAME_SIZE + 4))

        return 0;

    return MAX_ETH_FRAME_SIZE;

}


static void test_qemu_strtoll_invalid(void)

{

    const char *str = "   xxxx  \t abc";

    char f = 'X';

    const char *endptr = &f;

    int64_t res = 999;

    int err;

    err = qemu_strtoll(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert(endptr == str);

}


static int decode_i_picture_secondary_header(VC9Context *v)

{

    int status;

#if HAS_ADVANCED_PROFILE

    if (v->profile > PROFILE_MAIN)

    {

        v->s.ac_pred = get_bits(&v->s.gb, 1);

        if (v->postprocflag) v->postproc = get_bits(&v->s.gb, 1);

        /* 7.1.1.34 + 8.5.2 */

        if (v->overlap && v->pq<9)

        {

            v->condover = get_bits(&v->s.gb, 1);

            if (v->condover)

            {

                v->condover = 2+get_bits(&v->s.gb, 1);

                if (v->condover == 3)

                {

                    status = bitplane_decoding(&v->over_flags_plane, v);

                    if (status < 0) return -1;

#  if TRACE

                    av_log(v->s.avctx, AV_LOG_DEBUG, "Overflags plane encoding: "

                           "Imode: %i, Invert: %i\n", status>>1, status&1);

#  endif

                }

            }

        }

    }

#endif

    /* Epilog (AC/DC syntax) should be done in caller */

    return 0;

}


void visit_type_enum(Visitor *v, int *obj, const char *strings[],

                     const char *kind, const char *name, Error **errp)

{

    if (!error_is_set(errp)) {

        v->type_enum(v, obj, strings, kind, name, errp);

    }

}


static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,

                                  AVPacket *pkt)

{

    AVIStream *ast, *next_ast = next_st->priv_data;

    int64_t ts, next_ts, ts_min = INT64_MAX;

    AVStream *st, *sub_st = NULL;

    int i;

    next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,

                           AV_TIME_BASE_Q);

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

        st  = s->streams[i];

        ast = st->priv_data;

        if (st->discard < AVDISCARD_ALL && ast->sub_pkt.data) {

            ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);

            if (ts <= next_ts && ts < ts_min) {

                ts_min = ts;

                sub_st = st;

            }

        }

    }

    if (sub_st) {

        ast = sub_st->priv_data;

        *pkt = ast->sub_pkt;

        pkt->stream_index = sub_st->index;

        if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)

            ast->sub_pkt.data = NULL;

    }

    return sub_st;

}


static void adb_keyboard_event(DeviceState *dev, QemuConsole *src,

                               InputEvent *evt)

{

    KBDState *s = (KBDState *)dev;

    int qcode, keycode;

    qcode = qemu_input_key_value_to_qcode(evt->u.key.data->key);

    if (qcode >= ARRAY_SIZE(qcode_to_adb_keycode)) {

        return;

    }

    /* FIXME: take handler into account when translating qcode */

    keycode = qcode_to_adb_keycode[qcode];

    if (keycode == NO_KEY) {  /* We don't want to send this to the guest */

        ADB_DPRINTF("Ignoring NO_KEY\n");

        return;

    }

    if (evt->u.key.data->down == false) { /* if key release event */

        keycode = keycode | 0x80;   /* create keyboard break code */

    }

    adb_kbd_put_keycode(s, keycode);

}


void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx)

{

    mm_flags = mm_support();

    if (avctx->dsp_mask) {

        if (avctx->dsp_mask & FF_MM_FORCE)

            mm_flags |= (avctx->dsp_mask & 0xffff);

        else

            mm_flags &= ~(avctx->dsp_mask & 0xffff);

    }

#if 0

    av_log(avctx, AV_LOG_INFO, "libavcodec: CPU flags:");

    if (mm_flags & MM_MMX)

        av_log(avctx, AV_LOG_INFO, " mmx");

    if (mm_flags & MM_MMXEXT)

        av_log(avctx, AV_LOG_INFO, " mmxext");

    if (mm_flags & MM_3DNOW)

        av_log(avctx, AV_LOG_INFO, " 3dnow");

    if (mm_flags & MM_SSE)

        av_log(avctx, AV_LOG_INFO, " sse");

    if (mm_flags & MM_SSE2)

        av_log(avctx, AV_LOG_INFO, " sse2");

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

#endif

    if (mm_flags & MM_MMX) {

        const int idct_algo= avctx->idct_algo;

        if(avctx->lowres==0){

            if(idct_algo==FF_IDCT_AUTO || idct_algo==FF_IDCT_SIMPLEMMX){

                c->idct_put= ff_simple_idct_put_mmx;

                c->idct_add= ff_simple_idct_add_mmx;

                c->idct    = ff_simple_idct_mmx;

                c->idct_permutation_type= FF_SIMPLE_IDCT_PERM;

#ifdef CONFIG_GPL

            }else if(idct_algo==FF_IDCT_LIBMPEG2MMX){

                if(mm_flags & MM_MMXEXT){

                    c->idct_put= ff_libmpeg2mmx2_idct_put;

                    c->idct_add= ff_libmpeg2mmx2_idct_add;

                    c->idct    = ff_mmxext_idct;

                }else{

                    c->idct_put= ff_libmpeg2mmx_idct_put;

                    c->idct_add= ff_libmpeg2mmx_idct_add;

                    c->idct    = ff_mmx_idct;

                }

                c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM;

#endif

            }else if((ENABLE_VP3_DECODER || ENABLE_VP5_DECODER || ENABLE_VP6_DECODER || ENABLE_THEORA_DECODER) &&

                     idct_algo==FF_IDCT_VP3){

                if(mm_flags & MM_SSE2){

                    c->idct_put= ff_vp3_idct_put_sse2;

                    c->idct_add= ff_vp3_idct_add_sse2;

                    c->idct    = ff_vp3_idct_sse2;

                    c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM;

                }else{

                    c->idct_put= ff_vp3_idct_put_mmx;

                    c->idct_add= ff_vp3_idct_add_mmx;

                    c->idct    = ff_vp3_idct_mmx;

                    c->idct_permutation_type= FF_PARTTRANS_IDCT_PERM;

                }

            }else if(idct_algo==FF_IDCT_CAVS){

                    c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM;

            }else if(idct_algo==FF_IDCT_XVIDMMX){

                if(mm_flags & MM_SSE2){

                    c->idct_put= ff_idct_xvid_sse2_put;

                    c->idct_add= ff_idct_xvid_sse2_add;

                    c->idct    = ff_idct_xvid_sse2;

                    c->idct_permutation_type= FF_SSE2_IDCT_PERM;

                }else if(mm_flags & MM_MMXEXT){

                    c->idct_put= ff_idct_xvid_mmx2_put;

                    c->idct_add= ff_idct_xvid_mmx2_add;

                    c->idct    = ff_idct_xvid_mmx2;

                }else{

                    c->idct_put= ff_idct_xvid_mmx_put;

                    c->idct_add= ff_idct_xvid_mmx_add;

                    c->idct    = ff_idct_xvid_mmx;

                }

            }

        }

        c->put_pixels_clamped = put_pixels_clamped_mmx;

        c->put_signed_pixels_clamped = put_signed_pixels_clamped_mmx;

        c->add_pixels_clamped = add_pixels_clamped_mmx;

        c->clear_blocks = clear_blocks_mmx;

#define SET_HPEL_FUNCS(PFX, IDX, SIZE, CPU) \

        c->PFX ## _pixels_tab[IDX][0] = PFX ## _pixels ## SIZE ## _ ## CPU; \

        c->PFX ## _pixels_tab[IDX][1] = PFX ## _pixels ## SIZE ## _x2_ ## CPU; \

        c->PFX ## _pixels_tab[IDX][2] = PFX ## _pixels ## SIZE ## _y2_ ## CPU; \

        c->PFX ## _pixels_tab[IDX][3] = PFX ## _pixels ## SIZE ## _xy2_ ## CPU

        SET_HPEL_FUNCS(put, 0, 16, mmx);

        SET_HPEL_FUNCS(put_no_rnd, 0, 16, mmx);

        SET_HPEL_FUNCS(avg, 0, 16, mmx);

        SET_HPEL_FUNCS(avg_no_rnd, 0, 16, mmx);

        SET_HPEL_FUNCS(put, 1, 8, mmx);

        SET_HPEL_FUNCS(put_no_rnd, 1, 8, mmx);

        SET_HPEL_FUNCS(avg, 1, 8, mmx);

        SET_HPEL_FUNCS(avg_no_rnd, 1, 8, mmx);

        c->gmc= gmc_mmx;

        c->add_bytes= add_bytes_mmx;

        c->add_bytes_l2= add_bytes_l2_mmx;

        c->draw_edges = draw_edges_mmx;

        if (ENABLE_ANY_H263) {

            c->h263_v_loop_filter= h263_v_loop_filter_mmx;

            c->h263_h_loop_filter= h263_h_loop_filter_mmx;

        }

        if ((ENABLE_VP3_DECODER || ENABLE_THEORA_DECODER) &&

            !(avctx->flags & CODEC_FLAG_BITEXACT)) {

            c->vp3_v_loop_filter= ff_vp3_v_loop_filter_mmx;

            c->vp3_h_loop_filter= ff_vp3_h_loop_filter_mmx;

        }

        c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_mmx_rnd;

        c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_mmx;

        c->put_no_rnd_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_mmx_nornd;

        c->h264_idct_dc_add=

        c->h264_idct_add= ff_h264_idct_add_mmx;

        c->h264_idct8_dc_add=

        c->h264_idct8_add= ff_h264_idct8_add_mmx;

        if (mm_flags & MM_SSE2)

            c->h264_idct8_add= ff_h264_idct8_add_sse2;

        if (mm_flags & MM_MMXEXT) {

            c->prefetch = prefetch_mmx2;

            c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2;

            c->put_pixels_tab[0][2] = put_pixels16_y2_mmx2;

            c->avg_pixels_tab[0][0] = avg_pixels16_mmx2;

            c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmx2;

            c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmx2;

            c->put_pixels_tab[1][1] = put_pixels8_x2_mmx2;

            c->put_pixels_tab[1][2] = put_pixels8_y2_mmx2;

            c->avg_pixels_tab[1][0] = avg_pixels8_mmx2;

            c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmx2;

            c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmx2;

            c->h264_idct_dc_add= ff_h264_idct_dc_add_mmx2;

            c->h264_idct8_dc_add= ff_h264_idct8_dc_add_mmx2;

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmx2;

                c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmx2;

                c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmx2;

                c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmx2;

                c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2;

                c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2;

            }

#define SET_QPEL_FUNCS(PFX, IDX, SIZE, CPU) \

            c->PFX ## _pixels_tab[IDX][ 0] = PFX ## SIZE ## _mc00_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 1] = PFX ## SIZE ## _mc10_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 2] = PFX ## SIZE ## _mc20_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 3] = PFX ## SIZE ## _mc30_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 4] = PFX ## SIZE ## _mc01_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 5] = PFX ## SIZE ## _mc11_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 6] = PFX ## SIZE ## _mc21_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 7] = PFX ## SIZE ## _mc31_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 8] = PFX ## SIZE ## _mc02_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][ 9] = PFX ## SIZE ## _mc12_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][10] = PFX ## SIZE ## _mc22_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][11] = PFX ## SIZE ## _mc32_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][12] = PFX ## SIZE ## _mc03_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][13] = PFX ## SIZE ## _mc13_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][14] = PFX ## SIZE ## _mc23_ ## CPU; \

            c->PFX ## _pixels_tab[IDX][15] = PFX ## SIZE ## _mc33_ ## CPU

            SET_QPEL_FUNCS(put_qpel, 0, 16, mmx2);

            SET_QPEL_FUNCS(put_qpel, 1, 8, mmx2);

            SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmx2);

            SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, mmx2);

            SET_QPEL_FUNCS(avg_qpel, 0, 16, mmx2);

            SET_QPEL_FUNCS(avg_qpel, 1, 8, mmx2);

            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmx2);

            SET_QPEL_FUNCS(put_h264_qpel, 1, 8, mmx2);

            SET_QPEL_FUNCS(put_h264_qpel, 2, 4, mmx2);

            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmx2);

            SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, mmx2);

            SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, mmx2);

            SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, mmx2);

            SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, mmx2);

            SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2);

            SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, mmx2);

            c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_mmx2_rnd;

            c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_mmx2;

            c->avg_h264_chroma_pixels_tab[2]= avg_h264_chroma_mc2_mmx2;

            c->put_h264_chroma_pixels_tab[2]= put_h264_chroma_mc2_mmx2;

            c->h264_v_loop_filter_luma= h264_v_loop_filter_luma_mmx2;

            c->h264_h_loop_filter_luma= h264_h_loop_filter_luma_mmx2;

            c->h264_v_loop_filter_chroma= h264_v_loop_filter_chroma_mmx2;

            c->h264_h_loop_filter_chroma= h264_h_loop_filter_chroma_mmx2;

            c->h264_v_loop_filter_chroma_intra= h264_v_loop_filter_chroma_intra_mmx2;

            c->h264_h_loop_filter_chroma_intra= h264_h_loop_filter_chroma_intra_mmx2;

            c->h264_loop_filter_strength= h264_loop_filter_strength_mmx2;

            c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_mmx2;

            c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_mmx2;

            c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_mmx2;

            c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_mmx2;

            c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_mmx2;

            c->weight_h264_pixels_tab[5]= ff_h264_weight_4x8_mmx2;

            c->weight_h264_pixels_tab[6]= ff_h264_weight_4x4_mmx2;

            c->weight_h264_pixels_tab[7]= ff_h264_weight_4x2_mmx2;

            c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_mmx2;

            c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_mmx2;

            c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_mmx2;

            c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_mmx2;

            c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_mmx2;

            c->biweight_h264_pixels_tab[5]= ff_h264_biweight_4x8_mmx2;

            c->biweight_h264_pixels_tab[6]= ff_h264_biweight_4x4_mmx2;

            c->biweight_h264_pixels_tab[7]= ff_h264_biweight_4x2_mmx2;

            if (ENABLE_CAVS_DECODER)

                ff_cavsdsp_init_mmx2(c, avctx);

            if (ENABLE_VC1_DECODER || ENABLE_WMV3_DECODER)

                ff_vc1dsp_init_mmx(c, avctx);

            c->add_png_paeth_prediction= add_png_paeth_prediction_mmx2;

        } else if (mm_flags & MM_3DNOW) {

            c->prefetch = prefetch_3dnow;

            c->put_pixels_tab[0][1] = put_pixels16_x2_3dnow;

            c->put_pixels_tab[0][2] = put_pixels16_y2_3dnow;

            c->avg_pixels_tab[0][0] = avg_pixels16_3dnow;

            c->avg_pixels_tab[0][1] = avg_pixels16_x2_3dnow;

            c->avg_pixels_tab[0][2] = avg_pixels16_y2_3dnow;

            c->put_pixels_tab[1][1] = put_pixels8_x2_3dnow;

            c->put_pixels_tab[1][2] = put_pixels8_y2_3dnow;

            c->avg_pixels_tab[1][0] = avg_pixels8_3dnow;

            c->avg_pixels_tab[1][1] = avg_pixels8_x2_3dnow;

            c->avg_pixels_tab[1][2] = avg_pixels8_y2_3dnow;

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_3dnow;

                c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_3dnow;

                c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_3dnow;

                c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_3dnow;

                c->avg_pixels_tab[0][3] = avg_pixels16_xy2_3dnow;

                c->avg_pixels_tab[1][3] = avg_pixels8_xy2_3dnow;

            }

            SET_QPEL_FUNCS(put_qpel, 0, 16, 3dnow);

            SET_QPEL_FUNCS(put_qpel, 1, 8, 3dnow);

            SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, 3dnow);

            SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, 3dnow);

            SET_QPEL_FUNCS(avg_qpel, 0, 16, 3dnow);

            SET_QPEL_FUNCS(avg_qpel, 1, 8, 3dnow);

            SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 3dnow);

            SET_QPEL_FUNCS(put_h264_qpel, 1, 8, 3dnow);

            SET_QPEL_FUNCS(put_h264_qpel, 2, 4, 3dnow);

            SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 3dnow);

            SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, 3dnow);

            SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, 3dnow);

            SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, 3dnow);

            SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, 3dnow);

            SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, 3dnow);

            SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, 3dnow);

            c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_3dnow_rnd;

            c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_3dnow;

            if (ENABLE_CAVS_DECODER)

                ff_cavsdsp_init_3dnow(c, avctx);

        }

#define H264_QPEL_FUNCS(x, y, CPU)\

            c->put_h264_qpel_pixels_tab[0][x+y*4] = put_h264_qpel16_mc##x##y##_##CPU;\

            c->put_h264_qpel_pixels_tab[1][x+y*4] = put_h264_qpel8_mc##x##y##_##CPU;\

            c->avg_h264_qpel_pixels_tab[0][x+y*4] = avg_h264_qpel16_mc##x##y##_##CPU;\

            c->avg_h264_qpel_pixels_tab[1][x+y*4] = avg_h264_qpel8_mc##x##y##_##CPU;

        if((mm_flags & MM_SSE2) && !(mm_flags & MM_3DNOW)){

            // these functions are slower than mmx on AMD, but faster on Intel

/* FIXME works in most codecs, but crashes svq1 due to unaligned chroma

            c->put_pixels_tab[0][0] = put_pixels16_sse2;

            c->avg_pixels_tab[0][0] = avg_pixels16_sse2;

*/

            H264_QPEL_FUNCS(0, 0, sse2);

        }

        if(mm_flags & MM_SSE2){

            H264_QPEL_FUNCS(0, 1, sse2);

            H264_QPEL_FUNCS(0, 2, sse2);

            H264_QPEL_FUNCS(0, 3, sse2);

            H264_QPEL_FUNCS(1, 1, sse2);

            H264_QPEL_FUNCS(1, 2, sse2);

            H264_QPEL_FUNCS(1, 3, sse2);

            H264_QPEL_FUNCS(2, 1, sse2);

            H264_QPEL_FUNCS(2, 2, sse2);

            H264_QPEL_FUNCS(2, 3, sse2);

            H264_QPEL_FUNCS(3, 1, sse2);

            H264_QPEL_FUNCS(3, 2, sse2);

            H264_QPEL_FUNCS(3, 3, sse2);

        }

#ifdef HAVE_SSSE3

        if(mm_flags & MM_SSSE3){

            H264_QPEL_FUNCS(1, 0, ssse3);

            H264_QPEL_FUNCS(1, 1, ssse3);

            H264_QPEL_FUNCS(1, 2, ssse3);

            H264_QPEL_FUNCS(1, 3, ssse3);

            H264_QPEL_FUNCS(2, 0, ssse3);

            H264_QPEL_FUNCS(2, 1, ssse3);

            H264_QPEL_FUNCS(2, 2, ssse3);

            H264_QPEL_FUNCS(2, 3, ssse3);

            H264_QPEL_FUNCS(3, 0, ssse3);

            H264_QPEL_FUNCS(3, 1, ssse3);

            H264_QPEL_FUNCS(3, 2, ssse3);

            H264_QPEL_FUNCS(3, 3, ssse3);

            c->put_no_rnd_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_ssse3_nornd;

            c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_ssse3_rnd;

            c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_ssse3_rnd;

            c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_ssse3;

            c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_ssse3;

            c->add_png_paeth_prediction= add_png_paeth_prediction_ssse3;

        }

#endif

#ifdef CONFIG_SNOW_DECODER

        if(mm_flags & MM_SSE2 & 0){

            c->horizontal_compose97i = ff_snow_horizontal_compose97i_sse2;

#ifdef HAVE_7REGS

            c->vertical_compose97i = ff_snow_vertical_compose97i_sse2;

#endif

            c->inner_add_yblock = ff_snow_inner_add_yblock_sse2;

        }

        else{

            if(mm_flags & MM_MMXEXT){

            c->horizontal_compose97i = ff_snow_horizontal_compose97i_mmx;

#ifdef HAVE_7REGS

            c->vertical_compose97i = ff_snow_vertical_compose97i_mmx;

#endif

            }

            c->inner_add_yblock = ff_snow_inner_add_yblock_mmx;

        }

#endif

        if(mm_flags & MM_3DNOW){

            c->vorbis_inverse_coupling = vorbis_inverse_coupling_3dnow;

            c->vector_fmul = vector_fmul_3dnow;

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->float_to_int16 = float_to_int16_3dnow;

                c->float_to_int16_interleave = float_to_int16_interleave_3dnow;

            }

        }

        if(mm_flags & MM_3DNOWEXT){

            c->vector_fmul_reverse = vector_fmul_reverse_3dnow2;

            c->vector_fmul_window = vector_fmul_window_3dnow2;

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->float_to_int16_interleave = float_to_int16_interleave_3dn2;

            }

        }

        if(mm_flags & MM_SSE){

            c->vorbis_inverse_coupling = vorbis_inverse_coupling_sse;

            c->ac3_downmix = ac3_downmix_sse;

            c->vector_fmul = vector_fmul_sse;

            c->vector_fmul_reverse = vector_fmul_reverse_sse;

            c->vector_fmul_add_add = vector_fmul_add_add_sse;

            c->vector_fmul_window = vector_fmul_window_sse;

            c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse;

            c->float_to_int16 = float_to_int16_sse;

            c->float_to_int16_interleave = float_to_int16_interleave_sse;

        }

        if(mm_flags & MM_3DNOW)

            c->vector_fmul_add_add = vector_fmul_add_add_3dnow; // faster than sse

        if(mm_flags & MM_SSE2){

            c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse2;

            c->float_to_int16 = float_to_int16_sse2;

            c->float_to_int16_interleave = float_to_int16_interleave_sse2;

            c->add_int16 = add_int16_sse2;

            c->sub_int16 = sub_int16_sse2;

            c->scalarproduct_int16 = scalarproduct_int16_sse2;

        }

    }

    if (ENABLE_ENCODERS)

        dsputilenc_init_mmx(c, avctx);

#if 0

    // for speed testing

    get_pixels = just_return;

    put_pixels_clamped = just_return;

    add_pixels_clamped = just_return;

    pix_abs16x16 = just_return;

    pix_abs16x16_x2 = just_return;

    pix_abs16x16_y2 = just_return;

    pix_abs16x16_xy2 = just_return;

    put_pixels_tab[0] = just_return;

    put_pixels_tab[1] = just_return;

    put_pixels_tab[2] = just_return;

    put_pixels_tab[3] = just_return;

    put_no_rnd_pixels_tab[0] = just_return;

    put_no_rnd_pixels_tab[1] = just_return;

    put_no_rnd_pixels_tab[2] = just_return;

    put_no_rnd_pixels_tab[3] = just_return;

    avg_pixels_tab[0] = just_return;

    avg_pixels_tab[1] = just_return;

    avg_pixels_tab[2] = just_return;

    avg_pixels_tab[3] = just_return;

    avg_no_rnd_pixels_tab[0] = just_return;

    avg_no_rnd_pixels_tab[1] = just_return;

    avg_no_rnd_pixels_tab[2] = just_return;

    avg_no_rnd_pixels_tab[3] = just_return;

    //av_fdct = just_return;

    //ff_idct = just_return;

#endif

}


static void iscsi_retry_timer_expired(void *opaque)

{

    struct IscsiTask *iTask = opaque;

    iTask->complete = 1;

    if (iTask->co) {

        qemu_coroutine_enter(iTask->co, NULL);

    }

}


int qemu_shutdown_requested_get(void)

{

    return shutdown_requested;

}


static inline void RENAME(rgb15ToY)(uint8_t *dst, uint8_t *src, int width)

{

	int i;

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

	{

		int d= ((uint16_t*)src)[i];

		int r= d&0x1F;

		int g= (d>>5)&0x1F;

		int b= (d>>10)&0x1F;

		dst[i]= ((RY*r + GY*g + BY*b)>>(RGB2YUV_SHIFT-3)) + 16;

	}

}


static int kvm_dirty_pages_log_change(target_phys_addr_t phys_addr, target_phys_addr_t end_addr,

                                      unsigned flags,

                                      unsigned mask)

{

    KVMState *s = kvm_state;

    KVMSlot *mem = kvm_lookup_slot(s, phys_addr);

    if (mem == NULL)  {

            dprintf("invalid parameters %llx-%llx\n", phys_addr, end_addr);

            return -EINVAL;

    }

    flags = (mem->flags & ~mask) | flags;

    /* Nothing changed, no need to issue ioctl */

    if (flags == mem->flags)

            return 0;

    mem->flags = flags;

    return kvm_set_user_memory_region(s, mem);

}


static void RENAME(uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,

                                      long width, long height,

                                      long lumStride, long chromStride, long srcStride)

{

    long y;

    const long chromWidth= -((-width)>>1);

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

        RENAME(extract_even)(src+1, ydst, width);

        if(y&1) {

            RENAME(extract_even2avg)(src-srcStride, src, udst, vdst, chromWidth);

            udst+= chromStride;

            vdst+= chromStride;

        }

        src += srcStride;

        ydst+= lumStride;

    }

#if COMPILE_TEMPLATE_MMX

    __asm__(

            EMMS"       \n\t"

            SFENCE"     \n\t"

            ::: "memory"

        );

#endif

}


static int bayer_to_yv12_wrapper(SwsContext *c, const uint8_t* src[], int srcStride[], int srcSliceY,

                                 int srcSliceH, uint8_t* dst[], int dstStride[])

{

    const uint8_t *srcPtr= src[0];

    uint8_t *dstY= dst[0];

    uint8_t *dstU= dst[1];

    uint8_t *dstV= dst[2];

    int i;

    void (*copy)       (const uint8_t *src, int src_stride, uint8_t *dstY, uint8_t *dstU, uint8_t *dstV, int luma_stride, int width, int32_t *rgb2yuv);

    void (*interpolate)(const uint8_t *src, int src_stride, uint8_t *dstY, uint8_t *dstU, uint8_t *dstV, int luma_stride, int width, int32_t *rgb2yuv);

    switch(c->srcFormat) {

#define CASE(pixfmt, prefix) \

    case pixfmt: copy        = bayer_##prefix##_to_yv12_copy; \

                 interpolate = bayer_##prefix##_to_yv12_interpolate; \

                 break;

    CASE(AV_PIX_FMT_BAYER_BGGR8,    bggr8)

    CASE(AV_PIX_FMT_BAYER_BGGR16LE, bggr16le)

    CASE(AV_PIX_FMT_BAYER_BGGR16BE, bggr16be)

    CASE(AV_PIX_FMT_BAYER_RGGB8,    rggb8)

    CASE(AV_PIX_FMT_BAYER_RGGB16LE, rggb16le)

    CASE(AV_PIX_FMT_BAYER_RGGB16BE, rggb16be)

    CASE(AV_PIX_FMT_BAYER_GBRG8,    gbrg8)

    CASE(AV_PIX_FMT_BAYER_GBRG16LE, gbrg16le)

    CASE(AV_PIX_FMT_BAYER_GBRG16BE, gbrg16be)

    CASE(AV_PIX_FMT_BAYER_GRBG8,    grbg8)

    CASE(AV_PIX_FMT_BAYER_GRBG16LE, grbg16le)

    CASE(AV_PIX_FMT_BAYER_GRBG16BE, grbg16be)

#undef CASE

    default: return 0;

    }

    copy(srcPtr, srcStride[0], dstY, dstU, dstV, dstStride[0], c->srcW, c->input_rgb2yuv_table);

    srcPtr += 2 * srcStride[0];

    dstY   += 2 * dstStride[0];

    dstU   +=     dstStride[1];

    dstV   +=     dstStride[1];

    for (i = 2; i < srcSliceH - 2; i += 2) {

        interpolate(srcPtr, srcStride[0], dstY, dstU, dstV, dstStride[0], c->srcW, c->input_rgb2yuv_table);

        srcPtr += 2 * srcStride[0];

        dstY   += 2 * dstStride[0];

        dstU   +=     dstStride[1];

        dstV   +=     dstStride[1];

    }

    copy(srcPtr, srcStride[0], dstY, dstU, dstV, dstStride[0], c->srcW, c->input_rgb2yuv_table);

    return srcSliceH;

}


static int vaapi_encode_h264_init_picture_params(AVCodecContext *avctx,

                                                 VAAPIEncodePicture *pic)

{

    VAAPIEncodeContext                *ctx = avctx->priv_data;

    VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params;

    VAEncPictureParameterBufferH264  *vpic = pic->codec_picture_params;

    VAAPIEncodeH264Context           *priv = ctx->priv_data;

    int i;

    if (pic->type == PICTURE_TYPE_IDR) {

        av_assert0(pic->display_order == pic->encode_order);

        vpic->frame_num = 0;

        priv->next_frame_num = 1;

        priv->cpb_delay = 0;

    } else {

        vpic->frame_num = priv->next_frame_num;

        if (pic->type != PICTURE_TYPE_B) {

            // nal_ref_idc != 0

            ++priv->next_frame_num;

        }

        ++priv->cpb_delay;

    }

    priv->dpb_delay = pic->display_order - pic->encode_order + 1;

    vpic->frame_num = vpic->frame_num &

        ((1 << (4 + vseq->seq_fields.bits.log2_max_frame_num_minus4)) - 1);

    vpic->CurrPic.picture_id          = pic->recon_surface;

    vpic->CurrPic.frame_idx           = vpic->frame_num;

    vpic->CurrPic.flags               = 0;

    vpic->CurrPic.TopFieldOrderCnt    = pic->display_order;

    vpic->CurrPic.BottomFieldOrderCnt = pic->display_order;

    for (i = 0; i < pic->nb_refs; i++) {

        VAAPIEncodePicture *ref = pic->refs[i];

        av_assert0(ref && ref->encode_order < pic->encode_order);

        vpic->ReferenceFrames[i].picture_id = ref->recon_surface;

        vpic->ReferenceFrames[i].frame_idx  = ref->encode_order;

        vpic->ReferenceFrames[i].flags = VA_PICTURE_H264_SHORT_TERM_REFERENCE;

        vpic->ReferenceFrames[i].TopFieldOrderCnt    = ref->display_order;

        vpic->ReferenceFrames[i].BottomFieldOrderCnt = ref->display_order;

    }

    for (; i < FF_ARRAY_ELEMS(vpic->ReferenceFrames); i++) {

        vpic->ReferenceFrames[i].picture_id = VA_INVALID_ID;

        vpic->ReferenceFrames[i].flags = VA_PICTURE_H264_INVALID;

    }

    vpic->coded_buf = pic->output_buffer;

    vpic->pic_fields.bits.idr_pic_flag = (pic->type == PICTURE_TYPE_IDR);

    vpic->pic_fields.bits.reference_pic_flag = (pic->type != PICTURE_TYPE_B);

    pic->nb_slices = 1;

    return 0;

}


static inline int is_bit_set(BlockDriverState *bs, int64_t bitnum)

{

    uint64_t offset = sizeof(struct cow_header_v2) + bitnum / 8;

    uint8_t bitmap;

    if (bdrv_pread(bs->file, offset, &bitmap, sizeof(bitmap)) !=

	    sizeof(bitmap)) {

       return -errno;

    }

    return !!(bitmap & (1 << (bitnum % 8)));

}


bool st_init(const char *file)

{

    pthread_t thread;

    pthread_attr_t attr;

    sigset_t set, oldset;

    int ret;

    pthread_attr_init(&attr);

    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    sigfillset(&set);

    pthread_sigmask(SIG_SETMASK, &set, &oldset);

    ret = pthread_create(&thread, &attr, writeout_thread, NULL);

    pthread_sigmask(SIG_SETMASK, &oldset, NULL);

    if (ret != 0) {

        return false;

    }

    atexit(st_flush_trace_buffer);

    st_set_trace_file(file);

    return true;

}


static int libquvi_close(AVFormatContext *s)

{

    LibQuviContext *qc = s->priv_data;

    if (qc->fmtctx)

        avformat_close_input(&qc->fmtctx);

    return 0;

}


static void aspeed_soc_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    AspeedSoCClass *sc = ASPEED_SOC_CLASS(oc);

    sc->info = (AspeedSoCInfo *) data;

    dc->realize = aspeed_soc_realize;

}


static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,

                                   struct in_addr my_ip)

{

    AVFormatContext *avc;

    AVStream avs[MAX_STREAMS];

    int i;

    avc =  avformat_alloc_context();

    if (avc == NULL) {

        return -1;

    }

    av_metadata_set2(&avc->metadata, "title",

                     stream->title[0] ? stream->title : "No Title", 0);

    avc->nb_streams = stream->nb_streams;

    if (stream->is_multicast) {

        snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",

                 inet_ntoa(stream->multicast_ip),

                 stream->multicast_port, stream->multicast_ttl);

    } else {

        snprintf(avc->filename, 1024, "rtp://0.0.0.0");

    }

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

        avc->streams[i] = &avs[i];

        avc->streams[i]->codec = stream->streams[i]->codec;

    }

    *pbuffer = av_mallocz(2048);

    avf_sdp_create(&avc, 1, *pbuffer, 2048);

    av_free(avc);

    return strlen(*pbuffer);

}


static int dvdsub_decode(AVCodecContext *avctx,

                         void *data, int *data_size,

                         AVPacket *avpkt)

{

    DVDSubContext *ctx = avctx->priv_data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    AVSubtitle *sub = data;

    int is_menu;

    if (ctx->buf) {

        int ret = append_to_cached_buf(avctx, buf, buf_size);

        if (ret < 0) {

            *data_size = 0;

            return ret;

        }

        buf = ctx->buf;

        buf_size = ctx->buf_size;

    }

    is_menu = decode_dvd_subtitles(ctx, sub, buf, buf_size);

    if (is_menu == AVERROR(EAGAIN)) {

        *data_size = 0;

        return append_to_cached_buf(avctx, buf, buf_size);

    }

    if (is_menu < 0) {

    no_subtitle:

        reset_rects(sub);

        *data_size = 0;

        return buf_size;

    }

    if (!is_menu && find_smallest_bounding_rectangle(sub) == 0)

        goto no_subtitle;

    if (ctx->forced_subs_only && !(sub->rects[0]->flags & AV_SUBTITLE_FLAG_FORCED))

        goto no_subtitle;

#if defined(DEBUG)

    {

    char ppm_name[32];

    snprintf(ppm_name, sizeof(ppm_name), "/tmp/%05d.ppm", ctx->sub_id++);

    av_dlog(NULL, "start=%d ms end =%d ms\n",

            sub->start_display_time,

            sub->end_display_time);

    ppm_save(ppm_name, sub->rects[0]->pict.data[0],

             sub->rects[0]->w, sub->rects[0]->h, (uint32_t*) sub->rects[0]->pict.data[1]);

    }

#endif

    av_freep(&ctx->buf);

    ctx->buf_size = 0;

    *data_size = 1;

    return buf_size;

}


static void ibm_40p_init(MachineState *machine)

{

    CPUPPCState *env = NULL;

    uint16_t cmos_checksum;

    PowerPCCPU *cpu;

    DeviceState *dev;

    SysBusDevice *pcihost;

    Nvram *m48t59 = NULL;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    void *fw_cfg;

    int i;

    uint32_t kernel_base = 0, initrd_base = 0;

    long kernel_size = 0, initrd_size = 0;

    char boot_device;

    /* init CPU */

    if (!machine->cpu_model) {

        machine->cpu_model = "604";

    }

    cpu = POWERPC_CPU(cpu_generic_init(TYPE_POWERPC_CPU, machine->cpu_model));

    if (!cpu) {

        error_report("could not initialize CPU '%s'",

                     machine->cpu_model);

        exit(1);

    }

    env = &cpu->env;

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        error_report("only 6xx bus is supported on this machine");

        exit(1);

    }

    if (env->flags & POWERPC_FLAG_RTC_CLK) {

        /* POWER / PowerPC 601 RTC clock frequency is 7.8125 MHz */

        cpu_ppc_tb_init(env, 7812500UL);

    } else {

        /* Set time-base frequency to 100 Mhz */

        cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

    }

    qemu_register_reset(ppc_prep_reset, cpu);

    /* PCI host */

    dev = qdev_create(NULL, "raven-pcihost");

    if (!bios_name) {

        bios_name = BIOS_FILENAME;

    }

    qdev_prop_set_string(dev, "bios-name", bios_name);

    qdev_prop_set_uint32(dev, "elf-machine", PPC_ELF_MACHINE);

    pcihost = SYS_BUS_DEVICE(dev);

    object_property_add_child(qdev_get_machine(), "raven", OBJECT(dev), NULL);

    qdev_init_nofail(dev);

    pci_bus = PCI_BUS(qdev_get_child_bus(dev, "pci.0"));

    if (!pci_bus) {

        error_report("could not create PCI host controller");

        exit(1);

    }

    /* PCI -> ISA bridge */

    dev = DEVICE(pci_create_simple(pci_bus, PCI_DEVFN(11, 0), "i82378"));

    qdev_connect_gpio_out(dev, 0,

                          cpu->env.irq_inputs[PPC6xx_INPUT_INT]);

    sysbus_connect_irq(pcihost, 0, qdev_get_gpio_in(dev, 15));

    sysbus_connect_irq(pcihost, 1, qdev_get_gpio_in(dev, 13));

    sysbus_connect_irq(pcihost, 2, qdev_get_gpio_in(dev, 15));

    sysbus_connect_irq(pcihost, 3, qdev_get_gpio_in(dev, 13));

    isa_bus = ISA_BUS(qdev_get_child_bus(dev, "isa.0"));

    /* Memory controller */

    dev = DEVICE(isa_create(isa_bus, "rs6000-mc"));

    qdev_prop_set_uint32(dev, "ram-size", machine->ram_size);

    qdev_init_nofail(dev);

    /* initialize CMOS checksums */

    cmos_checksum = 0x6aa9;

    qbus_walk_children(BUS(isa_bus), prep_set_cmos_checksum, NULL, NULL, NULL,

                       &cmos_checksum);

    /* add some more devices */

    if (defaults_enabled()) {

        isa_create_simple(isa_bus, "i8042");

        m48t59 = NVRAM(isa_create_simple(isa_bus, "isa-m48t59"));

        dev = DEVICE(isa_create(isa_bus, "cs4231a"));

        qdev_prop_set_uint32(dev, "iobase", 0x830);

        qdev_prop_set_uint32(dev, "irq", 10);

        qdev_init_nofail(dev);

        dev = DEVICE(isa_create(isa_bus, "pc87312"));

        qdev_prop_set_uint32(dev, "config", 12);

        qdev_init_nofail(dev);

        dev = DEVICE(isa_create(isa_bus, "prep-systemio"));

        qdev_prop_set_uint32(dev, "ibm-planar-id", 0xfc);

        qdev_prop_set_uint32(dev, "equipment", 0xc0);

        qdev_init_nofail(dev);

        pci_create_simple(pci_bus, PCI_DEVFN(1, 0), "lsi53c810");

        /* XXX: s3-trio at PCI_DEVFN(2, 0) */

        pci_vga_init(pci_bus);

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

            pci_nic_init_nofail(&nd_table[i], pci_bus, "pcnet",

                                i == 0 ? "3" : NULL);

        }

    }

    /* Prepare firmware configuration for OpenBIOS */

    fw_cfg = fw_cfg_init_mem(CFG_ADDR, CFG_ADDR + 2);

    if (machine->kernel_filename) {

        /* load kernel */

        kernel_base = KERNEL_LOAD_ADDR;

        kernel_size = load_image_targphys(machine->kernel_filename,

                                          kernel_base,

                                          machine->ram_size - kernel_base);

        if (kernel_size < 0) {

            error_report("could not load kernel '%s'",

                         machine->kernel_filename);

            exit(1);

        }

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

        /* load initrd */

        if (machine->initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(machine->initrd_filename,

                                              initrd_base,

                                              machine->ram_size - initrd_base);

            if (initrd_size < 0) {

                error_report("could not load initial ram disk '%s'",

                             machine->initrd_filename);

                exit(1);

            }

            fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_base);

            fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

        }

        if (machine->kernel_cmdline && *machine->kernel_cmdline) {

            fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, CMDLINE_ADDR);

            pstrcpy_targphys("cmdline", CMDLINE_ADDR, TARGET_PAGE_SIZE,

                             machine->kernel_cmdline);

            fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA,

                              machine->kernel_cmdline);

            fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,

                           strlen(machine->kernel_cmdline) + 1);

        }

        boot_device = 'm';

    } else {

        boot_device = machine->boot_order[0];

    }

    fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)machine->ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, ARCH_PREP);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_IS_KVM, kvm_enabled());

    if (kvm_enabled()) {

#ifdef CONFIG_KVM

        uint8_t *hypercall;

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, kvmppc_get_tbfreq());

        hypercall = g_malloc(16);

        kvmppc_get_hypercall(env, hypercall, 16);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16);

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid());

#endif

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, NANOSECONDS_PER_SECOND);

    }

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, boot_device);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

    /* Prepare firmware configuration for Open Hack'Ware */

    if (m48t59) {

        PPC_NVRAM_set_params(m48t59, NVRAM_SIZE, "PREP", ram_size,

                             boot_device,

                             kernel_base, kernel_size,

                             machine->kernel_cmdline,

                             initrd_base, initrd_size,

                             /* XXX: need an option to load a NVRAM image */

                             0,

                             graphic_width, graphic_height, graphic_depth);

    }

}


static void *iommu_init(target_phys_addr_t addr, uint32_t version, qemu_irq irq)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "iommu");

    qdev_prop_set_uint32(dev, "version", version);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_connect_irq(s, 0, irq);

    sysbus_mmio_map(s, 0, addr);

    return s;

}


static void test_qemu_strtoull_full_empty(void)

{

    const char *str = "";

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0);

}


static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst1, int16_t *dst2,

                                        int dstWidth, const uint8_t *src1,

                                        const uint8_t *src2, int srcW, int xInc)

{

    int32_t *filterPos = c->hChrFilterPos;

    int16_t *filter    = c->hChrFilter;

    void    *mmx2FilterCode= c->chrMmx2FilterCode;

    int i;

#if defined(PIC)

    DECLARE_ALIGNED(8, uint64_t, ebxsave);

#endif

    __asm__ volatile(

#if defined(PIC)

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

#endif

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

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

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

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

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

        "xor          %%"REG_a", %%"REG_a"  \n\t" // i

        PREFETCH"   (%%"REG_c")             \n\t"

        PREFETCH" 32(%%"REG_c")             \n\t"

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

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        "xor          %%"REG_a", %%"REG_a"  \n\t" // i

        "mov                 %5, %%"REG_c"  \n\t" // src

        "mov                 %6, %%"REG_D"  \n\t" // buf2

        PREFETCH"   (%%"REG_c")             \n\t"

        PREFETCH" 32(%%"REG_c")             \n\t"

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

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

#if defined(PIC)

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

#endif

        :: "m" (src1), "m" (dst1), "m" (filter), "m" (filterPos),

           "m" (mmx2FilterCode), "m" (src2), "m"(dst2)

#if defined(PIC)

          ,"m" (ebxsave)

#endif

        : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D

#if !defined(PIC)

         ,"%"REG_b

#endif

    );

    for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) {

        dst1[i] = src1[srcW-1]*128;

        dst2[i] = src2[srcW-1]*128;

    }

}


static void get_pointer(Object *obj, Visitor *v, Property *prop,

                        const char *(*print)(void *ptr),

                        const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    void **ptr = qdev_get_prop_ptr(dev, prop);

    char *p;

    p = (char *) (*ptr ? print(*ptr) : "");

    visit_type_str(v, &p, name, errp);

}


static uint64_t jazz_led_read(void *opaque, target_phys_addr_t addr,

                              unsigned int size)

{

    LedState *s = opaque;

    uint8_t val;

    val = s->segments;

    trace_jazz_led_read(addr, val);

    return val;

}


float32 HELPER(ucf64_divs)(float32 a, float32 b, CPUUniCore32State *env)

{

    return float32_div(a, b, &env->ucf64.fp_status);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);

    sc->realize      = scsi_generic_realize;

    sc->unrealize    = scsi_unrealize;

    sc->alloc_req    = scsi_new_request;

    sc->parse_cdb    = scsi_generic_parse_cdb;

    dc->fw_name = "disk";

    dc->desc = "pass through generic scsi device (/dev/sg*)";

    dc->reset = scsi_generic_reset;

    dc->props = scsi_generic_properties;

    dc->vmsd  = &vmstate_scsi_device;

}


START_TEST(qlist_destroy_test)

{

    int i;

    QList *qlist;

    qlist = qlist_new();

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

        qlist_append(qlist, qint_from_int(i));

    QDECREF(qlist);

}


static void vnc_client_read(void *opaque)

{

    VncState *vs = opaque;

    long ret;

    buffer_reserve(&vs->input, 4096);

#ifdef CONFIG_VNC_TLS

    if (vs->tls_session) {

	ret = gnutls_read(vs->tls_session, buffer_end(&vs->input), 4096);

	if (ret < 0) {

	    if (ret == GNUTLS_E_AGAIN)

		errno = EAGAIN;

	    else

		errno = EIO;

	    ret = -1;

	}

    } else

#endif /* CONFIG_VNC_TLS */

	ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);

    ret = vnc_client_io_error(vs, ret, socket_error());

    if (!ret)

	return;

    vs->input.offset += ret;

    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {

	size_t len = vs->read_handler_expect;

	int ret;

	ret = vs->read_handler(vs, vs->input.buffer, len);

	if (vs->csock == -1)

	    return;

	if (!ret) {

	    memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));

	    vs->input.offset -= len;

	} else {

	    vs->read_handler_expect = ret;

	}

    }

}


POWERPC_FAMILY(e5500)(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    dc->desc = "e5500 core";

    pcc->init_proc = init_proc_e5500;

    pcc->check_pow = check_pow_none;

    pcc->insns_flags = PPC_INSNS_BASE | PPC_ISEL |

                       PPC_WRTEE | PPC_RFDI | PPC_RFMCI |

                       PPC_CACHE | PPC_CACHE_LOCK | PPC_CACHE_ICBI |

                       PPC_CACHE_DCBZ | PPC_CACHE_DCBA |

                       PPC_FLOAT | PPC_FLOAT_FRES |

                       PPC_FLOAT_FRSQRTE | PPC_FLOAT_FSEL |

                       PPC_FLOAT_STFIWX | PPC_WAIT |

                       PPC_MEM_TLBSYNC | PPC_TLBIVAX | PPC_MEM_SYNC |

                       PPC_64B | PPC_POPCNTB | PPC_POPCNTWD;

    pcc->insns_flags2 = PPC2_BOOKE206 | PPC2_PRCNTL | PPC2_PERM_ISA206;

    pcc->msr_mask = (1ull << MSR_CM) |

                    (1ull << MSR_GS) |

                    (1ull << MSR_UCLE) |

                    (1ull << MSR_CE) |

                    (1ull << MSR_EE) |

                    (1ull << MSR_PR) |

                    (1ull << MSR_FP) |

                    (1ull << MSR_ME) |

                    (1ull << MSR_FE0) |

                    (1ull << MSR_DE) |

                    (1ull << MSR_FE1) |

                    (1ull << MSR_IR) |

                    (1ull << MSR_DR) |

                    (1ull << MSR_PX) |

                    (1ull << MSR_RI);

    pcc->mmu_model = POWERPC_MMU_BOOKE206;

    pcc->excp_model = POWERPC_EXCP_BOOKE;

    pcc->bus_model = PPC_FLAGS_INPUT_BookE;

    /* FIXME: figure out the correct flag for e5500 */

    pcc->bfd_mach = bfd_mach_ppc_e500;

    pcc->flags = POWERPC_FLAG_CE | POWERPC_FLAG_DE |

                 POWERPC_FLAG_PMM | POWERPC_FLAG_BUS_CLK;

}


void av_md5_update(AVMD5 *ctx, const uint8_t *src, int len)

{

    const uint8_t *end;

    int j;

    j = ctx->len & 63;

    ctx->len += len;

    if (j) {

        int cnt = FFMIN(len, 64 - j);

        memcpy(ctx->block + j, src, cnt);

        src += cnt;

        len -= cnt;

        if (j + cnt < 64)

            return;

        body(ctx->ABCD, (uint32_t *)ctx->block);

    }

    end = src + (len & ~63);

    if (HAVE_BIGENDIAN || (!HAVE_FAST_UNALIGNED && ((intptr_t)src & 3))) {

       while (src < end) {

           memcpy(ctx->block, src, 64);

           body(ctx->ABCD, (uint32_t *) ctx->block);

           src += 64;

        }

    } else {

        while (src < end) {

            body(ctx->ABCD, (uint32_t *)src);

            src += 64;

        }

    }

    len &= 63;

    if (len > 0)

        memcpy(ctx->block, src, len);

}


int main()

{

    int rt, rs;

    int achi, acli;

    int dsp;

    int acho, aclo;

    int resulth, resultl;

    int resdsp;

    achi = 0x05;

    acli = 0xB4CB;

    rs  = 0xFF06;

    rt  = 0xCB00;

    resulth = 0x04;

    resultl = 0x947438CB;

    __asm

        ("mthi %2, $ac1\n\t"

         "mtlo %3, $ac1\n\t"

         "maq_s.w.phr $ac1, %4, %5\n\t"

         "mfhi %0, $ac1\n\t"

         "mflo %1, $ac1\n\t"

         : "=r"(acho), "=r"(aclo)

         : "r"(achi), "r"(acli), "r"(rs), "r"(rt)

        );

    assert(resulth == acho);

    assert(resultl == aclo);

    achi = 0x06;

    acli = 0xB4CB;

    rs  = 0x8000;

    rt  = 0x8000;

    resulth = 0x6;

    resultl = 0x8000b4ca;

    resdsp = 1;

    __asm

        ("mthi %3, $ac1\n\t"

         "mtlo %4, $ac1\n\t"

         "maq_s.w.phr $ac1, %5, %6\n\t"

         "mfhi %0, $ac1\n\t"

         "mflo %1, $ac1\n\t"

         "rddsp %2\n\t"

         : "=r"(acho), "=r"(aclo), "=r"(dsp)

         : "r"(achi), "r"(acli), "r"(rs), "r"(rt)

        );

    assert(resulth == acho);

    assert(resultl == aclo);

    assert(((dsp >> 17) & 0x01) == resdsp);

    return 0;

}


int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,

                   const char *version, const char *serial)

{

    int cylinders, heads, secs;

    uint64_t nb_sectors;

    s->bs = bs;

    s->drive_kind = kind;

    bdrv_get_geometry(bs, &nb_sectors);

    bdrv_guess_geometry(bs, &cylinders, &heads, &secs);

    if (cylinders < 1 || cylinders > 16383) {

        error_report("cyls must be between 1 and 16383");

        return -1;

    }

    if (heads < 1 || heads > 16) {

        error_report("heads must be between 1 and 16");

        return -1;

    }

    if (secs < 1 || secs > 63) {

        error_report("secs must be between 1 and 63");

        return -1;

    }

    s->cylinders = cylinders;

    s->heads = heads;

    s->sectors = secs;

    s->nb_sectors = nb_sectors;

    /* The SMART values should be preserved across power cycles

       but they aren't.  */

    s->smart_enabled = 1;

    s->smart_autosave = 1;

    s->smart_errors = 0;

    s->smart_selftest_count = 0;

    if (kind == IDE_CD) {

        bdrv_set_dev_ops(bs, &ide_cd_block_ops, s);

        bdrv_set_buffer_alignment(bs, 2048);

    } else {

        if (!bdrv_is_inserted(s->bs)) {

            error_report("Device needs media, but drive is empty");

            return -1;

        }

        if (bdrv_is_read_only(bs)) {

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

            return -1;

        }

    }

    if (serial) {

        strncpy(s->drive_serial_str, serial, sizeof(s->drive_serial_str));

    } else {

        snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),

                 "QM%05d", s->drive_serial);

    }

    if (version) {

        pstrcpy(s->version, sizeof(s->version), version);

    } else {

        pstrcpy(s->version, sizeof(s->version), QEMU_VERSION);

    }

    ide_reset(s);

    bdrv_iostatus_enable(bs);

    return 0;

}


int subch_device_load(SubchDev *s, QEMUFile *f)

{

    SubchDev *old_s;

    Error *err = NULL;

    uint16_t old_schid = s->schid;

    uint16_t old_devno = s->devno;

    int i;

    s->cssid = qemu_get_byte(f);

    s->ssid = qemu_get_byte(f);

    s->schid = qemu_get_be16(f);

    s->devno = qemu_get_be16(f);

    if (s->devno != old_devno) {

        /* Only possible if machine < 2.7 (no css_dev_path) */

        error_setg(&err, "%x != %x", old_devno,  s->devno);

        error_append_hint(&err, "Devno mismatch, tried to load wrong section!"

                          " Likely reason: some sequences of plug and unplug"

                          " can break migration for machine versions prior to"

                          " 2.7 (known design flaw).\n");

        error_report_err(err);

        return -EINVAL;

    }

    /* Re-assign subch. */

    if (old_schid != s->schid) {

        old_s = channel_subsys.css[s->cssid]->sch_set[s->ssid]->sch[old_schid];

        /*

         * (old_s != s) means that some other device has its correct

         * subchannel already assigned (in load).

         */

        if (old_s == s) {

            css_subch_assign(s->cssid, s->ssid, old_schid, s->devno, NULL);

        }

        /* It's OK to re-assign without a prior de-assign. */

        css_subch_assign(s->cssid, s->ssid, s->schid, s->devno, s);

    }

    s->thinint_active = qemu_get_byte(f);

    /* SCHIB */

    /*     PMCW */

    s->curr_status.pmcw.intparm = qemu_get_be32(f);

    s->curr_status.pmcw.flags = qemu_get_be16(f);

    s->curr_status.pmcw.devno = qemu_get_be16(f);

    s->curr_status.pmcw.lpm = qemu_get_byte(f);

    s->curr_status.pmcw.pnom  = qemu_get_byte(f);

    s->curr_status.pmcw.lpum = qemu_get_byte(f);

    s->curr_status.pmcw.pim = qemu_get_byte(f);

    s->curr_status.pmcw.mbi = qemu_get_be16(f);

    s->curr_status.pmcw.pom = qemu_get_byte(f);

    s->curr_status.pmcw.pam = qemu_get_byte(f);

    qemu_get_buffer(f, s->curr_status.pmcw.chpid, 8);

    s->curr_status.pmcw.chars = qemu_get_be32(f);

    /*     SCSW */

    s->curr_status.scsw.flags = qemu_get_be16(f);

    s->curr_status.scsw.ctrl = qemu_get_be16(f);

    s->curr_status.scsw.cpa = qemu_get_be32(f);

    s->curr_status.scsw.dstat = qemu_get_byte(f);

    s->curr_status.scsw.cstat = qemu_get_byte(f);

    s->curr_status.scsw.count = qemu_get_be16(f);

    s->curr_status.mba = qemu_get_be64(f);

    qemu_get_buffer(f, s->curr_status.mda, 4);

    /* end SCHIB */

    qemu_get_buffer(f, s->sense_data, 32);

    s->channel_prog = qemu_get_be64(f);

    /* last cmd */

    s->last_cmd.cmd_code = qemu_get_byte(f);

    s->last_cmd.flags = qemu_get_byte(f);

    s->last_cmd.count = qemu_get_be16(f);

    s->last_cmd.cda = qemu_get_be32(f);

    s->last_cmd_valid = qemu_get_byte(f);

    s->id.reserved = qemu_get_byte(f);

    s->id.cu_type = qemu_get_be16(f);

    s->id.cu_model = qemu_get_byte(f);

    s->id.dev_type = qemu_get_be16(f);

    s->id.dev_model = qemu_get_byte(f);

    s->id.unused = qemu_get_byte(f);

    for (i = 0; i < ARRAY_SIZE(s->id.ciw); i++) {

        s->id.ciw[i].type = qemu_get_byte(f);

        s->id.ciw[i].command = qemu_get_byte(f);

        s->id.ciw[i].count = qemu_get_be16(f);

    }

    s->ccw_fmt_1 = qemu_get_byte(f);

    s->ccw_no_data_cnt = qemu_get_byte(f);

    /*

     * Hack alert. We don't migrate the channel subsystem status (no

     * device!), but we need to find out if the guest enabled mss/mcss-e.

     * If the subchannel is enabled, it certainly was able to access it,

     * so adjust the max_ssid/max_cssid values for relevant ssid/cssid

     * values. This is not watertight, but better than nothing.

     */

    if (s->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ENA) {

        if (s->ssid) {

            channel_subsys.max_ssid = MAX_SSID;

        }

        if (s->cssid != channel_subsys.default_cssid) {

            channel_subsys.max_cssid = MAX_CSSID;

        }

    }

    return 0;

}


void bdrv_init(void)

{

    module_call_init(MODULE_INIT_BLOCK);

}


void hmp_change(Monitor *mon, const QDict *qdict)

{

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

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

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

    Error *err = NULL;

    if (strcmp(device, "vnc") == 0 &&

            (strcmp(target, "passwd") == 0 ||

             strcmp(target, "password") == 0)) {

        if (!arg) {

            monitor_read_password(mon, hmp_change_read_arg, NULL);

            return;

        }

    }

    qmp_change(device, target, !!arg, arg, &err);

    if (error_is_type(err, QERR_DEVICE_ENCRYPTED)) {

        monitor_printf(mon, "%s (%s) is encrypted.\n",

                       error_get_field(err, "device"),

                       error_get_field(err, "filename"));

        if (!monitor_get_rs(mon)) {

            monitor_printf(mon,

                    "terminal does not support password prompting\n");

            error_free(err);

            return;

        }

        readline_start(monitor_get_rs(mon), "Password: ", 1,

                       cb_hmp_change_bdrv_pwd, err);

        return;

    }

    hmp_handle_error(mon, &err);

}


static void gen_loop(DisasContext *ctx, int r1, int32_t offset)

{

    int l1;

    l1 = gen_new_label();

    tcg_gen_subi_tl(cpu_gpr_a[r1], cpu_gpr_a[r1], 1);

    tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_gpr_a[r1], -1, l1);

    gen_goto_tb(ctx, 1, ctx->pc + offset);

    gen_set_label(l1);

    gen_goto_tb(ctx, 0, ctx->next_pc);

}


static void tight_send_compact_size(VncState *vs, size_t len)

{

    int lpc = 0;

    int bytes = 0;

    char buf[3] = {0, 0, 0};

    buf[bytes++] = len & 0x7F;

    if (len > 0x7F) {

        buf[bytes-1] |= 0x80;

        buf[bytes++] = (len >> 7) & 0x7F;

        if (len > 0x3FFF) {

            buf[bytes-1] |= 0x80;

            buf[bytes++] = (len >> 14) & 0xFF;

        }

    }

    for (lpc = 0; lpc < bytes; lpc++) {

        vnc_write_u8(vs, buf[lpc]);

    }

}


static inline void gen_evmwsmi(DisasContext *ctx)

{

    TCGv_i64 t0, t1;

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

    t0 = tcg_temp_new_i64();

    t1 = tcg_temp_new_i64();

    /* t0 := rA; t1 := rB */

#if defined(TARGET_PPC64)

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

    tcg_gen_ext32s_tl(t1, cpu_gpr[rB(ctx->opcode)]);

#else

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

    tcg_gen_ext_tl_i64(t1, cpu_gpr[rB(ctx->opcode)]);

#endif

    tcg_gen_mul_i64(t0, t0, t1);  /* t0 := rA * rB */

    gen_store_gpr64(rD(ctx->opcode), t0); /* rD := t0 */

    tcg_temp_free_i64(t0);

    tcg_temp_free_i64(t1);

}


static uint64_t subpage_ram_read(void *opaque, target_phys_addr_t addr,

                                 unsigned size)

{

    ram_addr_t raddr = addr;

    void *ptr = qemu_get_ram_ptr(raddr);

    switch (size) {

    case 1: return ldub_p(ptr);

    case 2: return lduw_p(ptr);

    case 4: return ldl_p(ptr);

    default: abort();

    }

}


static int xan_decode_init(AVCodecContext *avctx)

{

    XanContext *s = avctx->priv_data;

    int i;

    s->avctx = avctx;

    if ((avctx->codec->id == CODEC_ID_XAN_WC3) &&

        (s->avctx->palctrl == NULL)) {

        av_log(avctx, AV_LOG_ERROR, " WC3 Xan video: palette expected.\n");

        return -1;

    }

    avctx->pix_fmt = PIX_FMT_PAL8;

    avctx->has_b_frames = 0;

    dsputil_init(&s->dsp, avctx);

    /* initialize the RGB -> YUV tables */

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

        y_r_table[i] = Y_R * i;

        y_g_table[i] = Y_G * i;

        y_b_table[i] = Y_B * i;

        u_r_table[i] = U_R * i;

        u_g_table[i] = U_G * i;

        u_b_table[i] = U_B * i;

        v_r_table[i] = V_R * i;

        v_g_table[i] = V_G * i;

        v_b_table[i] = V_B * i;

    }

    if(avcodec_check_dimensions(avctx, avctx->width, avctx->height))

        return -1;

    s->buffer1 = av_malloc(avctx->width * avctx->height);

    s->buffer2 = av_malloc(avctx->width * avctx->height);

    if (!s->buffer1 || !s->buffer2)

        return -1;

    return 0;

}


void gen_intermediate_code_internal(XtensaCPU *cpu,

                                    TranslationBlock *tb, bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUXtensaState *env = &cpu->env;

    DisasContext dc;

    int insn_count = 0;

    int j, lj = -1;

    int max_insns = tb->cflags & CF_COUNT_MASK;

    uint32_t pc_start = tb->pc;

    uint32_t next_page_start =

        (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    dc.config = env->config;

    dc.singlestep_enabled = cs->singlestep_enabled;

    dc.tb = tb;

    dc.pc = pc_start;

    dc.ring = tb->flags & XTENSA_TBFLAG_RING_MASK;

    dc.cring = (tb->flags & XTENSA_TBFLAG_EXCM) ? 0 : dc.ring;

    dc.lbeg = env->sregs[LBEG];

    dc.lend = env->sregs[LEND];

    dc.is_jmp = DISAS_NEXT;

    dc.ccount_delta = 0;

    dc.debug = tb->flags & XTENSA_TBFLAG_DEBUG;

    dc.icount = tb->flags & XTENSA_TBFLAG_ICOUNT;

    dc.cpenable = (tb->flags & XTENSA_TBFLAG_CPENABLE_MASK) >>

        XTENSA_TBFLAG_CPENABLE_SHIFT;

    dc.window = ((tb->flags & XTENSA_TBFLAG_WINDOW_MASK) >>

                 XTENSA_TBFLAG_WINDOW_SHIFT);

    init_litbase(&dc);

    init_sar_tracker(&dc);

    if (dc.icount) {

        dc.next_icount = tcg_temp_local_new_i32();

    }

    gen_tb_start(tb);

    if (tb->flags & XTENSA_TBFLAG_EXCEPTION) {

        tcg_gen_movi_i32(cpu_pc, dc.pc);

        gen_exception(&dc, EXCP_DEBUG);

    }

    do {

        check_breakpoint(env, &dc);

        if (search_pc) {

            j = tcg_op_buf_count();

            if (lj < j) {

                lj++;

                while (lj < j) {

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

                }

            }

            tcg_ctx.gen_opc_pc[lj] = dc.pc;

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = insn_count;

        }

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

            tcg_gen_debug_insn_start(dc.pc);

        }

        ++dc.ccount_delta;

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

            gen_io_start();

        }

        if (dc.icount) {

            int label = gen_new_label();

            tcg_gen_addi_i32(dc.next_icount, cpu_SR[ICOUNT], 1);

            tcg_gen_brcondi_i32(TCG_COND_NE, dc.next_icount, 0, label);

            tcg_gen_mov_i32(dc.next_icount, cpu_SR[ICOUNT]);

            if (dc.debug) {

                gen_debug_exception(&dc, DEBUGCAUSE_IC);

            }

            gen_set_label(label);

        }

        if (dc.debug) {

            gen_ibreak_check(env, &dc);

        }

        disas_xtensa_insn(env, &dc);

        ++insn_count;

        if (dc.icount) {

            tcg_gen_mov_i32(cpu_SR[ICOUNT], dc.next_icount);

        }

        if (cs->singlestep_enabled) {

            tcg_gen_movi_i32(cpu_pc, dc.pc);

            gen_exception(&dc, EXCP_DEBUG);

            break;

        }

    } while (dc.is_jmp == DISAS_NEXT &&

            insn_count < max_insns &&

            dc.pc < next_page_start &&

            dc.pc + xtensa_insn_len(env, &dc) <= next_page_start &&

            !tcg_op_buf_full());

    reset_litbase(&dc);

    reset_sar_tracker(&dc);

    if (dc.icount) {

        tcg_temp_free(dc.next_icount);

    }

    if (tb->cflags & CF_LAST_IO) {

        gen_io_end();

    }

    if (dc.is_jmp == DISAS_NEXT) {

        gen_jumpi(&dc, dc.pc, 0);

    }

    gen_tb_end(tb, insn_count);

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

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

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

        log_target_disas(env, pc_start, dc.pc - pc_start, 0);

        qemu_log("\n");

    }

#endif

    if (search_pc) {

        j = tcg_op_buf_count();

        memset(tcg_ctx.gen_opc_instr_start + lj + 1, 0,

                (j - lj) * sizeof(tcg_ctx.gen_opc_instr_start[0]));

    } else {

        tb->size = dc.pc - pc_start;

        tb->icount = insn_count;

    }

}


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)

        // 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;

        }

    }

}


static target_ulong h_put_tce_indirect(PowerPCCPU *cpu,

                                       sPAPRMachineState *spapr,

                                       target_ulong opcode, target_ulong *args)

{

    int i;

    target_ulong liobn = args[0];

    target_ulong ioba = args[1];

    target_ulong ioba1 = ioba;

    target_ulong tce_list = args[2];

    target_ulong npages = args[3];

    target_ulong ret = H_PARAMETER, tce = 0;

    sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn);

    CPUState *cs = CPU(cpu);

    hwaddr page_mask, page_size;

    if (!tcet) {

        return H_PARAMETER;

    }

    if ((npages > 512) || (tce_list & SPAPR_TCE_PAGE_MASK)) {

        return H_PARAMETER;

    }

    page_mask = IOMMU_PAGE_MASK(tcet->page_shift);

    page_size = IOMMU_PAGE_SIZE(tcet->page_shift);

    ioba &= page_mask;

    for (i = 0; i < npages; ++i, ioba += page_size) {

        target_ulong off = (tce_list & ~SPAPR_TCE_RW) +

                                i * sizeof(target_ulong);

        tce = ldq_be_phys(cs->as, off);

        ret = put_tce_emu(tcet, ioba, tce);

        if (ret) {

            break;

        }

    }

    /* Trace last successful or the first problematic entry */

    i = i ? (i - 1) : 0;

    if (SPAPR_IS_PCI_LIOBN(liobn)) {

        trace_spapr_iommu_pci_indirect(liobn, ioba1, tce_list, i, tce, ret);

    } else {

        trace_spapr_iommu_indirect(liobn, ioba1, tce_list, i, tce, ret);

    }

    return ret;

}


ivshmem_server_parse_args(IvshmemServerArgs *args, int argc, char *argv[])

{

    int c;

    unsigned long long v;

    Error *errp = NULL;

    while ((c = getopt(argc, argv,

                       "h"  /* help */

                       "v"  /* verbose */

                       "F"  /* foreground */

                       "p:" /* pid_file */

                       "S:" /* unix_socket_path */

                       "m:" /* shm_path */

                       "l:" /* shm_size */

                       "n:" /* n_vectors */

                      )) != -1) {

        switch (c) {

        case 'h': /* help */

            ivshmem_server_usage(argv[0], 0);

            break;

        case 'v': /* verbose */

            args->verbose = 1;

            break;

        case 'F': /* foreground */

            args->foreground = 1;

            break;

        case 'p': /* pid_file */

            args->pid_file = strdup(optarg);

            break;

        case 'S': /* unix_socket_path */

            args->unix_socket_path = strdup(optarg);

            break;

        case 'm': /* shm_path */

            args->shm_path = strdup(optarg);

            break;

        case 'l': /* shm_size */

            parse_option_size("shm_size", optarg, &args->shm_size, &errp);

            if (errp) {

                fprintf(stderr, "cannot parse shm size: %s\n",

                        error_get_pretty(errp));

                error_free(errp);

                ivshmem_server_usage(argv[0], 1);

            }

            break;

        case 'n': /* n_vectors */

            if (parse_uint_full(optarg, &v, 0) < 0) {

                fprintf(stderr, "cannot parse n_vectors\n");

                ivshmem_server_usage(argv[0], 1);

            }

            args->n_vectors = v;

            break;

        default:

            ivshmem_server_usage(argv[0], 1);

            break;

        }

    }

    if (args->n_vectors > IVSHMEM_SERVER_MAX_VECTORS) {

        fprintf(stderr, "too many requested vectors (max is %d)\n",

                IVSHMEM_SERVER_MAX_VECTORS);

        ivshmem_server_usage(argv[0], 1);

    }

    if (args->verbose == 1 && args->foreground == 0) {

        fprintf(stderr, "cannot use verbose in daemon mode\n");

        ivshmem_server_usage(argv[0], 1);

    }

}


static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,

                                 Error **errp)

{

    uint32_t flags;

    bool fixedNewstyle = false;

    bool no_zeroes = false;

    /* Client sends:

        [ 0 ..   3]   client flags

       Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   NBD option

        [12 ..  15]   Data length

        ...           Rest of request

        [ 0 ..   7]   NBD_OPTS_MAGIC

        [ 8 ..  11]   Second NBD option

        [12 ..  15]   Data length

        ...           Rest of request

    */

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

        error_prepend(errp, "read failed: ");

        return -EIO;

    }

    be32_to_cpus(&flags);

    trace_nbd_negotiate_options_flags(flags);

    if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {

        fixedNewstyle = true;

        flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;

    }

    if (flags & NBD_FLAG_C_NO_ZEROES) {

        no_zeroes = true;

        flags &= ~NBD_FLAG_C_NO_ZEROES;

    }

    if (flags != 0) {

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

        return -EINVAL;

    }

    while (1) {

        int ret;

        uint32_t option, length;

        uint64_t magic;

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

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        magic = be64_to_cpu(magic);

        trace_nbd_negotiate_options_check_magic(magic);

        if (magic != NBD_OPTS_MAGIC) {

            error_setg(errp, "Bad magic received");

            return -EINVAL;

        }

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

                     sizeof(option), errp) < 0) {

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        option = be32_to_cpu(option);

        client->opt = option;

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

            error_prepend(errp, "read failed: ");

            return -EINVAL;

        }

        length = be32_to_cpu(length);

        client->optlen = length;

        if (length > NBD_MAX_BUFFER_SIZE) {

            error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",

                       length, NBD_MAX_BUFFER_SIZE);

            return -EINVAL;

        }

        trace_nbd_negotiate_options_check_option(option,

                                                 nbd_opt_lookup(option));

        if (client->tlscreds &&

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

            QIOChannel *tioc;

            if (!fixedNewstyle) {

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

                return -EINVAL;

            }

            switch (option) {

            case NBD_OPT_STARTTLS:

                if (length) {

                    /* Unconditionally drop the connection if the client

                     * can't start a TLS negotiation correctly */

                    return nbd_reject_length(client, true, errp);

                }

                tioc = nbd_negotiate_handle_starttls(client, errp);

                if (!tioc) {

                    return -EIO;

                }

                ret = 0;

                object_unref(OBJECT(client->ioc));

                client->ioc = QIO_CHANNEL(tioc);

                break;

            case NBD_OPT_EXPORT_NAME:

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

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

                           option);

                return -EINVAL;

            default:

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

                    return -EIO;

                }

                ret = nbd_negotiate_send_rep_err(client,

                                                 NBD_REP_ERR_TLS_REQD, errp,

                                                 "Option 0x%" PRIx32

                                                 "not permitted before TLS",

                                                 option);

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

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

                 * we can't ack the abort.  */

                if (option == NBD_OPT_ABORT) {

                    return 1;

                }

                break;

            }

        } else if (fixedNewstyle) {

            switch (option) {

            case NBD_OPT_LIST:

                if (length) {

                    ret = nbd_reject_length(client, false, errp);

                } else {

                    ret = nbd_negotiate_handle_list(client, errp);

                }

                break;

            case NBD_OPT_ABORT:

                /* NBD spec says we must try to reply before

                 * disconnecting, but that we must also tolerate

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

                nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);

                return 1;

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client,

                                                        myflags, no_zeroes,

                                                        errp);

            case NBD_OPT_INFO:

            case NBD_OPT_GO:

                ret = nbd_negotiate_handle_info(client, myflags, errp);

                if (ret == 1) {

                    assert(option == NBD_OPT_GO);

                    return 0;

                }

                break;

            case NBD_OPT_STARTTLS:

                if (length) {

                    ret = nbd_reject_length(client, false, errp);

                } else if (client->tlscreds) {

                    ret = nbd_negotiate_send_rep_err(client,

                                                     NBD_REP_ERR_INVALID, errp,

                                                     "TLS already enabled");

                } else {

                    ret = nbd_negotiate_send_rep_err(client,

                                                     NBD_REP_ERR_POLICY, errp,

                                                     "TLS not configured");

                }

                break;

            case NBD_OPT_STRUCTURED_REPLY:

                if (length) {

                    ret = nbd_reject_length(client, false, errp);

                } else if (client->structured_reply) {

                    ret = nbd_negotiate_send_rep_err(

                        client, NBD_REP_ERR_INVALID, errp,

                        "structured reply already negotiated");

                } else {

                    ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);

                    client->structured_reply = true;

                    myflags |= NBD_FLAG_SEND_DF;

                }

                break;

            default:

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

                    return -EIO;

                }

                ret = nbd_negotiate_send_rep_err(client,

                                                 NBD_REP_ERR_UNSUP, errp,

                                                 "Unsupported option 0x%"

                                                 PRIx32 " (%s)", option,

                                                 nbd_opt_lookup(option));

                break;

            }

        } else {

            /*

             * If broken new-style we should drop the connection

             * for anything except NBD_OPT_EXPORT_NAME

             */

            switch (option) {

            case NBD_OPT_EXPORT_NAME:

                return nbd_negotiate_handle_export_name(client,

                                                        myflags, no_zeroes,

                                                        errp);

            default:

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

                           option, nbd_opt_lookup(option));

                return -EINVAL;

            }

        }

        if (ret < 0) {

            return ret;

        }

    }

}