int v9fs_device_realize_common(V9fsState *s, Error **errp)

{

    V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);

    int i, len;

    struct stat stat;

    FsDriverEntry *fse;

    V9fsPath path;

    int rc = 1;

    /* initialize pdu allocator */

    QLIST_INIT(&s->free_list);

    QLIST_INIT(&s->active_list);

    for (i = 0; i < (MAX_REQ - 1); i++) {

        QLIST_INSERT_HEAD(&s->free_list, &v->pdus[i], next);

        v->pdus[i].s = s;

        v->pdus[i].idx = i;

    }

    v9fs_path_init(&path);

    fse = get_fsdev_fsentry(s->fsconf.fsdev_id);

    if (!fse) {

        /* We don't have a fsdev identified by fsdev_id */

        error_setg(errp, "9pfs device couldn't find fsdev with the "

                   "id = %s",

                   s->fsconf.fsdev_id ? s->fsconf.fsdev_id : "NULL");

        goto out;

    }

    if (!s->fsconf.tag) {

        /* we haven't specified a mount_tag */

        error_setg(errp, "fsdev with id %s needs mount_tag arguments",

                   s->fsconf.fsdev_id);

        goto out;

    }

    s->ctx.export_flags = fse->export_flags;

    s->ctx.fs_root = g_strdup(fse->path);

    s->ctx.exops.get_st_gen = NULL;

    len = strlen(s->fsconf.tag);

    if (len > MAX_TAG_LEN - 1) {

        error_setg(errp, "mount tag '%s' (%d bytes) is longer than "

                   "maximum (%d bytes)", s->fsconf.tag, len, MAX_TAG_LEN - 1);

        goto out;

    }

    s->tag = g_strdup(s->fsconf.tag);

    s->ctx.uid = -1;

    s->ops = fse->ops;

    s->fid_list = NULL;

    qemu_co_rwlock_init(&s->rename_lock);

    if (s->ops->init(&s->ctx) < 0) {

        error_setg(errp, "9pfs Failed to initialize fs-driver with id:%s"

                   " and export path:%s", s->fsconf.fsdev_id, s->ctx.fs_root);

        goto out;

    }

    /*

     * Check details of export path, We need to use fs driver

     * call back to do that. Since we are in the init path, we don't

     * use co-routines here.

     */

    if (s->ops->name_to_path(&s->ctx, NULL, "/", &path) < 0) {

        error_setg(errp,

                   "error in converting name to path %s", strerror(errno));

        goto out;

    }

    if (s->ops->lstat(&s->ctx, &path, &stat)) {

        error_setg(errp, "share path %s does not exist", fse->path);

        goto out;

    } else if (!S_ISDIR(stat.st_mode)) {

        error_setg(errp, "share path %s is not a directory", fse->path);

        goto out;

    }

    v9fs_path_free(&path);

    rc = 0;

out:

    if (rc) {

        if (s->ops->cleanup && s->ctx.private) {

            s->ops->cleanup(&s->ctx);

        }

        g_free(s->tag);

        g_free(s->ctx.fs_root);

        v9fs_path_free(&path);

    }

    return rc;

}


static void pc_compat_1_6(MachineState *machine)

{

    pc_compat_1_7(machine);

    rom_file_has_mr = false;

    has_acpi_build = false;

}


static void __attribute__((destructor)) coroutine_cleanup(void)

{

    Coroutine *co;

    Coroutine *tmp;

    QSLIST_FOREACH_SAFE(co, &pool, pool_next, tmp) {

        QSLIST_REMOVE_HEAD(&pool, pool_next);

        qemu_coroutine_delete(co);

    }

}


int qemu_acl_party_is_allowed(qemu_acl *acl,

                              const char *party)

{

    qemu_acl_entry *entry;

    TAILQ_FOREACH(entry, &acl->entries, next) {

#ifdef CONFIG_FNMATCH

        if (fnmatch(entry->match, party, 0) == 0)

            return entry->deny ? 0 : 1;

#else

        /* No fnmatch, so fallback to exact string matching

         * instead of allowing wildcards */

        if (strcmp(entry->match, party) == 0)

            return entry->deny ? 0 : 1;

#endif

    }

    return acl->defaultDeny ? 0 : 1;

}


static void tcg_out_ld_abs(TCGContext *s, TCGType type, TCGReg dest, void *abs)

{

    intptr_t addr = (intptr_t)abs;

    if ((facilities & FACILITY_GEN_INST_EXT) && !(addr & 1)) {

        ptrdiff_t disp = tcg_pcrel_diff(s, abs) >> 1;

        if (disp == (int32_t)disp) {

            if (type == TCG_TYPE_I32) {

                tcg_out_insn(s, RIL, LRL, dest, disp);

            } else {

                tcg_out_insn(s, RIL, LGRL, dest, disp);

            }

            return;

        }

    }

    tcg_out_movi(s, TCG_TYPE_PTR, dest, addr & ~0xffff);

    tcg_out_ld(s, type, dest, dest, addr & 0xffff);

}


static void v9fs_wstat(void *opaque)

{

    int32_t fid;

    int err = 0;

    int16_t unused;

    V9fsStat v9stat;

    size_t offset = 7;

    struct stat stbuf;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dwS", &fid, &unused, &v9stat);

    trace_v9fs_wstat(pdu->tag, pdu->id, fid,

                     v9stat.mode, v9stat.atime, v9stat.mtime);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /* do we need to sync the file? */

    if (donttouch_stat(&v9stat)) {

        err = v9fs_co_fsync(pdu, fidp, 0);

        goto out;

    }

    if (v9stat.mode != -1) {

        uint32_t v9_mode;

        err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

        if (err < 0) {

            goto out;

        }

        v9_mode = stat_to_v9mode(&stbuf);

        if ((v9stat.mode & P9_STAT_MODE_TYPE_BITS) !=

            (v9_mode & P9_STAT_MODE_TYPE_BITS)) {

            /* Attempting to change the type */

            err = -EIO;

            goto out;

        }

        err = v9fs_co_chmod(pdu, &fidp->path,

                            v9mode_to_mode(v9stat.mode,

                                           &v9stat.extension));

        if (err < 0) {

            goto out;

        }

    }

    if (v9stat.mtime != -1 || v9stat.atime != -1) {

        struct timespec times[2];

        if (v9stat.atime != -1) {

            times[0].tv_sec = v9stat.atime;

            times[0].tv_nsec = 0;

        } else {

            times[0].tv_nsec = UTIME_OMIT;

        }

        if (v9stat.mtime != -1) {

            times[1].tv_sec = v9stat.mtime;

            times[1].tv_nsec = 0;

        } else {

            times[1].tv_nsec = UTIME_OMIT;

        }

        err = v9fs_co_utimensat(pdu, &fidp->path, times);

        if (err < 0) {

            goto out;

        }

    }

    if (v9stat.n_gid != -1 || v9stat.n_uid != -1) {

        err = v9fs_co_chown(pdu, &fidp->path, v9stat.n_uid, v9stat.n_gid);

        if (err < 0) {

            goto out;

        }

    }

    if (v9stat.name.size != 0) {

        err = v9fs_complete_rename(pdu, fidp, -1, &v9stat.name);

        if (err < 0) {

            goto out;

        }

    }

    if (v9stat.length != -1) {

        err = v9fs_co_truncate(pdu, &fidp->path, v9stat.length);

        if (err < 0) {

            goto out;

        }

    }

    err = offset;

out:

    put_fid(pdu, fidp);

out_nofid:

    v9fs_stat_free(&v9stat);

    complete_pdu(s, pdu, err);

}


static void drive_backup_prepare(BlkTransactionState *common, Error **errp)

{

    DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);

    BlockBackend *blk;

    DriveBackup *backup;

    Error *local_err = NULL;

    assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);

    backup = common->action->drive_backup;

    blk = blk_by_name(backup->device);

    if (!blk) {

        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,

                  "Device '%s' not found", backup->device);

        return;

    }

    /* AioContext is released in .clean() */

    state->aio_context = blk_get_aio_context(blk);

    aio_context_acquire(state->aio_context);

    qmp_drive_backup(backup->device, backup->target,

                     backup->has_format, backup->format,

                     backup->sync,

                     backup->has_mode, backup->mode,

                     backup->has_speed, backup->speed,

                     backup->has_bitmap, backup->bitmap,

                     backup->has_on_source_error, backup->on_source_error,

                     backup->has_on_target_error, backup->on_target_error,

                     &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    state->bs = blk_bs(blk);

    state->job = state->bs->job;

}


void helper_ltr_T0(void)

{

    int selector;

    SegmentCache *dt;

    uint32_t e1, e2;

    int index, type, entry_limit;

    target_ulong ptr;

    selector = T0 & 0xffff;

    if ((selector & 0xfffc) == 0) {

        /* NULL selector case: invalid TR */

        env->tr.base = 0;

        env->tr.limit = 0;

        env->tr.flags = 0;

    } else {

        if (selector & 0x4)

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        dt = &env->gdt;

        index = selector & ~7;

#ifdef TARGET_X86_64

        if (env->hflags & HF_LMA_MASK)

            entry_limit = 15;

        else

#endif

            entry_limit = 7;

        if ((index + entry_limit) > dt->limit)

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        ptr = dt->base + index;

        e1 = ldl_kernel(ptr);

        e2 = ldl_kernel(ptr + 4);

        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;

        if ((e2 & DESC_S_MASK) ||

            (type != 1 && type != 9))

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        if (!(e2 & DESC_P_MASK))

            raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);

#ifdef TARGET_X86_64

        if (env->hflags & HF_LMA_MASK) {

            uint32_t e3;

            e3 = ldl_kernel(ptr + 8);

            load_seg_cache_raw_dt(&env->tr, e1, e2);

            env->tr.base |= (target_ulong)e3 << 32;

        } else

#endif

        {

            load_seg_cache_raw_dt(&env->tr, e1, e2);

        }

        e2 |= DESC_TSS_BUSY_MASK;

        stl_kernel(ptr + 4, e2);

    }

    env->tr.selector = selector;

}


static void uhci_async_cancel_device(UHCIState *s, USBDevice *dev)

{

    UHCIQueue *queue;

    UHCIAsync *curr, *n;

    QTAILQ_FOREACH(queue, &s->queues, next) {

        QTAILQ_FOREACH_SAFE(curr, &queue->asyncs, next, n) {

            if (!usb_packet_is_inflight(&curr->packet) ||

                curr->packet.ep->dev != dev) {

                continue;

            }

            uhci_async_cancel(curr);

        }

    }

}


static int dnxhd_decode_macroblock(DNXHDContext *ctx, AVFrame *frame,

                                   int x, int y)

{

    int shift1 = ctx->bit_depth == 10;

    int dct_linesize_luma   = frame->linesize[0];

    int dct_linesize_chroma = frame->linesize[1];

    uint8_t *dest_y, *dest_u, *dest_v;

    int dct_y_offset, dct_x_offset;

    int qscale, i;

    qscale = get_bits(&ctx->gb, 11);

    skip_bits1(&ctx->gb);

    if (qscale != ctx->last_qscale) {

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

            ctx->luma_scale[i]   = qscale * ctx->cid_table->luma_weight[i];

            ctx->chroma_scale[i] = qscale * ctx->cid_table->chroma_weight[i];

        }

        ctx->last_qscale = qscale;

    }

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

        ctx->bdsp.clear_block(ctx->blocks[i]);

        ctx->decode_dct_block(ctx, ctx->blocks[i], i, qscale);

    }

    if (ctx->is_444) {

        for (; i < 12; i++) {

            ctx->bdsp.clear_block(ctx->blocks[i]);

            ctx->decode_dct_block(ctx, ctx->blocks[i], i, qscale);

        }

    }

    if (frame->interlaced_frame) {

        dct_linesize_luma   <<= 1;

        dct_linesize_chroma <<= 1;

    }

    dest_y = frame->data[0] + ((y * dct_linesize_luma)   << 4) + (x << (4 + shift1));

    dest_u = frame->data[1] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));

    dest_v = frame->data[2] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));

    if (ctx->cur_field) {

        dest_y += frame->linesize[0];

        dest_u += frame->linesize[1];

        dest_v += frame->linesize[2];

    }

    dct_y_offset = dct_linesize_luma << 3;

    dct_x_offset = 8 << shift1;

    if (!ctx->is_444) {

        ctx->idsp.idct_put(dest_y,                               dct_linesize_luma, ctx->blocks[0]);

        ctx->idsp.idct_put(dest_y + dct_x_offset,                dct_linesize_luma, ctx->blocks[1]);

        ctx->idsp.idct_put(dest_y + dct_y_offset,                dct_linesize_luma, ctx->blocks[4]);

        ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, ctx->blocks[5]);

        if (!(ctx->avctx->flags & CODEC_FLAG_GRAY)) {

            dct_y_offset = dct_linesize_chroma << 3;

            ctx->idsp.idct_put(dest_u,                dct_linesize_chroma, ctx->blocks[2]);

            ctx->idsp.idct_put(dest_v,                dct_linesize_chroma, ctx->blocks[3]);

            ctx->idsp.idct_put(dest_u + dct_y_offset, dct_linesize_chroma, ctx->blocks[6]);

            ctx->idsp.idct_put(dest_v + dct_y_offset, dct_linesize_chroma, ctx->blocks[7]);

        }

    } else {

        ctx->idsp.idct_put(dest_y,                               dct_linesize_luma, ctx->blocks[0]);

        ctx->idsp.idct_put(dest_y + dct_x_offset,                dct_linesize_luma, ctx->blocks[1]);

        ctx->idsp.idct_put(dest_y + dct_y_offset,                dct_linesize_luma, ctx->blocks[6]);

        ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, ctx->blocks[7]);

        if (!(ctx->avctx->flags & CODEC_FLAG_GRAY)) {

            dct_y_offset = dct_linesize_chroma << 3;

            ctx->idsp.idct_put(dest_u,                               dct_linesize_chroma, ctx->blocks[2]);

            ctx->idsp.idct_put(dest_u + dct_x_offset,                dct_linesize_chroma, ctx->blocks[3]);

            ctx->idsp.idct_put(dest_u + dct_y_offset,                dct_linesize_chroma, ctx->blocks[8]);

            ctx->idsp.idct_put(dest_u + dct_y_offset + dct_x_offset, dct_linesize_chroma, ctx->blocks[9]);

            ctx->idsp.idct_put(dest_v,                               dct_linesize_chroma, ctx->blocks[4]);

            ctx->idsp.idct_put(dest_v + dct_x_offset,                dct_linesize_chroma, ctx->blocks[5]);

            ctx->idsp.idct_put(dest_v + dct_y_offset,                dct_linesize_chroma, ctx->blocks[10]);

            ctx->idsp.idct_put(dest_v + dct_y_offset + dct_x_offset, dct_linesize_chroma, ctx->blocks[11]);

        }

    }

    return 0;

}


static void apply_loop_filter(Vp3DecodeContext *s)

{

    int x, y, plane;

    int width, height;

    int fragment;

    int stride;

    unsigned char *plane_data;

    int bounding_values_array[256];

    int *bounding_values= bounding_values_array+127;

    int filter_limit;

    /* find the right loop limit value */

    for (x = 63; x >= 0; x--) {

        if (vp31_ac_scale_factor[x] >= s->quality_index)

            break;

    }

    filter_limit = vp31_filter_limit_values[s->quality_index];

    /* set up the bounding values */

    memset(bounding_values_array, 0, 256 * sizeof(int));

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

        bounding_values[-x - filter_limit] = -filter_limit + x;

        bounding_values[-x] = -x;

        bounding_values[x] = x;

        bounding_values[x + filter_limit] = filter_limit - x;

    }

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

        if (plane == 0) {

            /* Y plane parameters */

            fragment = 0;

            width = s->fragment_width;

            height = s->fragment_height;

            stride = s->current_frame.linesize[0];

            plane_data = s->current_frame.data[0];

        } else if (plane == 1) {

            /* U plane parameters */

            fragment = s->u_fragment_start;

            width = s->fragment_width / 2;

            height = s->fragment_height / 2;

            stride = s->current_frame.linesize[1];

            plane_data = s->current_frame.data[1];

        } else {

            /* V plane parameters */

            fragment = s->v_fragment_start;

            width = s->fragment_width / 2;

            height = s->fragment_height / 2;

            stride = s->current_frame.linesize[2];

            plane_data = s->current_frame.data[2];

        }

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

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

START_TIMER

                /* do not perform left edge filter for left columns frags */

                if ((x > 0) &&

                    (s->all_fragments[fragment].coding_method != MODE_COPY)) {

                    horizontal_filter(

                        plane_data + s->all_fragments[fragment].first_pixel - 7*stride,

                        stride, bounding_values);

                }

                /* do not perform top edge filter for top row fragments */

                if ((y > 0) &&

                    (s->all_fragments[fragment].coding_method != MODE_COPY)) {

                    vertical_filter(

                        plane_data + s->all_fragments[fragment].first_pixel + stride,

                        stride, bounding_values);

                }

                /* do not perform right edge filter for right column

                 * fragments or if right fragment neighbor is also coded

                 * in this frame (it will be filtered in next iteration) */

                if ((x < width - 1) &&

                    (s->all_fragments[fragment].coding_method != MODE_COPY) &&

                    (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {

                    horizontal_filter(

                        plane_data + s->all_fragments[fragment + 1].first_pixel - 7*stride,

                        stride, bounding_values);

                }

                /* do not perform bottom edge filter for bottom row

                 * fragments or if bottom fragment neighbor is also coded

                 * in this frame (it will be filtered in the next row) */

                if ((y < height - 1) &&

                    (s->all_fragments[fragment].coding_method != MODE_COPY) &&

                    (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {

                    vertical_filter(

                        plane_data + s->all_fragments[fragment + width].first_pixel + stride,

                        stride, bounding_values);

                }

                fragment++;

STOP_TIMER("loop filter")

            }

        }

    }

}


static int vt82c686b_ide_initfn(PCIDevice *dev)

{

    PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, dev);;

    uint8_t *pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_VIA);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_VIA_IDE);

    pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_IDE);

    pci_config_set_prog_interface(pci_conf, 0x8a); /* legacy ATA mode */

    pci_config_set_revision(pci_conf,0x06); /* Revision 0.6 */

    pci_set_long(pci_conf + PCI_CAPABILITY_LIST, 0x000000c0);

    qemu_register_reset(via_reset, d);

    pci_register_bar(&d->dev, 4, 0x10,

                           PCI_BASE_ADDRESS_SPACE_IO, bmdma_map);

    vmstate_register(&dev->qdev, 0, &vmstate_ide_pci, d);

    vt82c686b_init_ports(d);

    return 0;

}


void set_numa_modes(void)

{

    CPUArchState *env;

    int i;

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

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

            if (node_cpumask[i] & (1 << env->cpu_index)) {

                env->numa_node = i;

            }

        }

    }

}


static void omap_mcbsp_writew(void *opaque, hwaddr addr,

                uint32_t value)

{

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

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (offset == 0x04) {				/* DXR */

        if (((s->xcr[0] >> 5) & 7) < 3)			/* XWDLEN1 */

            return;

        if (s->tx_req > 3) {

            s->tx_req -= 4;

            if (s->codec && s->codec->cts) {

                s->codec->out.fifo[s->codec->out.len ++] =

                        (value >> 24) & 0xff;

                s->codec->out.fifo[s->codec->out.len ++] =

                        (value >> 16) & 0xff;

                s->codec->out.fifo[s->codec->out.len ++] =

                        (value >> 8) & 0xff;

                s->codec->out.fifo[s->codec->out.len ++] =

                        (value >> 0) & 0xff;

            }

            if (s->tx_req < 4)

                omap_mcbsp_tx_done(s);

        } else

            printf("%s: Tx FIFO overrun\n", __FUNCTION__);

        return;

    }

    omap_badwidth_write16(opaque, addr, value);

}


static void fcse_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    if (env->cp15.c13_fcse != value) {

        /* Unlike real hardware the qemu TLB uses virtual addresses,

         * not modified virtual addresses, so this causes a TLB flush.

         */

        tlb_flush(CPU(cpu), 1);

        env->cp15.c13_fcse = value;

    }

}


static void bw_io_write(void *opaque, target_phys_addr_t addr,

                        uint64_t val, unsigned size)

{

    switch (size) {

    case 1:

        cpu_outb(addr, val);

        break;

    case 2:

        cpu_outw(addr, val);

        break;

    case 4:

        cpu_outl(addr, val);

        break;

    default:

        abort();

    }

}


static void check_watchpoint(int offset, int len, int flags)

{

    CPUState *cpu = current_cpu;

    CPUArchState *env = cpu->env_ptr;

    target_ulong pc, cs_base;

    target_ulong vaddr;

    CPUWatchpoint *wp;

    int cpu_flags;

    if (cpu->watchpoint_hit) {

        /* We re-entered the check after replacing the TB. Now raise

         * the debug interrupt so that is will trigger after the

         * current instruction. */

        cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);

        return;

    }

    vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;

    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {

        if (cpu_watchpoint_address_matches(wp, vaddr, len)

            && (wp->flags & flags)) {

            wp->flags |= BP_WATCHPOINT_HIT;

            if (!cpu->watchpoint_hit) {

                cpu->watchpoint_hit = wp;

                tb_check_watchpoint(cpu);

                if (wp->flags & BP_STOP_BEFORE_ACCESS) {

                    cpu->exception_index = EXCP_DEBUG;

                    cpu_loop_exit(cpu);

                } else {

                    cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);

                    tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);

                    cpu_resume_from_signal(cpu, NULL);

                }

            }

        } else {

            wp->flags &= ~BP_WATCHPOINT_HIT;

        }

    }

}


static void *qpa_thread_in (void *arg)

{

    PAVoiceIn *pa = arg;

    HWVoiceIn *hw = &pa->hw;

    int threshold;

    threshold = conf.divisor ? hw->samples / conf.divisor : 0;

    if (audio_pt_lock (&pa->pt, AUDIO_FUNC)) {

        return NULL;

    }

    for (;;) {

        int incr, to_grab, wpos;

        for (;;) {

            if (pa->done) {

                goto exit;

            }

            if (pa->dead > threshold) {

                break;

            }

            if (audio_pt_wait (&pa->pt, AUDIO_FUNC)) {

                goto exit;

            }

        }

        incr = to_grab = pa->dead;

        wpos = hw->wpos;

        if (audio_pt_unlock (&pa->pt, AUDIO_FUNC)) {

            return NULL;

        }

        while (to_grab) {

            int error;

            int chunk = audio_MIN (to_grab, hw->samples - wpos);

            void *buf = advance (pa->pcm_buf, wpos);

            if (pa_simple_read (pa->s, buf,

                                chunk << hw->info.shift, &error) < 0) {

                qpa_logerr (error, "pa_simple_read failed\n");

                return NULL;

            }

            hw->conv (hw->conv_buf + wpos, buf, chunk);

            wpos = (wpos + chunk) % hw->samples;

            to_grab -= chunk;

        }

        if (audio_pt_lock (&pa->pt, AUDIO_FUNC)) {

            return NULL;

        }

        pa->wpos = wpos;

        pa->dead -= incr;

        pa->incr += incr;

    }

 exit:

    audio_pt_unlock (&pa->pt, AUDIO_FUNC);

    return NULL;

}


void check_file_unfixed_eof_mmaps(void)

{

	char *cp;

	unsigned int *p1;

	uintptr_t p;

	int i;

	fprintf (stderr, "%s", __func__);

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

	{

		p1 = mmap(NULL, pagesize, PROT_READ,

			  MAP_PRIVATE,

			  test_fd,

			  (test_fsize - sizeof *p1) & ~pagemask);

		fail_unless (p1 != MAP_FAILED);

		/* Make sure we get pages aligned with the pagesize. The

		   target expects this.  */

		p = (uintptr_t) p1;

		fail_unless ((p & pagemask) == 0);

		/* Verify that the file maps was made correctly.  */

		fail_unless (p1[(test_fsize & pagemask) / sizeof *p1 - 1]

			     == ((test_fsize - sizeof *p1) / sizeof *p1));

		/* Verify that the end of page is accessable and zeroed.  */

		cp = (void *) p1;

		fail_unless (cp[pagesize - 4] == 0);

		munmap (p1, pagesize);

	}

	fprintf (stderr, " passed\n");

}


static int64_t update_scr(AVFormatContext *ctx,int stream_index,int64_t pts)

{

    MpegMuxContext *s = ctx->priv_data;

    int64_t scr;

    if (s->is_vcd)

        /* Since the data delivery rate is constant, SCR is computed

           using the formula C + i * 1200 where C is the start constant

           and i is the pack index.

           It is recommended that SCR 0 is at the beginning of the VCD front

           margin (a sequence of empty Form 2 sectors on the CD).

           It is recommended that the front margin is 30 sectors long, so

           we use C = 30*1200 = 36000

           (Note that even if the front margin is not 30 sectors the file

           will still be correct according to the standard. It just won't have

           the "recommended" value).*/

        scr = 36000 + s->packet_number * 1200;

    else {

        /* XXX I believe this calculation of SCR is wrong. SCR

           specifies at which time the data should enter the decoder.

           Two packs cannot enter the decoder at the same time. */

        /* XXX: system clock should be computed precisely, especially for

        CBR case. The current mode gives at least something coherent */

        if (stream_index == s->scr_stream_index

            && pts != AV_NOPTS_VALUE)

            scr = pts;

        else

            scr = s->last_scr;

    }

    s->last_scr=scr;

    return scr;

}


static int decode_micromips_opc (CPUMIPSState *env, DisasContext *ctx)

{

    uint32_t op;

    /* make sure instructions are on a halfword boundary */

    if (ctx->pc & 0x1) {

        env->CP0_BadVAddr = ctx->pc;

        generate_exception(ctx, EXCP_AdEL);

        ctx->bstate = BS_STOP;

        return 2;

    }

    op = (ctx->opcode >> 10) & 0x3f;

    /* Enforce properly-sized instructions in a delay slot */

    if (ctx->hflags & MIPS_HFLAG_BDS_STRICT) {

        switch (op & 0x7) { /* MSB-3..MSB-5 */

        case 0:

        /* POOL32A, POOL32B, POOL32I, POOL32C */

        case 4:

        /* ADDI32, ADDIU32, ORI32, XORI32, SLTI32, SLTIU32, ANDI32, JALX32 */

        case 5:

        /* LBU32, LHU32, POOL32F, JALS32, BEQ32, BNE32, J32, JAL32 */

        case 6:

        /* SB32, SH32, ADDIUPC, SWC132, SDC132, SW32 */

        case 7:

        /* LB32, LH32, LWC132, LDC132, LW32 */

            if (ctx->hflags & MIPS_HFLAG_BDS16) {

                generate_exception(ctx, EXCP_RI);

                /* Just stop translation; the user is confused.  */

                ctx->bstate = BS_STOP;

                return 2;

            }

            break;

        case 1:

        /* POOL16A, POOL16B, POOL16C, LWGP16, POOL16F */

        case 2:

        /* LBU16, LHU16, LWSP16, LW16, SB16, SH16, SWSP16, SW16 */

        case 3:

        /* MOVE16, ANDI16, POOL16D, POOL16E, BEQZ16, BNEZ16, B16, LI16 */

            if (ctx->hflags & MIPS_HFLAG_BDS32) {

                generate_exception(ctx, EXCP_RI);

                /* Just stop translation; the user is confused.  */

                ctx->bstate = BS_STOP;

                return 2;

            }

            break;

        }

    }

    switch (op) {

    case POOL16A:

        {

            int rd = mmreg(uMIPS_RD(ctx->opcode));

            int rs1 = mmreg(uMIPS_RS1(ctx->opcode));

            int rs2 = mmreg(uMIPS_RS2(ctx->opcode));

            uint32_t opc = 0;

            switch (ctx->opcode & 0x1) {

            case ADDU16:

                opc = OPC_ADDU;

                break;

            case SUBU16:

                opc = OPC_SUBU;

                break;

            }

            gen_arith(ctx, opc, rd, rs1, rs2);

        }

        break;

    case POOL16B:

        {

            int rd = mmreg(uMIPS_RD(ctx->opcode));

            int rs = mmreg(uMIPS_RS(ctx->opcode));

            int amount = (ctx->opcode >> 1) & 0x7;

            uint32_t opc = 0;

            amount = amount == 0 ? 8 : amount;

            switch (ctx->opcode & 0x1) {

            case SLL16:

                opc = OPC_SLL;

                break;

            case SRL16:

                opc = OPC_SRL;

                break;

            }

            gen_shift_imm(ctx, opc, rd, rs, amount);

        }

        break;

    case POOL16C:

        gen_pool16c_insn(ctx);

        break;

    case LWGP16:

        {

            int rd = mmreg(uMIPS_RD(ctx->opcode));

            int rb = 28;            /* GP */

            int16_t offset = SIMM(ctx->opcode, 0, 7) << 2;

            gen_ld(ctx, OPC_LW, rd, rb, offset);

        }

        break;

    case POOL16F:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        if (ctx->opcode & 1) {

            generate_exception(ctx, EXCP_RI);

        } else {

            /* MOVEP */

            int enc_dest = uMIPS_RD(ctx->opcode);

            int enc_rt = uMIPS_RS2(ctx->opcode);

            int enc_rs = uMIPS_RS1(ctx->opcode);

            int rd, rs, re, rt;

            static const int rd_enc[] = { 5, 5, 6, 4, 4, 4, 4, 4 };

            static const int re_enc[] = { 6, 7, 7, 21, 22, 5, 6, 7 };

            static const int rs_rt_enc[] = { 0, 17, 2, 3, 16, 18, 19, 20 };

            rd = rd_enc[enc_dest];

            re = re_enc[enc_dest];

            rs = rs_rt_enc[enc_rs];

            rt = rs_rt_enc[enc_rt];

            gen_arith(ctx, OPC_ADDU, rd, rs, 0);

            gen_arith(ctx, OPC_ADDU, re, rt, 0);

        }

        break;

    case LBU16:

        {

            int rd = mmreg(uMIPS_RD(ctx->opcode));

            int rb = mmreg(uMIPS_RS(ctx->opcode));

            int16_t offset = ZIMM(ctx->opcode, 0, 4);

            offset = (offset == 0xf ? -1 : offset);

            gen_ld(ctx, OPC_LBU, rd, rb, offset);

        }

        break;

    case LHU16:

        {

            int rd = mmreg(uMIPS_RD(ctx->opcode));

            int rb = mmreg(uMIPS_RS(ctx->opcode));

            int16_t offset = ZIMM(ctx->opcode, 0, 4) << 1;

            gen_ld(ctx, OPC_LHU, rd, rb, offset);

        }

        break;

    case LWSP16:

        {

            int rd = (ctx->opcode >> 5) & 0x1f;

            int rb = 29;            /* SP */

            int16_t offset = ZIMM(ctx->opcode, 0, 5) << 2;

            gen_ld(ctx, OPC_LW, rd, rb, offset);

        }

        break;

    case LW16:

        {

            int rd = mmreg(uMIPS_RD(ctx->opcode));

            int rb = mmreg(uMIPS_RS(ctx->opcode));

            int16_t offset = ZIMM(ctx->opcode, 0, 4) << 2;

            gen_ld(ctx, OPC_LW, rd, rb, offset);

        }

        break;

    case SB16:

        {

            int rd = mmreg2(uMIPS_RD(ctx->opcode));

            int rb = mmreg(uMIPS_RS(ctx->opcode));

            int16_t offset = ZIMM(ctx->opcode, 0, 4);

            gen_st(ctx, OPC_SB, rd, rb, offset);

        }

        break;

    case SH16:

        {

            int rd = mmreg2(uMIPS_RD(ctx->opcode));

            int rb = mmreg(uMIPS_RS(ctx->opcode));

            int16_t offset = ZIMM(ctx->opcode, 0, 4) << 1;

            gen_st(ctx, OPC_SH, rd, rb, offset);

        }

        break;

    case SWSP16:

        {

            int rd = (ctx->opcode >> 5) & 0x1f;

            int rb = 29;            /* SP */

            int16_t offset = ZIMM(ctx->opcode, 0, 5) << 2;

            gen_st(ctx, OPC_SW, rd, rb, offset);

        }

        break;

    case SW16:

        {

            int rd = mmreg2(uMIPS_RD(ctx->opcode));

            int rb = mmreg(uMIPS_RS(ctx->opcode));

            int16_t offset = ZIMM(ctx->opcode, 0, 4) << 2;

            gen_st(ctx, OPC_SW, rd, rb, offset);

        }

        break;

    case MOVE16:

        {

            int rd = uMIPS_RD5(ctx->opcode);

            int rs = uMIPS_RS5(ctx->opcode);

            gen_arith(ctx, OPC_ADDU, rd, rs, 0);

        }

        break;

    case ANDI16:

        gen_andi16(ctx);

        break;

    case POOL16D:

        switch (ctx->opcode & 0x1) {

        case ADDIUS5:

            gen_addius5(ctx);

            break;

        case ADDIUSP:

            gen_addiusp(ctx);

            break;

        }

        break;

    case POOL16E:

        switch (ctx->opcode & 0x1) {

        case ADDIUR2:

            gen_addiur2(ctx);

            break;

        case ADDIUR1SP:

            gen_addiur1sp(ctx);

            break;

        }

        break;

    case B16:

        gen_compute_branch(ctx, OPC_BEQ, 2, 0, 0,

                           SIMM(ctx->opcode, 0, 10) << 1, 4);

        break;

    case BNEZ16:

    case BEQZ16:

        gen_compute_branch(ctx, op == BNEZ16 ? OPC_BNE : OPC_BEQ, 2,

                           mmreg(uMIPS_RD(ctx->opcode)),

                           0, SIMM(ctx->opcode, 0, 7) << 1, 4);

        break;

    case LI16:

        {

            int reg = mmreg(uMIPS_RD(ctx->opcode));

            int imm = ZIMM(ctx->opcode, 0, 7);

            imm = (imm == 0x7f ? -1 : imm);

            tcg_gen_movi_tl(cpu_gpr[reg], imm);

        }

        break;

    case RES_20:

    case RES_28:

    case RES_29:

    case RES_30:

    case RES_31:

    case RES_38:

    case RES_39:

        generate_exception(ctx, EXCP_RI);

        break;

    default:

        decode_micromips32_opc(env, ctx);

        return 4;

    }

    return 2;

}


static void ratelimit_set_speed(RateLimit *limit, uint64_t speed)

{

    limit->slice_quota = speed / (1000000000ULL / SLICE_TIME);

}


static void tap_update_fd_handler(TAPState *s)

{

    qemu_set_fd_handler2(s->fd,

                         s->read_poll && s->enabled ? tap_can_send : NULL,

                         s->read_poll && s->enabled ? tap_send     : NULL,

                         s->write_poll && s->enabled ? tap_writable : NULL,

                         s);

}


static void pc_init1(ram_addr_t ram_size,

                     const char *boot_device,

                     const char *kernel_filename,

                     const char *kernel_cmdline,

                     const char *initrd_filename,

                     const char *cpu_model,

                     int pci_enabled)

{

    char *filename;

    int ret, linux_boot, i;

    ram_addr_t ram_addr, bios_offset, option_rom_offset;

    ram_addr_t below_4g_mem_size, above_4g_mem_size = 0;

    int bios_size, isa_bios_size;

    PCIBus *pci_bus;

    ISADevice *isa_dev;

    int piix3_devfn = -1;

    CPUState *env;

    qemu_irq *cpu_irq;

    qemu_irq *isa_irq;

    qemu_irq *i8259;

    IsaIrqState *isa_irq_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    void *fw_cfg;

    if (ram_size >= 0xe0000000 ) {

        above_4g_mem_size = ram_size - 0xe0000000;

        below_4g_mem_size = 0xe0000000;

    } else {

        below_4g_mem_size = ram_size;

    }

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_X86_64

        cpu_model = "qemu64";

#else

        cpu_model = "qemu32";

#endif

    }

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

        env = pc_new_cpu(cpu_model);

    }

    vmport_init();

    /* allocate RAM */

    ram_addr = qemu_ram_alloc(0xa0000);

    cpu_register_physical_memory(0, 0xa0000, ram_addr);

    /* Allocate, even though we won't register, so we don't break the

     * phys_ram_base + PA assumption. This range includes vga (0xa0000 - 0xc0000),

     * and some bios areas, which will be registered later

     */

    ram_addr = qemu_ram_alloc(0x100000 - 0xa0000);

    ram_addr = qemu_ram_alloc(below_4g_mem_size - 0x100000);

    cpu_register_physical_memory(0x100000,

                 below_4g_mem_size - 0x100000,

                 ram_addr);

    /* above 4giga memory allocation */

    if (above_4g_mem_size > 0) {

#if TARGET_PHYS_ADDR_BITS == 32

        hw_error("To much RAM for 32-bit physical address");

#else

        ram_addr = qemu_ram_alloc(above_4g_mem_size);

        cpu_register_physical_memory(0x100000000ULL,

                                     above_4g_mem_size,

                                     ram_addr);

#endif

    }

    /* BIOS load */

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        bios_size = get_image_size(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size <= 0 ||

        (bios_size % 65536) != 0) {

        goto bios_error;

    }

    bios_offset = qemu_ram_alloc(bios_size);

    ret = rom_add_file_fixed(bios_name, (uint32_t)(-bios_size));

    if (ret != 0) {

    bios_error:

        fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", bios_name);

        exit(1);

    }

    if (filename) {

        qemu_free(filename);

    }

    /* map the last 128KB of the BIOS in ISA space */

    isa_bios_size = bios_size;

    if (isa_bios_size > (128 * 1024))

        isa_bios_size = 128 * 1024;

    cpu_register_physical_memory(0x100000 - isa_bios_size,

                                 isa_bios_size,

                                 (bios_offset + bios_size - isa_bios_size) | IO_MEM_ROM);

    rom_enable_driver_roms = 1;

    option_rom_offset = qemu_ram_alloc(PC_ROM_SIZE);

    cpu_register_physical_memory(PC_ROM_MIN_VGA, PC_ROM_SIZE, option_rom_offset);

    /* map all the bios at the top of memory */

    cpu_register_physical_memory((uint32_t)(-bios_size),

                                 bios_size, bios_offset | IO_MEM_ROM);

    fw_cfg = bochs_bios_init();

    if (linux_boot) {

        load_linux(fw_cfg, kernel_filename, initrd_filename, kernel_cmdline, below_4g_mem_size);

    }

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

        rom_add_option(option_rom[i]);

    }

    cpu_irq = qemu_allocate_irqs(pic_irq_request, NULL, 1);

    i8259 = i8259_init(cpu_irq[0]);

    isa_irq_state = qemu_mallocz(sizeof(*isa_irq_state));

    isa_irq_state->i8259 = i8259;

    isa_irq = qemu_allocate_irqs(isa_irq_handler, isa_irq_state, 24);

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, isa_irq);

    } else {

        pci_bus = NULL;

        isa_bus_new(NULL);

    }

    isa_bus_irqs(isa_irq);

    ferr_irq = isa_reserve_irq(13);

    /* init basic PC hardware */

    register_ioport_write(0x80, 1, 1, ioport80_write, NULL);

    register_ioport_write(0xf0, 1, 1, ioportF0_write, NULL);

    if (cirrus_vga_enabled) {

        if (pci_enabled) {

            pci_cirrus_vga_init(pci_bus);

        } else {

            isa_cirrus_vga_init();

        }

    } else if (vmsvga_enabled) {

        if (pci_enabled)

            pci_vmsvga_init(pci_bus);

        else

            fprintf(stderr, "%s: vmware_vga: no PCI bus\n", __FUNCTION__);

    } else if (std_vga_enabled) {

        if (pci_enabled) {

            pci_vga_init(pci_bus, 0, 0);

        } else {

            isa_vga_init();

        }

    }

    rtc_state = rtc_init(2000);

    qemu_register_boot_set(pc_boot_set, rtc_state);

    register_ioport_read(0x92, 1, 1, ioport92_read, NULL);

    register_ioport_write(0x92, 1, 1, ioport92_write, NULL);

    if (pci_enabled) {

        isa_irq_state->ioapic = ioapic_init();

    }

    pit = pit_init(0x40, isa_reserve_irq(0));

    pcspk_init(pit);

    if (!no_hpet) {

        hpet_init(isa_irq);

    }

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

        if (serial_hds[i]) {

            serial_isa_init(i, serial_hds[i]);

        }

    }

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

        if (parallel_hds[i]) {

            parallel_init(i, parallel_hds[i]);

        }

    }

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

        NICInfo *nd = &nd_table[i];

        if (!pci_enabled || (nd->model && strcmp(nd->model, "ne2k_isa") == 0))

            pc_init_ne2k_isa(nd);

        else

            pci_nic_init_nofail(nd, "e1000", NULL);

    }

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

        fprintf(stderr, "qemu: too many IDE bus\n");

        exit(1);

    }

    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {

        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

    }

    if (pci_enabled) {

        pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

    } else {

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

            isa_ide_init(ide_iobase[i], ide_iobase2[i], ide_irq[i],

	                 hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

        }

    }

    isa_dev = isa_create_simple("i8042");

    DMA_init(0);

#ifdef HAS_AUDIO

    audio_init(pci_enabled ? pci_bus : NULL, isa_irq);

#endif

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

    }

    floppy_controller = fdctrl_init_isa(fd);

    cmos_init(below_4g_mem_size, above_4g_mem_size, boot_device, hd);

    if (pci_enabled && usb_enabled) {

        usb_uhci_piix3_init(pci_bus, piix3_devfn + 2);

    }

    if (pci_enabled && acpi_enabled) {

        uint8_t *eeprom_buf = qemu_mallocz(8 * 256); /* XXX: make this persistent */

        i2c_bus *smbus;

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              isa_reserve_irq(9));

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

            DeviceState *eeprom;

            eeprom = qdev_create((BusState *)smbus, "smbus-eeprom");

            qdev_prop_set_uint8(eeprom, "address", 0x50 + i);

            qdev_prop_set_ptr(eeprom, "data", eeprom_buf + (i * 256));

            qdev_init_nofail(eeprom);

        }

        piix4_acpi_system_hot_add_init(pci_bus);

    }

    if (i440fx_state) {

        i440fx_init_memory_mappings(i440fx_state);

    }

    if (pci_enabled) {

	int max_bus;

        int bus;

        max_bus = drive_get_max_bus(IF_SCSI);

	for (bus = 0; bus <= max_bus; bus++) {

            pci_create_simple(pci_bus, -1, "lsi53c895a");

        }

    }

    /* Add virtio console devices */

    if (pci_enabled) {

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

            if (virtcon_hds[i]) {

                pci_create_simple(pci_bus, -1, "virtio-console-pci");

            }

        }

    }

    rom_load_fw(fw_cfg);

}


static void dec_mul(DisasContext *dc)

{

    TCGv d[2];

    unsigned int subcode;

    if ((dc->tb_flags & MSR_EE_FLAG)

         && !(dc->env->pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK)

         && !(dc->env->pvr.regs[0] & PVR0_USE_HW_MUL_MASK)) {

        tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);

        t_gen_raise_exception(dc, EXCP_HW_EXCP);

        return;

    }

    subcode = dc->imm & 3;

    d[0] = tcg_temp_new();

    d[1] = tcg_temp_new();

    if (dc->type_b) {

        LOG_DIS("muli r%d r%d %x\n", dc->rd, dc->ra, dc->imm);

        t_gen_mulu(cpu_R[dc->rd], d[1], cpu_R[dc->ra], *(dec_alu_op_b(dc)));

        goto done;

    }

    /* mulh, mulhsu and mulhu are not available if C_USE_HW_MUL is < 2.  */

    if (subcode >= 1 && subcode <= 3

        && !((dc->env->pvr.regs[2] & PVR2_USE_MUL64_MASK))) {

        /* nop??? */

    }

    switch (subcode) {

        case 0:

            LOG_DIS("mul r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            t_gen_mulu(cpu_R[dc->rd], d[1], cpu_R[dc->ra], cpu_R[dc->rb]);

            break;

        case 1:

            LOG_DIS("mulh r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            t_gen_muls(d[0], cpu_R[dc->rd], cpu_R[dc->ra], cpu_R[dc->rb]);

            break;

        case 2:

            LOG_DIS("mulhsu r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            t_gen_muls(d[0], cpu_R[dc->rd], cpu_R[dc->ra], cpu_R[dc->rb]);

            break;

        case 3:

            LOG_DIS("mulhu r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            t_gen_mulu(d[0], cpu_R[dc->rd], cpu_R[dc->ra], cpu_R[dc->rb]);

            break;

        default:

            cpu_abort(dc->env, "unknown MUL insn %x\n", subcode);

            break;

    }

done:

    tcg_temp_free(d[0]);

    tcg_temp_free(d[1]);

}


static void fimd_update_memory_section(Exynos4210fimdState *s, unsigned win)

{

    Exynos4210fimdWindow *w = &s->window[win];

    target_phys_addr_t fb_start_addr, fb_mapped_len;

    if (!s->enabled || !(w->wincon & FIMD_WINCON_ENWIN) ||

            FIMD_WINDOW_PROTECTED(s->shadowcon, win)) {

        return;

    }

    if (w->host_fb_addr) {

        cpu_physical_memory_unmap(w->host_fb_addr, w->fb_len, 0, 0);

        w->host_fb_addr = NULL;

        w->fb_len = 0;

    }

    fb_start_addr = w->buf_start[fimd_get_buffer_id(w)];

    /* Total number of bytes of virtual screen used by current window */

    w->fb_len = fb_mapped_len = (w->virtpage_width + w->virtpage_offsize) *

            (w->rightbot_y - w->lefttop_y + 1);

    w->mem_section = memory_region_find(sysbus_address_space(&s->busdev),

            fb_start_addr, w->fb_len);

    assert(w->mem_section.mr);

    assert(w->mem_section.offset_within_address_space == fb_start_addr);

    DPRINT_TRACE("Window %u framebuffer changed: address=0x%08x, len=0x%x\n",

            win, fb_start_addr, w->fb_len);

    if (w->mem_section.size != w->fb_len ||

            !memory_region_is_ram(w->mem_section.mr)) {

        DPRINT_ERROR("Failed to find window %u framebuffer region\n", win);

        goto error_return;

    }

    w->host_fb_addr = cpu_physical_memory_map(fb_start_addr, &fb_mapped_len, 0);

    if (!w->host_fb_addr) {

        DPRINT_ERROR("Failed to map window %u framebuffer\n", win);

        goto error_return;

    }

    if (fb_mapped_len != w->fb_len) {

        DPRINT_ERROR("Window %u mapped framebuffer length is less then "

                "expected\n", win);

        cpu_physical_memory_unmap(w->host_fb_addr, fb_mapped_len, 0, 0);

        goto error_return;

    }

    return;

error_return:

    w->mem_section.mr = NULL;

    w->mem_section.size = 0;

    w->host_fb_addr = NULL;

    w->fb_len = 0;

}


PCIDevice *pci_try_create_multifunction(PCIBus *bus, int devfn,

                                        bool multifunction,

                                        const char *name)

{

    DeviceState *dev;

    dev = qdev_try_create(&bus->qbus, name);

    if (!dev) {

        return NULL;

    }

    qdev_prop_set_uint32(dev, "addr", devfn);

    qdev_prop_set_bit(dev, "multifunction", multifunction);

    return DO_UPCAST(PCIDevice, qdev, dev);

}


void OPPROTO op_addq_ESI_T0(void)

{

    ESI = (ESI + T0);

}


static int mov_write_trailer(AVFormatContext *s)

{

    MOVMuxContext *mov = s->priv_data;

    AVIOContext *pb = s->pb;

    int res = 0;

    int i;

    int64_t moov_pos;

    /*

     * Before actually writing the trailer, make sure that there are no

     * dangling subtitles, that need a terminating sample.

     */

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

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

        if (trk->enc->codec_id == AV_CODEC_ID_MOV_TEXT &&

            !trk->last_sample_is_subtitle_end) {

            mov_write_subtitle_end_packet(s, i, trk->track_duration);

            trk->last_sample_is_subtitle_end = 1;

        }

    }

    // If there were no chapters when the header was written, but there

    // are chapters now, write them in the trailer.  This only works

    // when we are not doing fragments.

    if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {

        if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {

            mov->chapter_track = mov->nb_streams++;

            if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)

                goto error;

        }

    }

    if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {

        moov_pos = avio_tell(pb);

        /* Write size of mdat tag */

        if (mov->mdat_size + 8 <= UINT32_MAX) {

            avio_seek(pb, mov->mdat_pos, SEEK_SET);

            avio_wb32(pb, mov->mdat_size + 8);

        } else {

            /* overwrite 'wide' placeholder atom */

            avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);

            /* special value: real atom size will be 64 bit value after

             * tag field */

            avio_wb32(pb, 1);

            ffio_wfourcc(pb, "mdat");

            avio_wb64(pb, mov->mdat_size + 16);

        }

        avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_moov_pos : moov_pos, SEEK_SET);

        if (mov->flags & FF_MOV_FLAG_FASTSTART) {

            av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");

            res = shift_data(s);

            if (res == 0) {

                avio_seek(s->pb, mov->reserved_moov_pos, SEEK_SET);

                mov_write_moov_tag(pb, mov, s);

            }

        } else if (mov->reserved_moov_size > 0) {

            int64_t size;

            mov_write_moov_tag(pb, mov, s);

            size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_moov_pos);

            if (size < 8){

                av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);

                return -1;

            }

            avio_wb32(pb, size);

            ffio_wfourcc(pb, "free");

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

                avio_w8(pb, 0);

            avio_seek(pb, moov_pos, SEEK_SET);

        } else {

            mov_write_moov_tag(pb, mov, s);

        }

    } else {

        mov_flush_fragment(s);

        mov_write_mfra_tag(pb, mov);

    }

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

        if (mov->flags & FF_MOV_FLAG_FRAGMENT &&

            mov->tracks[i].vc1_info.struct_offset && s->pb->seekable) {

            int64_t off = avio_tell(pb);

            uint8_t buf[7];

            if (mov_write_dvc1_structs(&mov->tracks[i], buf) >= 0) {

                avio_seek(pb, mov->tracks[i].vc1_info.struct_offset, SEEK_SET);

                avio_write(pb, buf, 7);

                avio_seek(pb, off, SEEK_SET);

            }

        }

    }

error:

    mov_free(s);

    return res;

}


static void acquire_privilege(const char *name, Error **errp)

{

    HANDLE token = NULL;

    TOKEN_PRIVILEGES priv;

    Error *local_err = NULL;

    if (OpenProcessToken(GetCurrentProcess(),

        TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token))

    {

        if (!LookupPrivilegeValue(NULL, name, &priv.Privileges[0].Luid)) {

            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,

                       "no luid for requested privilege");

            goto out;

        }

        priv.PrivilegeCount = 1;

        priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

        if (!AdjustTokenPrivileges(token, FALSE, &priv, 0, NULL, 0)) {

            error_setg(&local_err, QERR_QGA_COMMAND_FAILED,

                       "unable to acquire requested privilege");

            goto out;

        }

    } else {

        error_setg(&local_err, QERR_QGA_COMMAND_FAILED,

                   "failed to open privilege token");

    }

out:

    if (token) {

        CloseHandle(token);

    }

    if (local_err) {

        error_propagate(errp, local_err);

    }

}


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

{

    int nr_iov, c;

    int pattern = 0xcd;

    struct aio_ctx *ctx = calloc(1, sizeof(struct aio_ctx));

    while ((c = getopt(argc, argv, "CqP:")) != EOF) {

        switch (c) {

        case 'C':

            ctx->Cflag = 1;

            break;

        case 'q':

            ctx->qflag = 1;

            break;

        case 'P':

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                free(ctx);

                return 0;

            }

            break;

        default:

            free(ctx);

            return command_usage(&aio_write_cmd);

        }

    }

    if (optind > argc - 2) {

        free(ctx);

        return command_usage(&aio_write_cmd);

    }

    ctx->offset = cvtnum(argv[optind]);

    if (ctx->offset < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        free(ctx);

        return 0;

    }

    optind++;

    if (ctx->offset & 0x1ff) {

        printf("offset %" PRId64 " is not sector aligned\n",

               ctx->offset);

        free(ctx);

        return 0;

    }

    nr_iov = argc - optind;

    ctx->buf = create_iovec(&ctx->qiov, &argv[optind], nr_iov, pattern);

    if (ctx->buf == NULL) {

        free(ctx);

        return 0;

    }

    gettimeofday(&ctx->t1, NULL);

    bdrv_aio_writev(bs, ctx->offset >> 9, &ctx->qiov,

                    ctx->qiov.size >> 9, aio_write_done, ctx);

    return 0;

}


void tlb_set_page(CPUState *cpu, target_ulong vaddr,

                  hwaddr paddr, int prot,

                  int mmu_idx, target_ulong size)

{

    CPUArchState *env = cpu->env_ptr;

    MemoryRegionSection *section;

    unsigned int index;

    target_ulong address;

    target_ulong code_address;

    uintptr_t addend;

    CPUTLBEntry *te;

    hwaddr iotlb, xlat, sz;

    assert(size >= TARGET_PAGE_SIZE);

    if (size != TARGET_PAGE_SIZE) {

        tlb_add_large_page(env, vaddr, size);

    }

    sz = size;

    section = address_space_translate_for_iotlb(cpu->as, paddr,

                                                &xlat, &sz);

    assert(sz >= TARGET_PAGE_SIZE);

#if defined(DEBUG_TLB)

    printf("tlb_set_page: vaddr=" TARGET_FMT_lx " paddr=0x" TARGET_FMT_plx

           " prot=%x idx=%d\n",

           vaddr, paddr, prot, mmu_idx);

#endif

    address = vaddr;

    if (!memory_region_is_ram(section->mr) && !memory_region_is_romd(section->mr)) {

        /* IO memory case */

        address |= TLB_MMIO;

        addend = 0;

    } else {

        /* TLB_MMIO for rom/romd handled below */

        addend = (uintptr_t)memory_region_get_ram_ptr(section->mr) + xlat;

    }

    code_address = address;

    iotlb = memory_region_section_get_iotlb(cpu, section, vaddr, paddr, xlat,

                                            prot, &address);

    index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);

    env->iotlb[mmu_idx][index] = iotlb - vaddr;

    te = &env->tlb_table[mmu_idx][index];

    te->addend = addend - vaddr;

    if (prot & PAGE_READ) {

        te->addr_read = address;

    } else {

        te->addr_read = -1;

    }

    if (prot & PAGE_EXEC) {

        te->addr_code = code_address;

    } else {

        te->addr_code = -1;

    }

    if (prot & PAGE_WRITE) {

        if ((memory_region_is_ram(section->mr) && section->readonly)

            || memory_region_is_romd(section->mr)) {

            /* Write access calls the I/O callback.  */

            te->addr_write = address | TLB_MMIO;

        } else if (memory_region_is_ram(section->mr)

                   && cpu_physical_memory_is_clean(section->mr->ram_addr

                                                   + xlat)) {

            te->addr_write = address | TLB_NOTDIRTY;

        } else {

            te->addr_write = address;

        }

    } else {

        te->addr_write = -1;

    }

}


int pit_get_initial_count(PITState *pit, int channel)

{

    PITChannelState *s = &pit->channels[channel];

    return s->count;

}


static void net_socket_update_fd_handler(NetSocketState *s)

{

    qemu_set_fd_handler2(s->fd,

                         s->read_poll  ? net_socket_can_send : NULL,

                         s->read_poll  ? s->send_fn : NULL,

                         s->write_poll ? net_socket_writable : NULL,

                         s);

}


static void bdrv_throttle_read_timer_cb(void *opaque)

{

    BlockDriverState *bs = opaque;

    qemu_co_enter_next(&bs->throttled_reqs[0]);

}


static void host_x86_cpu_initfn(Object *obj)

{

    X86CPU *cpu = X86_CPU(obj);

    CPUX86State *env = &cpu->env;

    KVMState *s = kvm_state;

    /* We can't fill the features array here because we don't know yet if

     * "migratable" is true or false.

     */

    cpu->host_features = true;

    /* If KVM is disabled, cpu_x86_create() will already report an error */

    if (kvm_enabled()) {

        env->cpuid_level = kvm_arch_get_supported_cpuid(s, 0x0, 0, R_EAX);

        env->cpuid_xlevel = kvm_arch_get_supported_cpuid(s, 0x80000000, 0, R_EAX);

        env->cpuid_xlevel2 = kvm_arch_get_supported_cpuid(s, 0xC0000000, 0, R_EAX);

    }

    object_property_set_bool(OBJECT(cpu), true, "pmu", &error_abort);

}


void usb_device_attach(USBDevice *dev, Error **errp)

{

    USBBus *bus = usb_bus_from_device(dev);

    USBPort *port = dev->port;

    char devspeed[32], portspeed[32];

    assert(port != NULL);

    assert(!dev->attached);

    usb_mask_to_str(devspeed, sizeof(devspeed), dev->speedmask);

    usb_mask_to_str(portspeed, sizeof(portspeed), port->speedmask);

    trace_usb_port_attach(bus->busnr, port->path,

                          devspeed, portspeed);

    if (!(port->speedmask & dev->speedmask)) {

        error_setg(errp, "Warning: speed mismatch trying to attach"

                   " usb device \"%s\" (%s speed)"

                   " to bus \"%s\", port \"%s\" (%s speed)",

                   dev->product_desc, devspeed,

                   bus->qbus.name, port->path, portspeed);

        return;

    }

    dev->attached++;

    usb_attach(port);

}


static void gen_store_exclusive(DisasContext *s, int rd, int rt, int rt2,

                                TCGv_i32 addr, int size)

{

    TCGv_i32 tmp;

    TCGv_i64 val64, extaddr;

    int done_label;

    int fail_label;

    /* if (env->exclusive_addr == addr && env->exclusive_val == [addr]) {

         [addr] = {Rt};

         {Rd} = 0;

       } else {

         {Rd} = 1;

       } */

    fail_label = gen_new_label();

    done_label = gen_new_label();

    extaddr = tcg_temp_new_i64();

    tcg_gen_extu_i32_i64(extaddr, addr);

    tcg_gen_brcond_i64(TCG_COND_NE, extaddr, cpu_exclusive_addr, fail_label);

    tcg_temp_free_i64(extaddr);

    tmp = tcg_temp_new_i32();

    switch (size) {

    case 0:

        gen_aa32_ld8u(tmp, addr, get_mem_index(s));

        break;

    case 1:

        gen_aa32_ld16u(tmp, addr, get_mem_index(s));

        break;

    case 2:

    case 3:

        gen_aa32_ld32u(tmp, addr, get_mem_index(s));

        break;

    default:

        abort();

    }

    val64 = tcg_temp_new_i64();

    if (size == 3) {

        TCGv_i32 tmp2 = tcg_temp_new_i32();

        TCGv_i32 tmp3 = tcg_temp_new_i32();

        tcg_gen_addi_i32(tmp2, addr, 4);

        gen_aa32_ld32u(tmp3, tmp2, get_mem_index(s));

        tcg_temp_free_i32(tmp2);

        tcg_gen_concat_i32_i64(val64, tmp, tmp3);

        tcg_temp_free_i32(tmp3);

    } else {

        tcg_gen_extu_i32_i64(val64, tmp);

    }

    tcg_temp_free_i32(tmp);

    tcg_gen_brcond_i64(TCG_COND_NE, val64, cpu_exclusive_val, fail_label);

    tcg_temp_free_i64(val64);

    tmp = load_reg(s, rt);

    switch (size) {

    case 0:

        gen_aa32_st8(tmp, addr, get_mem_index(s));

        break;

    case 1:

        gen_aa32_st16(tmp, addr, get_mem_index(s));

        break;

    case 2:

    case 3:

        gen_aa32_st32(tmp, addr, get_mem_index(s));

        break;

    default:

        abort();

    }

    tcg_temp_free_i32(tmp);

    if (size == 3) {

        tcg_gen_addi_i32(addr, addr, 4);

        tmp = load_reg(s, rt2);

        gen_aa32_st32(tmp, addr, get_mem_index(s));

        tcg_temp_free_i32(tmp);

    }

    tcg_gen_movi_i32(cpu_R[rd], 0);

    tcg_gen_br(done_label);

    gen_set_label(fail_label);

    tcg_gen_movi_i32(cpu_R[rd], 1);

    gen_set_label(done_label);

    tcg_gen_movi_i64(cpu_exclusive_addr, -1);

}


static int gdbserver_open(int port)

{

    struct sockaddr_in sockaddr;

    int fd, ret;

    fd = socket(PF_INET, SOCK_STREAM, 0);

    if (fd < 0) {

        perror("socket");

        return -1;

    }

#ifndef _WIN32

    fcntl(fd, F_SETFD, FD_CLOEXEC);

#endif

    socket_set_fast_reuse(fd);

    sockaddr.sin_family = AF_INET;

    sockaddr.sin_port = htons(port);

    sockaddr.sin_addr.s_addr = 0;

    ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));

    if (ret < 0) {

        perror("bind");

        close(fd);

        return -1;

    }

    ret = listen(fd, 0);

    if (ret < 0) {

        perror("listen");

        close(fd);

        return -1;

    }

    return fd;

}


void bdrv_get_geometry_hint(BlockDriverState *bs,

                            int *pcyls, int *pheads, int *psecs)

{

    *pcyls = bs->cyls;

    *pheads = bs->heads;

    *psecs = bs->secs;

}


static uint64_t arm_thiswdog_read(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    arm_mptimer_state *s = (arm_mptimer_state *)opaque;

    int id = get_current_cpu(s);

    return timerblock_read(&s->timerblock[id * 2 + 1], addr, size);

}


e1000_set_link_status(NetClientState *nc)

{

    E1000State *s = qemu_get_nic_opaque(nc);

    uint32_t old_status = s->mac_reg[STATUS];

    if (nc->link_down) {

        e1000_link_down(s);

    } else {

        if (s->compat_flags & E1000_FLAG_AUTONEG &&

            s->phy_reg[PHY_CTRL] & MII_CR_AUTO_NEG_EN &&

            s->phy_reg[PHY_CTRL] & MII_CR_RESTART_AUTO_NEG &&

            !(s->phy_reg[PHY_STATUS] & MII_SR_AUTONEG_COMPLETE)) {

            /* emulate auto-negotiation if supported */

            timer_mod(s->autoneg_timer,

                      qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 500);

        } else {

            e1000_link_up(s);

        }

    }

    if (s->mac_reg[STATUS] != old_status)

        set_ics(s, 0, E1000_ICR_LSC);

}


static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple){

    MpegEncContext * const s = &h->s;

    int i;

    int step    = 1;

    int offset  = 1;

    int uvoffset= 1;

    int top_idx = 1;

    int skiplast= 0;

    src_y  -=   linesize;

    src_cb -= uvlinesize;

    src_cr -= uvlinesize;

    if(!simple && FRAME_MBAFF){

        if(s->mb_y&1){

            offset  = MB_MBAFF ? 1 : 17;

            uvoffset= MB_MBAFF ? 1 : 9;

            if(!MB_MBAFF){

                *(uint64_t*)(h->top_borders[0][s->mb_x]+ 0)= *(uint64_t*)(src_y +  15*linesize);

                *(uint64_t*)(h->top_borders[0][s->mb_x]+ 8)= *(uint64_t*)(src_y +8+15*linesize);

                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

                    *(uint64_t*)(h->top_borders[0][s->mb_x]+16)= *(uint64_t*)(src_cb+7*uvlinesize);

                    *(uint64_t*)(h->top_borders[0][s->mb_x]+24)= *(uint64_t*)(src_cr+7*uvlinesize);

                }

            }

        }else{

            if(!MB_MBAFF){

                h->left_border[0]= h->top_borders[0][s->mb_x][15];

                if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

                    h->left_border[34   ]= h->top_borders[0][s->mb_x][16+7  ];

                    h->left_border[34+18]= h->top_borders[0][s->mb_x][16+8+7];

                }

                skiplast= 1;

            }

            offset  =

            uvoffset=

            top_idx = MB_MBAFF ? 0 : 1;

        }

        step= MB_MBAFF ? 2 : 1;

    }

    // There are two lines saved, the line above the the top macroblock of a pair,

    // and the line above the bottom macroblock

    h->left_border[offset]= h->top_borders[top_idx][s->mb_x][15];

    for(i=1; i<17 - skiplast; i++){

        h->left_border[offset+i*step]= src_y[15+i*  linesize];

    }

    *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+0)= *(uint64_t*)(src_y +  16*linesize);

    *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+8)= *(uint64_t*)(src_y +8+16*linesize);

    if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

        h->left_border[uvoffset+34   ]= h->top_borders[top_idx][s->mb_x][16+7];

        h->left_border[uvoffset+34+18]= h->top_borders[top_idx][s->mb_x][24+7];

        for(i=1; i<9 - skiplast; i++){

            h->left_border[uvoffset+34   +i*step]= src_cb[7+i*uvlinesize];

            h->left_border[uvoffset+34+18+i*step]= src_cr[7+i*uvlinesize];

        }

        *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+16)= *(uint64_t*)(src_cb+8*uvlinesize);

        *(uint64_t*)(h->top_borders[top_idx][s->mb_x]+24)= *(uint64_t*)(src_cr+8*uvlinesize);

    }

}


static ssize_t qio_channel_file_readv(QIOChannel *ioc,

                                      const struct iovec *iov,

                                      size_t niov,

                                      int **fds,

                                      size_t *nfds,

                                      Error **errp)

{

    QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);

    ssize_t ret;

 retry:

    ret = readv(fioc->fd, iov, niov);

    if (ret < 0) {

        if (errno == EAGAIN ||

            errno == EWOULDBLOCK) {

            return QIO_CHANNEL_ERR_BLOCK;

        }

        if (errno == EINTR) {

            goto retry;

        }

        error_setg_errno(errp, errno,

                         "Unable to read from file");

        return -1;

    }

    return ret;

}


int mmap_frag(unsigned long host_start,

               unsigned long start, unsigned long end,

               int prot, int flags, int fd, unsigned long offset)

{

    unsigned long host_end, ret, addr;

    int prot1, prot_new;

    host_end = host_start + qemu_host_page_size;

    /* get the protection of the target pages outside the mapping */

    prot1 = 0;

    for(addr = host_start; addr < host_end; addr++) {

        if (addr < start || addr >= end)

            prot1 |= page_get_flags(addr);

    }

    if (prot1 == 0) {

        /* no page was there, so we allocate one */

        ret = (long)mmap((void *)host_start, qemu_host_page_size, prot,

                         flags | MAP_ANONYMOUS, -1, 0);

        if (ret == -1)

            return ret;

    }

    prot1 &= PAGE_BITS;

    prot_new = prot | prot1;

    if (!(flags & MAP_ANONYMOUS)) {

        /* msync() won't work here, so we return an error if write is

           possible while it is a shared mapping */

#ifndef __APPLE__

        if ((flags & MAP_TYPE) == MAP_SHARED &&

#else

        if ((flags &  MAP_SHARED) &&

#endif

            (prot & PROT_WRITE))

            return -EINVAL;

        /* adjust protection to be able to read */

        if (!(prot1 & PROT_WRITE))

            mprotect((void *)host_start, qemu_host_page_size, prot1 | PROT_WRITE);

        /* read the corresponding file data */

        pread(fd, (void *)start, end - start, offset);

        /* put final protection */

        if (prot_new != (prot1 | PROT_WRITE))

            mprotect((void *)host_start, qemu_host_page_size, prot_new);

    } else {

        /* just update the protection */

        if (prot_new != prot1) {

            mprotect((void *)host_start, qemu_host_page_size, prot_new);

        }

    }

    return 0;

}


static int decode_cabac_field_decoding_flag(H264Context *h) {

    MpegEncContext * const s = &h->s;

    const int mb_x = s->mb_x;

    const int mb_y = s->mb_y & ~1;

    const int mba_xy = mb_x - 1 +  mb_y   *s->mb_stride;

    const int mbb_xy = mb_x     + (mb_y-2)*s->mb_stride;

    unsigned int ctx = 0;

    if( h->slice_table[mba_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mba_xy] ) ) {

        ctx += 1;

    }

    if( h->slice_table[mbb_xy] == h->slice_num && IS_INTERLACED( s->current_picture.mb_type[mbb_xy] ) ) {

        ctx += 1;

    }

    return get_cabac( &h->cabac, &h->cabac_state[70 + ctx] );

}


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

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

{

    uint8_t *dstPtr= dst[0];

    const uint8_t *srcPtr= src[0];

    int i;

    void (*copy)       (const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int width);

    void (*interpolate)(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int width);

    switch(c->srcFormat) {

#define CASE(pixfmt, prefix) \

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

                 interpolate = bayer_##prefix##_to_rgb24_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], dstPtr, dstStride[0], c->srcW);

    srcPtr += 2 * srcStride[0];

    dstPtr += 2 * dstStride[0];

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

        interpolate(srcPtr, srcStride[0], dstPtr, dstStride[0], c->srcW);

        srcPtr += 2 * srcStride[0];

        dstPtr += 2 * dstStride[0];

    }

    copy(srcPtr, srcStride[0], dstPtr, dstStride[0], c->srcW);

    return srcSliceH;

}


static void ff_h264_idct_add16_mmx(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){

    int i;

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

        if(nnzc[ scan8[i] ])

            ff_h264_idct_add_mmx(dst + block_offset[i], block + i*16, stride);

    }

}


static char *make_digest_auth(HTTPAuthState *state, const char *username,

                              const char *password, const char *uri,

                              const char *method)

{

    DigestParams *digest = &state->digest_params;

    int len;

    uint32_t cnonce_buf[2];

    char cnonce[17];

    char nc[9];

    int i;

    char A1hash[33], A2hash[33], response[33];

    struct AVMD5 *md5ctx;

    uint8_t hash[16];

    char *authstr;

    digest->nc++;

    snprintf(nc, sizeof(nc), "%08x", digest->nc);

    /* Generate a client nonce. */

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

        cnonce_buf[i] = av_get_random_seed();

    ff_data_to_hex(cnonce, (const uint8_t*) cnonce_buf, sizeof(cnonce_buf), 1);

    cnonce[2*sizeof(cnonce_buf)] = 0;

    md5ctx = av_md5_alloc();

    if (!md5ctx)

        return NULL;

    av_md5_init(md5ctx);

    update_md5_strings(md5ctx, username, ":", state->realm, ":", password, NULL);

    av_md5_final(md5ctx, hash);

    ff_data_to_hex(A1hash, hash, 16, 1);

    A1hash[32] = 0;

    if (!strcmp(digest->algorithm, "") || !strcmp(digest->algorithm, "MD5")) {

    } else if (!strcmp(digest->algorithm, "MD5-sess")) {

        av_md5_init(md5ctx);

        update_md5_strings(md5ctx, A1hash, ":", digest->nonce, ":", cnonce, NULL);

        av_md5_final(md5ctx, hash);

        ff_data_to_hex(A1hash, hash, 16, 1);

        A1hash[32] = 0;

    } else {

        /* Unsupported algorithm */

        av_free(md5ctx);

        return NULL;

    }

    av_md5_init(md5ctx);

    update_md5_strings(md5ctx, method, ":", uri, NULL);

    av_md5_final(md5ctx, hash);

    ff_data_to_hex(A2hash, hash, 16, 1);

    A2hash[32] = 0;

    av_md5_init(md5ctx);

    update_md5_strings(md5ctx, A1hash, ":", digest->nonce, NULL);

    if (!strcmp(digest->qop, "auth") || !strcmp(digest->qop, "auth-int")) {

        update_md5_strings(md5ctx, ":", nc, ":", cnonce, ":", digest->qop, NULL);

    }

    update_md5_strings(md5ctx, ":", A2hash, NULL);

    av_md5_final(md5ctx, hash);

    ff_data_to_hex(response, hash, 16, 1);

    response[32] = 0;

    av_free(md5ctx);

    if (!strcmp(digest->qop, "") || !strcmp(digest->qop, "auth")) {

    } else if (!strcmp(digest->qop, "auth-int")) {

        /* qop=auth-int not supported */

        return NULL;

    } else {

        /* Unsupported qop value. */

        return NULL;

    }

    len = strlen(username) + strlen(state->realm) + strlen(digest->nonce) +

              strlen(uri) + strlen(response) + strlen(digest->algorithm) +

              strlen(digest->opaque) + strlen(digest->qop) + strlen(cnonce) +

              strlen(nc) + 150;

    authstr = av_malloc(len);

    if (!authstr)

        return NULL;

    snprintf(authstr, len, "Authorization: Digest ");

    /* TODO: Escape the quoted strings properly. */

    av_strlcatf(authstr, len, "username=\"%s\"",   username);

    av_strlcatf(authstr, len, ",realm=\"%s\"",     state->realm);

    av_strlcatf(authstr, len, ",nonce=\"%s\"",     digest->nonce);

    av_strlcatf(authstr, len, ",uri=\"%s\"",       uri);

    av_strlcatf(authstr, len, ",response=\"%s\"",  response);

    if (digest->algorithm[0])

        av_strlcatf(authstr, len, ",algorithm=%s",  digest->algorithm);

    if (digest->opaque[0])

        av_strlcatf(authstr, len, ",opaque=\"%s\"", digest->opaque);

    if (digest->qop[0]) {

        av_strlcatf(authstr, len, ",qop=\"%s\"",    digest->qop);

        av_strlcatf(authstr, len, ",cnonce=\"%s\"", cnonce);

        av_strlcatf(authstr, len, ",nc=%s",         nc);

    }

    av_strlcatf(authstr, len, "\r\n");

    return authstr;

}


static void decode_opc (CPUState *env, DisasContext *ctx, int *is_branch)

{

    int32_t offset;

    int rs, rt, rd, sa;

    uint32_t op, op1, op2;

    int16_t imm;

    /* make sure instructions are on a word boundary */

    if (ctx->pc & 0x3) {

        env->CP0_BadVAddr = ctx->pc;

        generate_exception(ctx, EXCP_AdEL);

        return;

    }

    /* Handle blikely not taken case */

    if ((ctx->hflags & MIPS_HFLAG_BMASK_BASE) == MIPS_HFLAG_BL) {

        int l1 = gen_new_label();

        MIPS_DEBUG("blikely condition (" TARGET_FMT_lx ")", ctx->pc + 4);

        tcg_gen_brcondi_tl(TCG_COND_NE, bcond, 0, l1);

        tcg_gen_movi_i32(hflags, ctx->hflags & ~MIPS_HFLAG_BMASK);

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

        gen_set_label(l1);

    }

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP)))

        tcg_gen_debug_insn_start(ctx->pc);

    op = MASK_OP_MAJOR(ctx->opcode);

    rs = (ctx->opcode >> 21) & 0x1f;

    rt = (ctx->opcode >> 16) & 0x1f;

    rd = (ctx->opcode >> 11) & 0x1f;

    sa = (ctx->opcode >> 6) & 0x1f;

    imm = (int16_t)ctx->opcode;

    switch (op) {

    case OPC_SPECIAL:

        op1 = MASK_SPECIAL(ctx->opcode);

        switch (op1) {

        case OPC_SLL:          /* Shift with immediate */

        case OPC_SRA:

            gen_shift_imm(env, ctx, op1, rd, rt, sa);

            break;

        case OPC_SRL:

            switch ((ctx->opcode >> 21) & 0x1f) {

            case 1:

                /* rotr is decoded as srl on non-R2 CPUs */

                if (env->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_ROTR;

                }

                /* Fallthrough */

            case 0:

                gen_shift_imm(env, ctx, op1, rd, rt, sa);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_MOVN:         /* Conditional move */

        case OPC_MOVZ:

            check_insn(env, ctx, ISA_MIPS4 | ISA_MIPS32 |

                                 INSN_LOONGSON2E | INSN_LOONGSON2F);

            gen_cond_move(env, op1, rd, rs, rt);

            break;

        case OPC_ADD ... OPC_SUBU:

            gen_arith(env, ctx, op1, rd, rs, rt);

            break;

        case OPC_SLLV:         /* Shifts */

        case OPC_SRAV:

            gen_shift(env, ctx, op1, rd, rs, rt);

            break;

        case OPC_SRLV:

            switch ((ctx->opcode >> 6) & 0x1f) {

            case 1:

                /* rotrv is decoded as srlv on non-R2 CPUs */

                if (env->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_ROTRV;

                }

                /* Fallthrough */

            case 0:

                gen_shift(env, ctx, op1, rd, rs, rt);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_SLT:          /* Set on less than */

        case OPC_SLTU:

            gen_slt(env, op1, rd, rs, rt);

            break;

        case OPC_AND:          /* Logic*/

        case OPC_OR:

        case OPC_NOR:

        case OPC_XOR:

            gen_logic(env, op1, rd, rs, rt);

            break;

        case OPC_MULT ... OPC_DIVU:

            if (sa) {

                check_insn(env, ctx, INSN_VR54XX);

                op1 = MASK_MUL_VR54XX(ctx->opcode);

                gen_mul_vr54xx(ctx, op1, rd, rs, rt);

            } else

                gen_muldiv(ctx, op1, rs, rt);

            break;

        case OPC_JR ... OPC_JALR:

            gen_compute_branch(ctx, op1, 4, rs, rd, sa);

            *is_branch = 1;

            break;

        case OPC_TGE ... OPC_TEQ: /* Traps */

        case OPC_TNE:

            gen_trap(ctx, op1, rs, rt, -1);

            break;

        case OPC_MFHI:          /* Move from HI/LO */

        case OPC_MFLO:

            gen_HILO(ctx, op1, rd);

            break;

        case OPC_MTHI:

        case OPC_MTLO:          /* Move to HI/LO */

            gen_HILO(ctx, op1, rs);

            break;

        case OPC_PMON:          /* Pmon entry point, also R4010 selsl */

#ifdef MIPS_STRICT_STANDARD

            MIPS_INVAL("PMON / selsl");

            generate_exception(ctx, EXCP_RI);

#else

            gen_helper_0i(pmon, sa);

#endif

            break;

        case OPC_SYSCALL:

            generate_exception(ctx, EXCP_SYSCALL);

            ctx->bstate = BS_STOP;

            break;

        case OPC_BREAK:

            generate_exception(ctx, EXCP_BREAK);

            break;

        case OPC_SPIM:

#ifdef MIPS_STRICT_STANDARD

            MIPS_INVAL("SPIM");

            generate_exception(ctx, EXCP_RI);

#else

           /* Implemented as RI exception for now. */

            MIPS_INVAL("spim (unofficial)");

            generate_exception(ctx, EXCP_RI);

#endif

            break;

        case OPC_SYNC:

            /* Treat as NOP. */

            break;

        case OPC_MOVCI:

            check_insn(env, ctx, ISA_MIPS4 | ISA_MIPS32);

            if (env->CP0_Config1 & (1 << CP0C1_FP)) {

                check_cp1_enabled(ctx);

                gen_movci(ctx, rd, rs, (ctx->opcode >> 18) & 0x7,

                          (ctx->opcode >> 16) & 1);

            } else {

                generate_exception_err(ctx, EXCP_CpU, 1);

            }

            break;

#if defined(TARGET_MIPS64)

       /* MIPS64 specific opcodes */

        case OPC_DSLL:

        case OPC_DSRA:

        case OPC_DSLL32:

        case OPC_DSRA32:

            check_insn(env, ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_shift_imm(env, ctx, op1, rd, rt, sa);

            break;

        case OPC_DSRL:

            switch ((ctx->opcode >> 21) & 0x1f) {

            case 1:

                /* drotr is decoded as dsrl on non-R2 CPUs */

                if (env->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_DROTR;

                }

                /* Fallthrough */

            case 0:

                check_insn(env, ctx, ISA_MIPS3);

                check_mips_64(ctx);

                gen_shift_imm(env, ctx, op1, rd, rt, sa);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DSRL32:

            switch ((ctx->opcode >> 21) & 0x1f) {

            case 1:

                /* drotr32 is decoded as dsrl32 on non-R2 CPUs */

                if (env->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_DROTR32;

                }

                /* Fallthrough */

            case 0:

                check_insn(env, ctx, ISA_MIPS3);

                check_mips_64(ctx);

                gen_shift_imm(env, ctx, op1, rd, rt, sa);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DADD ... OPC_DSUBU:

            check_insn(env, ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_arith(env, ctx, op1, rd, rs, rt);

            break;

        case OPC_DSLLV:

        case OPC_DSRAV:

            check_insn(env, ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_shift(env, ctx, op1, rd, rs, rt);

            break;

        case OPC_DSRLV:

            switch ((ctx->opcode >> 6) & 0x1f) {

            case 1:

                /* drotrv is decoded as dsrlv on non-R2 CPUs */

                if (env->insn_flags & ISA_MIPS32R2) {

                    op1 = OPC_DROTRV;

                }

                /* Fallthrough */

            case 0:

                check_insn(env, ctx, ISA_MIPS3);

                check_mips_64(ctx);

                gen_shift(env, ctx, op1, rd, rs, rt);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case OPC_DMULT ... OPC_DDIVU:

            check_insn(env, ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_muldiv(ctx, op1, rs, rt);

            break;

#endif

        default:            /* Invalid */

            MIPS_INVAL("special");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_SPECIAL2:

        op1 = MASK_SPECIAL2(ctx->opcode);

        switch (op1) {

        case OPC_MADD ... OPC_MADDU: /* Multiply and add/sub */

        case OPC_MSUB ... OPC_MSUBU:

            check_insn(env, ctx, ISA_MIPS32);

            gen_muldiv(ctx, op1, rs, rt);

            break;

        case OPC_MUL:

            gen_arith(env, ctx, op1, rd, rs, rt);

            break;

        case OPC_CLO:

        case OPC_CLZ:

            check_insn(env, ctx, ISA_MIPS32);

            gen_cl(ctx, op1, rd, rs);

            break;

        case OPC_SDBBP:

            /* XXX: not clear which exception should be raised

             *      when in debug mode...

             */

            check_insn(env, ctx, ISA_MIPS32);

            if (!(ctx->hflags & MIPS_HFLAG_DM)) {

                generate_exception(ctx, EXCP_DBp);

            } else {

                generate_exception(ctx, EXCP_DBp);

            }

            /* Treat as NOP. */

            break;

        case OPC_DIV_G_2F:

        case OPC_DIVU_G_2F:

        case OPC_MULT_G_2F:

        case OPC_MULTU_G_2F:

        case OPC_MOD_G_2F:

        case OPC_MODU_G_2F:

            check_insn(env, ctx, INSN_LOONGSON2F);

            gen_loongson_integer(ctx, op1, rd, rs, rt);

            break;

#if defined(TARGET_MIPS64)

        case OPC_DCLO:

        case OPC_DCLZ:

            check_insn(env, ctx, ISA_MIPS64);

            check_mips_64(ctx);

            gen_cl(ctx, op1, rd, rs);

            break;

        case OPC_DMULT_G_2F:

        case OPC_DMULTU_G_2F:

        case OPC_DDIV_G_2F:

        case OPC_DDIVU_G_2F:

        case OPC_DMOD_G_2F:

        case OPC_DMODU_G_2F:

            check_insn(env, ctx, INSN_LOONGSON2F);

            gen_loongson_integer(ctx, op1, rd, rs, rt);

            break;

#endif

        default:            /* Invalid */

            MIPS_INVAL("special2");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_SPECIAL3:

        op1 = MASK_SPECIAL3(ctx->opcode);

        switch (op1) {

        case OPC_EXT:

        case OPC_INS:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_bitops(ctx, op1, rt, rs, sa, rd);

            break;

        case OPC_BSHFL:

            check_insn(env, ctx, ISA_MIPS32R2);

            op2 = MASK_BSHFL(ctx->opcode);

            gen_bshfl(ctx, op2, rt, rd);

            break;

        case OPC_RDHWR:

            gen_rdhwr(env, ctx, rt, rd);

            break;

        case OPC_FORK:

            check_insn(env, ctx, ASE_MT);

            {

                TCGv t0 = tcg_temp_new();

                TCGv t1 = tcg_temp_new();

                gen_load_gpr(t0, rt);

                gen_load_gpr(t1, rs);

                gen_helper_fork(t0, t1);

                tcg_temp_free(t0);

                tcg_temp_free(t1);

            }

            break;

        case OPC_YIELD:

            check_insn(env, ctx, ASE_MT);

            {

                TCGv t0 = tcg_temp_new();

                save_cpu_state(ctx, 1);

                gen_load_gpr(t0, rs);

                gen_helper_yield(t0, t0);

                gen_store_gpr(t0, rd);

                tcg_temp_free(t0);

            }

            break;

        case OPC_DIV_G_2E ... OPC_DIVU_G_2E:

        case OPC_MULT_G_2E ... OPC_MULTU_G_2E:

        case OPC_MOD_G_2E ... OPC_MODU_G_2E:

            check_insn(env, ctx, INSN_LOONGSON2E);

            gen_loongson_integer(ctx, op1, rd, rs, rt);

            break;

#if defined(TARGET_MIPS64)

        case OPC_DEXTM ... OPC_DEXT:

        case OPC_DINSM ... OPC_DINS:

            check_insn(env, ctx, ISA_MIPS64R2);

            check_mips_64(ctx);

            gen_bitops(ctx, op1, rt, rs, sa, rd);

            break;

        case OPC_DBSHFL:

            check_insn(env, ctx, ISA_MIPS64R2);

            check_mips_64(ctx);

            op2 = MASK_DBSHFL(ctx->opcode);

            gen_bshfl(ctx, op2, rt, rd);

            break;

        case OPC_DDIV_G_2E ... OPC_DDIVU_G_2E:

        case OPC_DMULT_G_2E ... OPC_DMULTU_G_2E:

        case OPC_DMOD_G_2E ... OPC_DMODU_G_2E:

            check_insn(env, ctx, INSN_LOONGSON2E);

            gen_loongson_integer(ctx, op1, rd, rs, rt);

            break;

#endif

        default:            /* Invalid */

            MIPS_INVAL("special3");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_REGIMM:

        op1 = MASK_REGIMM(ctx->opcode);

        switch (op1) {

        case OPC_BLTZ ... OPC_BGEZL: /* REGIMM branches */

        case OPC_BLTZAL ... OPC_BGEZALL:

            gen_compute_branch(ctx, op1, 4, rs, -1, imm << 2);

            *is_branch = 1;

            break;

        case OPC_TGEI ... OPC_TEQI: /* REGIMM traps */

        case OPC_TNEI:

            gen_trap(ctx, op1, rs, -1, imm);

            break;

        case OPC_SYNCI:

            check_insn(env, ctx, ISA_MIPS32R2);

            /* Treat as NOP. */

            break;

        default:            /* Invalid */

            MIPS_INVAL("regimm");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_CP0:

        check_cp0_enabled(ctx);

        op1 = MASK_CP0(ctx->opcode);

        switch (op1) {

        case OPC_MFC0:

        case OPC_MTC0:

        case OPC_MFTR:

        case OPC_MTTR:

#if defined(TARGET_MIPS64)

        case OPC_DMFC0:

        case OPC_DMTC0:

#endif

#ifndef CONFIG_USER_ONLY

            gen_cp0(env, ctx, op1, rt, rd);

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_C0_FIRST ... OPC_C0_LAST:

#ifndef CONFIG_USER_ONLY

            gen_cp0(env, ctx, MASK_C0(ctx->opcode), rt, rd);

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_MFMC0:

#ifndef CONFIG_USER_ONLY

            {

                TCGv t0 = tcg_temp_new();

                op2 = MASK_MFMC0(ctx->opcode);

                switch (op2) {

                case OPC_DMT:

                    check_insn(env, ctx, ASE_MT);

                    gen_helper_dmt(t0, t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_EMT:

                    check_insn(env, ctx, ASE_MT);

                    gen_helper_emt(t0, t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_DVPE:

                    check_insn(env, ctx, ASE_MT);

                    gen_helper_dvpe(t0, t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_EVPE:

                    check_insn(env, ctx, ASE_MT);

                    gen_helper_evpe(t0, t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_DI:

                    check_insn(env, ctx, ISA_MIPS32R2);

                    save_cpu_state(ctx, 1);

                    gen_helper_di(t0);

                    gen_store_gpr(t0, rt);

                    /* Stop translation as we may have switched the execution mode */

                    ctx->bstate = BS_STOP;

                    break;

                case OPC_EI:

                    check_insn(env, ctx, ISA_MIPS32R2);

                    save_cpu_state(ctx, 1);

                    gen_helper_ei(t0);

                    gen_store_gpr(t0, rt);

                    /* Stop translation as we may have switched the execution mode */

                    ctx->bstate = BS_STOP;

                    break;

                default:            /* Invalid */

                    MIPS_INVAL("mfmc0");

                    generate_exception(ctx, EXCP_RI);

                    break;

                }

                tcg_temp_free(t0);

            }

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_RDPGPR:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_load_srsgpr(rt, rd);

            break;

        case OPC_WRPGPR:

            check_insn(env, ctx, ISA_MIPS32R2);

            gen_store_srsgpr(rt, rd);

            break;

        default:

            MIPS_INVAL("cp0");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_ADDI: /* Arithmetic with immediate opcode */

    case OPC_ADDIU:

         gen_arith_imm(env, ctx, op, rt, rs, imm);

         break;

    case OPC_SLTI: /* Set on less than with immediate opcode */

    case OPC_SLTIU:

         gen_slt_imm(env, op, rt, rs, imm);

         break;

    case OPC_ANDI: /* Arithmetic with immediate opcode */

    case OPC_LUI:

    case OPC_ORI:

    case OPC_XORI:

         gen_logic_imm(env, op, rt, rs, imm);

         break;

    case OPC_J ... OPC_JAL: /* Jump */

         offset = (int32_t)(ctx->opcode & 0x3FFFFFF) << 2;

         gen_compute_branch(ctx, op, 4, rs, rt, offset);

         *is_branch = 1;

         break;

    case OPC_BEQ ... OPC_BGTZ: /* Branch */

    case OPC_BEQL ... OPC_BGTZL:

         gen_compute_branch(ctx, op, 4, rs, rt, imm << 2);

         *is_branch = 1;

         break;

    case OPC_LB ... OPC_LWR: /* Load and stores */

    case OPC_LL:

         gen_ld(env, ctx, op, rt, rs, imm);

         break;

    case OPC_SB ... OPC_SW:

    case OPC_SWR:

         gen_st(ctx, op, rt, rs, imm);

         break;

    case OPC_SC:

         gen_st_cond(ctx, op, rt, rs, imm);

         break;

    case OPC_CACHE:

        check_insn(env, ctx, ISA_MIPS3 | ISA_MIPS32);

        /* Treat as NOP. */

        break;

    case OPC_PREF:

        check_insn(env, ctx, ISA_MIPS4 | ISA_MIPS32);

        /* Treat as NOP. */

        break;

    /* Floating point (COP1). */

    case OPC_LWC1:

    case OPC_LDC1:

    case OPC_SWC1:

    case OPC_SDC1:

        gen_cop1_ldst(env, ctx, op, rt, rs, imm);

        break;

    case OPC_CP1:

        if (env->CP0_Config1 & (1 << CP0C1_FP)) {

            check_cp1_enabled(ctx);

            op1 = MASK_CP1(ctx->opcode);

            switch (op1) {

            case OPC_MFHC1:

            case OPC_MTHC1:

                check_insn(env, ctx, ISA_MIPS32R2);

            case OPC_MFC1:

            case OPC_CFC1:

            case OPC_MTC1:

            case OPC_CTC1:

                gen_cp1(ctx, op1, rt, rd);

                break;

#if defined(TARGET_MIPS64)

            case OPC_DMFC1:

            case OPC_DMTC1:

                check_insn(env, ctx, ISA_MIPS3);

                gen_cp1(ctx, op1, rt, rd);

                break;

#endif

            case OPC_BC1ANY2:

            case OPC_BC1ANY4:

                check_cop1x(ctx);

                check_insn(env, ctx, ASE_MIPS3D);

                /* fall through */

            case OPC_BC1:

                gen_compute_branch1(env, ctx, MASK_BC1(ctx->opcode),

                                    (rt >> 2) & 0x7, imm << 2);

                *is_branch = 1;

                break;

            case OPC_S_FMT:

            case OPC_D_FMT:

            case OPC_W_FMT:

            case OPC_L_FMT:

            case OPC_PS_FMT:

                gen_farith(ctx, ctx->opcode & FOP(0x3f, 0x1f), rt, rd, sa,

                           (imm >> 8) & 0x7);

                break;

            default:

                MIPS_INVAL("cp1");

                generate_exception (ctx, EXCP_RI);

                break;

            }

        } else {

            generate_exception_err(ctx, EXCP_CpU, 1);

        }

        break;

    /* COP2.  */

    case OPC_LWC2:

    case OPC_LDC2:

    case OPC_SWC2:

    case OPC_SDC2:

    case OPC_CP2:

        /* COP2: Not implemented. */

        generate_exception_err(ctx, EXCP_CpU, 2);

        break;

    case OPC_CP3:

        if (env->CP0_Config1 & (1 << CP0C1_FP)) {

            check_cp1_enabled(ctx);

            op1 = MASK_CP3(ctx->opcode);

            switch (op1) {

            case OPC_LWXC1:

            case OPC_LDXC1:

            case OPC_LUXC1:

            case OPC_SWXC1:

            case OPC_SDXC1:

            case OPC_SUXC1:

                gen_flt3_ldst(ctx, op1, sa, rd, rs, rt);

                break;

            case OPC_PREFX:

                /* Treat as NOP. */

                break;

            case OPC_ALNV_PS:

            case OPC_MADD_S:

            case OPC_MADD_D:

            case OPC_MADD_PS:

            case OPC_MSUB_S:

            case OPC_MSUB_D:

            case OPC_MSUB_PS:

            case OPC_NMADD_S:

            case OPC_NMADD_D:

            case OPC_NMADD_PS:

            case OPC_NMSUB_S:

            case OPC_NMSUB_D:

            case OPC_NMSUB_PS:

                gen_flt3_arith(ctx, op1, sa, rs, rd, rt);

                break;

            default:

                MIPS_INVAL("cp3");

                generate_exception (ctx, EXCP_RI);

                break;

            }

        } else {

            generate_exception_err(ctx, EXCP_CpU, 1);

        }

        break;

#if defined(TARGET_MIPS64)

    /* MIPS64 opcodes */

    case OPC_LWU:

    case OPC_LDL ... OPC_LDR:

    case OPC_LLD:

    case OPC_LD:

        check_insn(env, ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_ld(env, ctx, op, rt, rs, imm);

        break;

    case OPC_SDL ... OPC_SDR:

    case OPC_SD:

        check_insn(env, ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_st(ctx, op, rt, rs, imm);

        break;

    case OPC_SCD:

        check_insn(env, ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_st_cond(ctx, op, rt, rs, imm);

        break;

    case OPC_DADDI:

    case OPC_DADDIU:

        check_insn(env, ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_arith_imm(env, ctx, op, rt, rs, imm);

        break;

#endif

    case OPC_JALX:

        check_insn(env, ctx, ASE_MIPS16 | ASE_MICROMIPS);

        offset = (int32_t)(ctx->opcode & 0x3FFFFFF) << 2;

        gen_compute_branch(ctx, op, 4, rs, rt, offset);

        *is_branch = 1;

        break;

    case OPC_MDMX:

        check_insn(env, ctx, ASE_MDMX);

        /* MDMX: Not implemented. */

    default:            /* Invalid */

        MIPS_INVAL("major opcode");

        generate_exception(ctx, EXCP_RI);

        break;

    }

}


static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr)

{

    SubStream *s = &m->substream[substr];

    unsigned int i;

    uint32_t seed = s->noisegen_seed;

    unsigned int maxchan = s->max_matrix_channel;

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

        uint16_t seed_shr7 = seed >> 7;

        m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift;

        m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7)   << s->noise_shift;

        seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);

    }

    s->noisegen_seed = seed;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *frame)

{

    AVFilterContext *ctx = inlink->dst;

    AudioEchoContext *s = ctx->priv;

    AVFrame *out_frame;

    if (av_frame_is_writable(frame)) {

        out_frame = frame;

    } else {

        out_frame = ff_get_audio_buffer(inlink, frame->nb_samples);

        if (!out_frame)

            return AVERROR(ENOMEM);

        av_frame_copy_props(out_frame, frame);

    }

    s->echo_samples(s, s->delayptrs, frame->extended_data, out_frame->extended_data,

                    frame->nb_samples, inlink->channels);

    s->next_pts = frame->pts + av_rescale_q(frame->nb_samples, (AVRational){1, inlink->sample_rate}, inlink->time_base);

    if (frame != out_frame)

        av_frame_free(&frame);

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

}


static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom)

{

    int size;

    char *path;

    void *ptr;

    char name[32];

    if (!pdev->romfile)

        return 0;

    if (strlen(pdev->romfile) == 0)

        return 0;

    if (!pdev->rom_bar) {

        /*

         * Load rom via fw_cfg instead of creating a rom bar,

         * for 0.11 compatibility.

         */

        int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);

        if (class == 0x0300) {

            rom_add_vga(pdev->romfile);

        } else {

            rom_add_option(pdev->romfile, -1);

        }

        return 0;

    }

    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);

    if (path == NULL) {

        path = qemu_strdup(pdev->romfile);

    }

    size = get_image_size(path);

    if (size < 0) {

        error_report("%s: failed to find romfile \"%s\"",

                     __FUNCTION__, pdev->romfile);

        return -1;

    }

    if (size & (size - 1)) {

        size = 1 << qemu_fls(size);

    }

    if (pdev->qdev.info->vmsd)

        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);

    else

        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);

    pdev->rom_offset = qemu_ram_alloc(&pdev->qdev, name, size);

    ptr = qemu_get_ram_ptr(pdev->rom_offset);

    load_image(path, ptr);

    if (is_default_rom) {

        /* Only the default rom images will be patched (if needed). */

        pci_patch_ids(pdev, ptr, size);

    }

    pci_register_bar(pdev, PCI_ROM_SLOT, size,

                     0, pci_map_option_rom);

    return 0;

}