static void nbd_close(BlockDriverState *bs)

{

    BDRVNBDState *s = bs->opaque;

    qemu_opts_del(s->socket_opts);

    nbd_client_session_close(&s->client);

}


static void reset(DeviceState *d)

{

    sPAPRDRConnector *drc = SPAPR_DR_CONNECTOR(d);

    sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    trace_spapr_drc_reset(spapr_drc_index(drc));

    g_free(drc->ccs);

    drc->ccs = NULL;

    /* immediately upon reset we can safely assume DRCs whose devices

     * are pending removal can be safely removed, and that they will

     * subsequently be left in an ISOLATED state. move the DRC to this

     * state in these cases (which will in turn complete any pending

     * device removals)

     */

    if (drc->awaiting_release) {

        drck->set_isolation_state(drc, SPAPR_DR_ISOLATION_STATE_ISOLATED);

        /* generally this should also finalize the removal, but if the device

         * hasn't yet been configured we normally defer removal under the

         * assumption that this transition is taking place as part of device

         * configuration. so check if we're still waiting after this, and

         * force removal if we are

         */

        if (drc->awaiting_release) {

            spapr_drc_detach(drc, DEVICE(drc->dev), NULL);

        }

        /* non-PCI devices may be awaiting a transition to UNUSABLE */

        if (spapr_drc_type(drc) != SPAPR_DR_CONNECTOR_TYPE_PCI &&

            drc->awaiting_release) {

            drck->set_allocation_state(drc, SPAPR_DR_ALLOCATION_STATE_UNUSABLE);

        }

    }

}


int kvm_remove_breakpoint(CPUState *current_env, target_ulong addr,

                          target_ulong len, int type)

{

    struct kvm_sw_breakpoint *bp;

    CPUState *env;

    int err;

    if (type == GDB_BREAKPOINT_SW) {

        bp = kvm_find_sw_breakpoint(current_env, addr);

        if (!bp)

            return -ENOENT;

        if (bp->use_count > 1) {

            bp->use_count--;

            return 0;

        }

        err = kvm_arch_remove_sw_breakpoint(current_env, bp);

        if (err)

            return err;

        QTAILQ_REMOVE(&current_env->kvm_state->kvm_sw_breakpoints, bp, entry);

        qemu_free(bp);

    } else {

        err = kvm_arch_remove_hw_breakpoint(addr, len, type);

        if (err)

            return err;

    }

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

        err = kvm_update_guest_debug(env, 0);

        if (err)

            return err;

    }

    return 0;

}


void helper_fcmp_gt_DT(CPUSH4State *env, float64 t0, float64 t1)

{

    int relation;

    set_float_exception_flags(0, &env->fp_status);

    relation = float64_compare(t0, t1, &env->fp_status);

    if (unlikely(relation == float_relation_unordered)) {

        update_fpscr(env, GETPC());

    } else {

        env->sr_t = (relation == float_relation_greater);

    }

}


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

{

    int c;

    OutputFormat output_format = OFORMAT_HUMAN;

    const char *filename, *fmt, *output;

    BlockDriverState *bs;

    ImageInfo *info;

    fmt = NULL;

    output = NULL;

    for(;;) {

        int option_index = 0;

        static const struct option long_options[] = {

            {"help", no_argument, 0, 'h'},

            {"format", required_argument, 0, 'f'},

            {"output", required_argument, 0, OPTION_OUTPUT},

            {0, 0, 0, 0}

        };

        c = getopt_long(argc, argv, "f:h",

                        long_options, &option_index);

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            break;

        case 'f':

            fmt = optarg;

            break;

        case OPTION_OUTPUT:

            output = optarg;

            break;

        }

    }

    if (optind >= argc) {

        help();

    }

    filename = argv[optind++];

    if (output && !strcmp(output, "json")) {

        output_format = OFORMAT_JSON;

    } else if (output && !strcmp(output, "human")) {

        output_format = OFORMAT_HUMAN;

    } else if (output) {

        error_report("--output must be used with human or json as argument.");

        return 1;

    }

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

    if (!bs) {

        return 1;

    }

    info = g_new0(ImageInfo, 1);

    collect_image_info(bs, info, filename, fmt);

    switch (output_format) {

    case OFORMAT_HUMAN:

        dump_human_image_info(info);

        dump_snapshots(bs);

        break;

    case OFORMAT_JSON:

        collect_snapshots(bs, info);

        dump_json_image_info(info);

        break;

    }

    qapi_free_ImageInfo(info);

    bdrv_delete(bs);

    return 0;

}


int qio_dns_resolver_lookup_sync(QIODNSResolver *resolver,

                                 SocketAddressLegacy *addr,

                                 size_t *naddrs,

                                 SocketAddressLegacy ***addrs,

                                 Error **errp)

{

    switch (addr->type) {

    case SOCKET_ADDRESS_LEGACY_KIND_INET:

        return qio_dns_resolver_lookup_sync_inet(resolver,

                                                 addr,

                                                 naddrs,

                                                 addrs,

                                                 errp);

    case SOCKET_ADDRESS_LEGACY_KIND_UNIX:

    case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:

    case SOCKET_ADDRESS_LEGACY_KIND_FD:

        return qio_dns_resolver_lookup_sync_nop(resolver,

                                                addr,

                                                naddrs,

                                                addrs,

                                                errp);

    default:

        abort();

    }

}


static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,

                         int nb_sectors, QEMUIOVector *qiov)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster;

    int ret = 0, n;

    uint64_t cluster_offset;

    struct iovec hd_iov;

    QEMUIOVector hd_qiov;

    uint8_t *buf;

    void *orig_buf;

    Error *err = NULL;

    if (qiov->niov > 1) {

        buf = orig_buf = qemu_try_blockalign(bs, qiov->size);

        if (buf == NULL) {

            return -ENOMEM;

        }

    } else {

        orig_buf = NULL;

        buf = (uint8_t *)qiov->iov->iov_base;

    }

    qemu_co_mutex_lock(&s->lock);

    while (nb_sectors != 0) {

        /* prepare next request */

        cluster_offset = get_cluster_offset(bs, sector_num << 9,

                                                 0, 0, 0, 0);

        index_in_cluster = sector_num & (s->cluster_sectors - 1);

        n = s->cluster_sectors - index_in_cluster;

        if (n > nb_sectors) {

            n = nb_sectors;

        }

        if (!cluster_offset) {

            if (bs->backing) {

                /* read from the base image */

                hd_iov.iov_base = (void *)buf;

                hd_iov.iov_len = n * 512;

                qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);

                qemu_co_mutex_unlock(&s->lock);

                ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);

                qemu_co_mutex_lock(&s->lock);

                if (ret < 0) {

                    goto fail;

                }

            } else {

                /* Note: in this case, no need to wait */

                memset(buf, 0, 512 * n);

            }

        } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {

            /* add AIO support for compressed blocks ? */

            if (decompress_cluster(bs, cluster_offset) < 0) {

                goto fail;

            }

            memcpy(buf,

                   s->cluster_cache + index_in_cluster * 512, 512 * n);

        } else {

            if ((cluster_offset & 511) != 0) {

                goto fail;

            }

            hd_iov.iov_base = (void *)buf;

            hd_iov.iov_len = n * 512;

            qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);

            qemu_co_mutex_unlock(&s->lock);

            ret = bdrv_co_readv(bs->file,

                                (cluster_offset >> 9) + index_in_cluster,

                                n, &hd_qiov);

            qemu_co_mutex_lock(&s->lock);

            if (ret < 0) {

                break;

            }

            if (bs->encrypted) {

                assert(s->cipher);

                if (encrypt_sectors(s, sector_num, buf,

                                    n, false, &err) < 0) {

                    goto fail;

                }

            }

        }

        ret = 0;

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

    }

done:

    qemu_co_mutex_unlock(&s->lock);

    if (qiov->niov > 1) {

        qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);

        qemu_vfree(orig_buf);

    }

    return ret;

fail:

    error_free(err);

    ret = -EIO;

    goto done;

}


static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)

{

    int hours, minutes, seconds;

    if (!show_bits(gb, 23)) {

        av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");

        return -1;

    }

    hours   = get_bits(gb, 5);

    minutes = get_bits(gb, 6);

    skip_bits1(gb);

    seconds = get_bits(gb, 6);

    s->time_base = seconds + 60*(minutes + 60*hours);

    skip_bits1(gb);

    skip_bits1(gb);

    return 0;

}


static int ftp_restart(FTPContext *s, int64_t pos)

{

    char command[CONTROL_BUFFER_SIZE];

    const int rest_codes[] = {350, 0};

    snprintf(command, sizeof(command), "REST %"PRId64"\r\n", pos);

    if (!ftp_send_command(s, command, rest_codes, NULL))

        return AVERROR(EIO);

    return 0;

}


static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,

        int64_t offset, unsigned int bytes, QEMUIOVector *qiov)

{

    BlockDriverState *bs = child->bs;

    /* Perform I/O through a temporary buffer so that users who scribble over

     * their read buffer while the operation is in progress do not end up

     * modifying the image file.  This is critical for zero-copy guest I/O

     * where anything might happen inside guest memory.

     */

    void *bounce_buffer;

    BlockDriver *drv = bs->drv;

    struct iovec iov;

    QEMUIOVector bounce_qiov;

    int64_t cluster_offset;

    unsigned int cluster_bytes;

    size_t skip_bytes;

    int ret;

    /* FIXME We cannot require callers to have write permissions when all they

     * are doing is a read request. If we did things right, write permissions

     * would be obtained anyway, but internally by the copy-on-read code. As

     * long as it is implemented here rather than in a separate filter driver,

     * the copy-on-read code doesn't have its own BdrvChild, however, for which

     * it could request permissions. Therefore we have to bypass the permission

     * system for the moment. */

    // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));

    /* Cover entire cluster so no additional backing file I/O is required when

     * allocating cluster in the image file.

     */

    bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);

    trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,

                                   cluster_offset, cluster_bytes);

    iov.iov_len = cluster_bytes;

    iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);

    if (bounce_buffer == NULL) {

        ret = -ENOMEM;

        goto err;

    }

    qemu_iovec_init_external(&bounce_qiov, &iov, 1);

    ret = bdrv_driver_preadv(bs, cluster_offset, cluster_bytes,

                             &bounce_qiov, 0);

    if (ret < 0) {

        goto err;

    }

    bdrv_debug_event(bs, BLKDBG_COR_WRITE);

    if (drv->bdrv_co_pwrite_zeroes &&

        buffer_is_zero(bounce_buffer, iov.iov_len)) {

        /* FIXME: Should we (perhaps conditionally) be setting

         * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy

         * that still correctly reads as zero? */

        ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, cluster_bytes, 0);

    } else {

        /* This does not change the data on the disk, it is not necessary

         * to flush even in cache=writethrough mode.

         */

        ret = bdrv_driver_pwritev(bs, cluster_offset, cluster_bytes,

                                  &bounce_qiov, 0);

    }

    if (ret < 0) {

        /* It might be okay to ignore write errors for guest requests.  If this

         * is a deliberate copy-on-read then we don't want to ignore the error.

         * Simply report it in all cases.

         */

        goto err;

    }

    skip_bytes = offset - cluster_offset;

    qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, bytes);

err:

    qemu_vfree(bounce_buffer);

    return ret;

}


int kvm_ioctl(KVMState *s, int type, ...)

{

    int ret;

    void *arg;

    va_list ap;

    va_start(ap, type);

    arg = va_arg(ap, void *);

    va_end(ap);

    ret = ioctl(s->fd, type, arg);

    if (ret == -1)

        ret = -errno;

    return ret;

}


static uint64_t exynos4210_mct_read(void *opaque, target_phys_addr_t offset,

        unsigned size)

{

    Exynos4210MCTState *s = (Exynos4210MCTState *)opaque;

    int index;

    int shift;

    uint64_t count;

    uint32_t value;

    int lt_i;

    switch (offset) {

    case MCT_CFG:

        value = s->reg_mct_cfg;

        break;

    case G_CNT_L: case G_CNT_U:

        shift = 8 * (offset & 0x4);

        count = exynos4210_gfrc_get_count(&s->g_timer);

        value = UINT32_MAX & (count >> shift);

        DPRINTF("read FRC=0x%llx\n", count);

        break;

    case G_CNT_WSTAT:

        value = s->g_timer.reg.cnt_wstat;

        break;

    case G_COMP_L(0): case G_COMP_L(1): case G_COMP_L(2): case G_COMP_L(3):

    case G_COMP_U(0): case G_COMP_U(1): case G_COMP_U(2): case G_COMP_U(3):

    index = GET_G_COMP_IDX(offset);

    shift = 8 * (offset & 0x4);

    value = UINT32_MAX & (s->g_timer.reg.comp[index] >> shift);

    break;

    case G_TCON:

        value = s->g_timer.reg.tcon;

        break;

    case G_INT_CSTAT:

        value = s->g_timer.reg.int_cstat;

        break;

    case G_INT_ENB:

        value = s->g_timer.reg.int_enb;

        break;

        break;

    case G_WSTAT:

        value = s->g_timer.reg.wstat;

        break;

    case G_COMP0_ADD_INCR: case G_COMP1_ADD_INCR:

    case G_COMP2_ADD_INCR: case G_COMP3_ADD_INCR:

        value = s->g_timer.reg.comp_add_incr[GET_G_COMP_ADD_INCR_IDX(offset)];

        break;

        /* Local timers */

    case L0_TCNTB: case L0_ICNTB: case L0_FRCNTB:

    case L1_TCNTB: case L1_ICNTB: case L1_FRCNTB:

        lt_i = GET_L_TIMER_IDX(offset);

        index = GET_L_TIMER_CNT_REG_IDX(offset, lt_i);

        value = s->l_timer[lt_i].reg.cnt[index];

        break;

    case L0_TCNTO: case L1_TCNTO:

        lt_i = GET_L_TIMER_IDX(offset);

        value = exynos4210_ltick_cnt_get_cnto(&s->l_timer[lt_i].tick_timer);

        DPRINTF("local timer[%d] read TCNTO %x\n", lt_i, value);

        break;

    case L0_ICNTO: case L1_ICNTO:

        lt_i = GET_L_TIMER_IDX(offset);

        value = exynos4210_ltick_int_get_cnto(&s->l_timer[lt_i].tick_timer);

        DPRINTF("local timer[%d] read ICNTO %x\n", lt_i, value);

        break;

    case L0_FRCNTO: case L1_FRCNTO:

        lt_i = GET_L_TIMER_IDX(offset);

        value = exynos4210_lfrc_get_count(&s->l_timer[lt_i]);

        break;

    case L0_TCON: case L1_TCON:

        lt_i = ((offset & 0xF00) - L0_TCNTB) / 0x100;

        value = s->l_timer[lt_i].reg.tcon;

        break;

    case L0_INT_CSTAT: case L1_INT_CSTAT:

        lt_i = ((offset & 0xF00) - L0_TCNTB) / 0x100;

        value = s->l_timer[lt_i].reg.int_cstat;

        break;

    case L0_INT_ENB: case L1_INT_ENB:

        lt_i = ((offset & 0xF00) - L0_TCNTB) / 0x100;

        value = s->l_timer[lt_i].reg.int_enb;

        break;

    case L0_WSTAT: case L1_WSTAT:

        lt_i = ((offset & 0xF00) - L0_TCNTB) / 0x100;

        value = s->l_timer[lt_i].reg.wstat;

        break;

    default:

        hw_error("exynos4210.mct: bad read offset "

                TARGET_FMT_plx "\n", offset);

        break;

    }

    return value;

}


theora_gptopts(AVFormatContext *ctx, int idx, uint64_t gp, int64_t *dts)

{

    struct ogg *ogg = ctx->priv_data;

    struct ogg_stream *os = ogg->streams + idx;

    struct theora_params *thp = os->private;

    uint64_t iframe = gp >> thp->gpshift;

    uint64_t pframe = gp & thp->gpmask;

    if (thp->version < 0x030201)

        iframe++;

    if(!pframe)

        os->pflags |= AV_PKT_FLAG_KEY;

    if (dts)

        *dts = iframe + pframe;

    return iframe + pframe;

}


static void av_build_index_raw(AVFormatContext *s)

{

    AVPacket pkt1, *pkt = &pkt1;

    int ret;

    AVStream *st;

    st = s->streams[0];

    av_read_frame_flush(s);

    url_fseek(&s->pb, s->data_offset, SEEK_SET);

    for(;;) {

        ret = av_read_frame(s, pkt);

        if (ret < 0)

            break;

        if (pkt->stream_index == 0 && st->parser &&

            (pkt->flags & PKT_FLAG_KEY)) {

            add_index_entry(st, st->parser->frame_offset, pkt->dts,

                            AVINDEX_KEYFRAME);

        }

        av_free_packet(pkt);

    }

}


static FWCfgState *bochs_bios_init(void)

{

    FWCfgState *fw_cfg;

    uint8_t *smbios_tables, *smbios_anchor;

    size_t smbios_tables_len, smbios_anchor_len;

    uint64_t *numa_fw_cfg;

    int i, j;

    unsigned int apic_id_limit = pc_apic_id_limit(max_cpus);

    fw_cfg = fw_cfg_init_io(BIOS_CFG_IOPORT);

    /* FW_CFG_MAX_CPUS is a bit confusing/problematic on x86:

     *

     * SeaBIOS needs FW_CFG_MAX_CPUS for CPU hotplug, but the CPU hotplug

     * QEMU<->SeaBIOS interface is not based on the "CPU index", but on the APIC

     * ID of hotplugged CPUs[1]. This means that FW_CFG_MAX_CPUS is not the

     * "maximum number of CPUs", but the "limit to the APIC ID values SeaBIOS

     * may see".

     *

     * So, this means we must not use max_cpus, here, but the maximum possible

     * APIC ID value, plus one.

     *

     * [1] The only kind of "CPU identifier" used between SeaBIOS and QEMU is

     *     the APIC ID, not the "CPU index"

     */

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

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_bytes(fw_cfg, FW_CFG_ACPI_TABLES,

                     acpi_tables, acpi_tables_len);

    fw_cfg_add_i32(fw_cfg, FW_CFG_IRQ0_OVERRIDE, kvm_allows_irq0_override());

    smbios_tables = smbios_get_table_legacy(&smbios_tables_len);

    if (smbios_tables) {

        fw_cfg_add_bytes(fw_cfg, FW_CFG_SMBIOS_ENTRIES,

                         smbios_tables, smbios_tables_len);

    }

    smbios_get_tables(&smbios_tables, &smbios_tables_len,

                      &smbios_anchor, &smbios_anchor_len);

    if (smbios_anchor) {

        fw_cfg_add_file(fw_cfg, "etc/smbios/smbios-tables",

                        smbios_tables, smbios_tables_len);

        fw_cfg_add_file(fw_cfg, "etc/smbios/smbios-anchor",

                        smbios_anchor, smbios_anchor_len);

    }

    fw_cfg_add_bytes(fw_cfg, FW_CFG_E820_TABLE,

                     &e820_reserve, sizeof(e820_reserve));

    fw_cfg_add_file(fw_cfg, "etc/e820", e820_table,

                    sizeof(struct e820_entry) * e820_entries);

    fw_cfg_add_bytes(fw_cfg, FW_CFG_HPET, &hpet_cfg, sizeof(hpet_cfg));

    /* allocate memory for the NUMA channel: one (64bit) word for the number

     * of nodes, one word for each VCPU->node and one word for each node to

     * hold the amount of memory.

     */

    numa_fw_cfg = g_new0(uint64_t, 1 + apic_id_limit + nb_numa_nodes);

    numa_fw_cfg[0] = cpu_to_le64(nb_numa_nodes);

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

        unsigned int apic_id = x86_cpu_apic_id_from_index(i);

        assert(apic_id < apic_id_limit);

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

            if (test_bit(i, numa_info[j].node_cpu)) {

                numa_fw_cfg[apic_id + 1] = cpu_to_le64(j);

                break;

            }

        }

    }

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

        numa_fw_cfg[apic_id_limit + 1 + i] = cpu_to_le64(numa_info[i].node_mem);

    }

    fw_cfg_add_bytes(fw_cfg, FW_CFG_NUMA, numa_fw_cfg,

                     (1 + apic_id_limit + nb_numa_nodes) *

                     sizeof(*numa_fw_cfg));

    return fw_cfg;

}


int mmu_translate(CPUS390XState *env, target_ulong vaddr, int rw, uint64_t asc,

                  target_ulong *raddr, int *flags)

{

    int r = -1;

    uint8_t *sk;

    *flags = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

    vaddr &= TARGET_PAGE_MASK;

    if (!(env->psw.mask & PSW_MASK_DAT)) {

        *raddr = vaddr;

        r = 0;

        goto out;

    }

    switch (asc) {

    case PSW_ASC_PRIMARY:

    case PSW_ASC_HOME:

        r = mmu_translate_asc(env, vaddr, asc, raddr, flags, rw);

        break;

    case PSW_ASC_SECONDARY:

        /*

         * Instruction: Primary

         * Data: Secondary

         */

        if (rw == 2) {

            r = mmu_translate_asc(env, vaddr, PSW_ASC_PRIMARY, raddr, flags,

                                  rw);

            *flags &= ~(PAGE_READ | PAGE_WRITE);

        } else {

            r = mmu_translate_asc(env, vaddr, PSW_ASC_SECONDARY, raddr, flags,

                                  rw);

            *flags &= ~(PAGE_EXEC);

        }

        break;

    case PSW_ASC_ACCREG:

    default:

        hw_error("guest switched to unknown asc mode\n");

        break;

    }

 out:

    /* Convert real address -> absolute address */

    *raddr = mmu_real2abs(env, *raddr);

    if (*raddr <= ram_size) {

        sk = &env->storage_keys[*raddr / TARGET_PAGE_SIZE];

        if (*flags & PAGE_READ) {

            *sk |= SK_R;

        }

        if (*flags & PAGE_WRITE) {

            *sk |= SK_C;

        }

    }

    return r;

}


static inline int decode_ac_coeffs(GetBitContext *gb, int16_t *out,

                                   int blocks_per_slice,

                                   int plane_size_factor,

                                   const uint8_t *scan)

{

    int pos, block_mask, run, level, sign, run_cb_index, lev_cb_index;

    int max_coeffs, bits_left;

    /* set initial prediction values */

    run   = 4;

    level = 2;

    max_coeffs = blocks_per_slice << 6;

    block_mask = blocks_per_slice - 1;

    for (pos = blocks_per_slice - 1; pos < max_coeffs;) {

        run_cb_index = ff_prores_run_to_cb_index[FFMIN(run, 15)];

        lev_cb_index = ff_prores_lev_to_cb_index[FFMIN(level, 9)];

        bits_left = get_bits_left(gb);

        if (bits_left <= 0 || (bits_left <= 8 && !show_bits(gb, bits_left)))

            return 0;

        run = decode_vlc_codeword(gb, ff_prores_ac_codebook[run_cb_index]);

        if (run < 0)

            return AVERROR_INVALIDDATA;

        bits_left = get_bits_left(gb);

        if (bits_left <= 0 || (bits_left <= 8 && !show_bits(gb, bits_left)))

            return AVERROR_INVALIDDATA;

        level = decode_vlc_codeword(gb, ff_prores_ac_codebook[lev_cb_index]) + 1;

        if (level < 0)

            return AVERROR_INVALIDDATA;

        pos += run + 1;

        if (pos >= max_coeffs)

            break;

        sign = get_sbits(gb, 1);

        out[((pos & block_mask) << 6) + scan[pos >> plane_size_factor]] =

            (level ^ sign) - sign;

    }

    return 0;

}


static int local_opendir(FsContext *ctx,

                         V9fsPath *fs_path, V9fsFidOpenState *fs)

{

    int dirfd;

    DIR *stream;

    dirfd = local_opendir_nofollow(ctx, fs_path->data);

    if (dirfd == -1) {

        return -1;

    }

    stream = fdopendir(dirfd);

    if (!stream) {

        return -1;

    }

    fs->dir.stream = stream;

    return 0;

}


static int mpeg_mux_init(AVFormatContext *ctx)

{

    MpegMuxContext *s = ctx->priv_data;

    int bitrate, i, mpa_id, mpv_id, ac3_id;

    AVStream *st;

    StreamInfo *stream;

    s->packet_number = 0;

    s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);

    s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux);

    if (s->is_vcd)

        s->packet_size = 2324; /* VCD packet size */

    else

        s->packet_size = 2048;

    /* startcode(4) + length(2) + flags(1) */

    s->packet_data_max_size = s->packet_size - 7;

    if (s->is_mpeg2)

        s->packet_data_max_size -= 2;

    s->audio_bound = 0;

    s->video_bound = 0;

    mpa_id = AUDIO_ID;

    ac3_id = 0x80;

    mpv_id = VIDEO_ID;

    s->scr_stream_index = -1;

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

        st = ctx->streams[i];

        stream = av_mallocz(sizeof(StreamInfo));

        if (!stream)

            goto fail;

        st->priv_data = stream;

        switch(st->codec.codec_type) {

        case CODEC_TYPE_AUDIO:

            if (st->codec.codec_id == CODEC_ID_AC3)

                stream->id = ac3_id++;

            else

                stream->id = mpa_id++;

            stream->max_buffer_size = 4 * 1024;

            s->audio_bound++;

            break;

        case CODEC_TYPE_VIDEO:

            /* by default, video is used for the SCR computation */

            if (s->scr_stream_index == -1)

                s->scr_stream_index = i;

            stream->id = mpv_id++;

            stream->max_buffer_size = 46 * 1024;

            s->video_bound++;

            break;

        default:

            av_abort();

        }

    }

    /* if no SCR, use first stream (audio) */

    if (s->scr_stream_index == -1)

        s->scr_stream_index = 0;

    /* we increase slightly the bitrate to take into account the

       headers. XXX: compute it exactly */

    bitrate = 2000;

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

        st = ctx->streams[i];

        bitrate += st->codec.bit_rate;

    }

    s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);

    if (s->is_vcd || s->is_mpeg2)

        /* every packet */

        s->pack_header_freq = 1;

    else

        /* every 2 seconds */

        s->pack_header_freq = 2 * bitrate / s->packet_size / 8;

    /* the above seems to make pack_header_freq zero sometimes */

    if (s->pack_header_freq == 0)

       s->pack_header_freq = 1;

    if (s->is_mpeg2)

        /* every 200 packets. Need to look at the spec.  */

        s->system_header_freq = s->pack_header_freq * 40;

    else if (s->is_vcd)

        /* every 40 packets, this is my invention */

        s->system_header_freq = s->pack_header_freq * 40;

    else

        s->system_header_freq = s->pack_header_freq * 5;

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

        stream = ctx->streams[i]->priv_data;

        stream->buffer_ptr = 0;

        stream->packet_number = 0;

        stream->start_pts = AV_NOPTS_VALUE;

        stream->start_dts = AV_NOPTS_VALUE;

    }

    s->last_scr = 0;

    return 0;

 fail:

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

        av_free(ctx->streams[i]->priv_data);

    }

    return -ENOMEM;

}


static int mxf_read_header(AVFormatContext *s)

{

    MXFContext *mxf = s->priv_data;

    KLVPacket klv;

    int64_t essence_offset = 0;

    int ret;

    mxf->last_forward_tell = INT64_MAX;

    mxf->edit_units_per_packet = 1;

    if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) {

        av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n");

        return AVERROR_INVALIDDATA;

    }

    avio_seek(s->pb, -14, SEEK_CUR);

    mxf->fc = s;

    mxf->run_in = avio_tell(s->pb);

    while (!url_feof(s->pb)) {

        const MXFMetadataReadTableEntry *metadata;

        if (klv_read_packet(&klv, s->pb) < 0) {

            /* EOF - seek to previous partition or stop */

            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)

                break;

            else

                continue;

        }

        PRINT_KEY(s, "read header", klv.key);

        av_dlog(s, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);

        if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) ||

            IS_KLV_KEY(klv.key, mxf_essence_element_key) ||

            IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||

            IS_KLV_KEY(klv.key, mxf_system_item_key)) {

            if (!mxf->current_partition) {

                av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n");

                return AVERROR_INVALIDDATA;

            }

            if (!mxf->current_partition->essence_offset) {

                /* for OP1a we compute essence_offset

                 * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25)

                 * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset

                 *       for OPAtom we still need the actual essence_offset though (the KL's length can vary)

                 */

                int64_t op1a_essence_offset =

                    round_to_kag(mxf->current_partition->this_partition +

                                 mxf->current_partition->pack_length,       mxf->current_partition->kag_size) +

                    round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) +

                    round_to_kag(mxf->current_partition->index_byte_count,  mxf->current_partition->kag_size);

                if (mxf->op == OPAtom) {

                    /* point essence_offset to the actual data

                    * OPAtom has all the essence in one big KLV

                    */

                    mxf->current_partition->essence_offset = avio_tell(s->pb);

                    mxf->current_partition->essence_length = klv.length;

                } else {

                    /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf)  */

                    mxf->current_partition->essence_offset = op1a_essence_offset;

                }

            }

            if (!essence_offset)

                essence_offset = klv.offset;

            /* seek to footer, previous partition or stop */

            if (mxf_parse_handle_essence(mxf) <= 0)

                break;

            continue;

        } else if (!memcmp(klv.key, mxf_header_partition_pack_key, 13) &&

                   klv.key[13] >= 2 && klv.key[13] <= 4 && mxf->current_partition) {

            /* next partition pack - keep going, seek to previous partition or stop */

            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)

                break;

            else if (mxf->parsing_backward)

                continue;

            /* we're still parsing forward. proceed to parsing this partition pack */

        }

        for (metadata = mxf_metadata_read_table; metadata->read; metadata++) {

            if (IS_KLV_KEY(klv.key, metadata->key)) {

                int res;

                if (klv.key[5] == 0x53) {

                    res = mxf_read_local_tags(mxf, &klv, metadata->read, metadata->ctx_size, metadata->type);

                } else {

                    uint64_t next = avio_tell(s->pb) + klv.length;

                    res = metadata->read(mxf, s->pb, 0, klv.length, klv.key, klv.offset);

                    /* only seek forward, else this can loop for a long time */

                    if (avio_tell(s->pb) > next) {

                        av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n",

                               klv.offset);

                        return AVERROR_INVALIDDATA;

                    }

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

                }

                if (res < 0) {

                    av_log(s, AV_LOG_ERROR, "error reading header metadata\n");

                    return res;

                }

                break;

            }

        }

        if (!metadata->read)

            avio_skip(s->pb, klv.length);

    }

    /* FIXME avoid seek */

    if (!essence_offset)  {

        av_log(s, AV_LOG_ERROR, "no essence\n");

        return AVERROR_INVALIDDATA;

    }

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

    mxf_compute_essence_containers(mxf);

    /* we need to do this before computing the index tables

     * to be able to fill in zero IndexDurations with st->duration */

    if ((ret = mxf_parse_structural_metadata(mxf)) < 0)

        return ret;

    if ((ret = mxf_compute_index_tables(mxf)) < 0)

        return ret;

    if (mxf->nb_index_tables > 1) {

        /* TODO: look up which IndexSID to use via EssenceContainerData */

        av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n",

               mxf->nb_index_tables, mxf->index_tables[0].index_sid);

    } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) {

        av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n");

        return AVERROR_INVALIDDATA;

    }

    mxf_handle_small_eubc(s);

    return 0;

}


get_net_error_message(gint error)

{

    HMODULE module = NULL;

    gchar *retval = NULL;

    wchar_t *msg = NULL;

    int flags;

    size_t nchars;

    flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |

        FORMAT_MESSAGE_IGNORE_INSERTS |

        FORMAT_MESSAGE_FROM_SYSTEM;

    if (error >= NERR_BASE && error <= MAX_NERR) {

        module = LoadLibraryExW(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE);

        if (module != NULL) {

            flags |= FORMAT_MESSAGE_FROM_HMODULE;

        }

    }

    FormatMessageW(flags, module, error, 0, (LPWSTR)&msg, 0, NULL);

    if (msg != NULL) {

        nchars = wcslen(msg);

        if (nchars > 2 &&

            msg[nchars - 1] == L'\n' &&

            msg[nchars - 2] == L'\r') {

            msg[nchars - 2] = L'\0';

        }

        retval = g_utf16_to_utf8(msg, -1, NULL, NULL, NULL);

        LocalFree(msg);

    }

    if (module != NULL) {

        FreeLibrary(module);

    }

    return retval;

}


static void kqemu_record_flush(void)

{

    PCRecord *r, *r_next;

    int h;

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

        for(r = pc_rec_hash[h]; r != NULL; r = r_next) {

            r_next = r->next;

            free(r);

        }

        pc_rec_hash[h] = NULL;

    }

    nb_pc_records = 0;

}


static void iscsi_allocationmap_set(IscsiLun *iscsilun, int64_t sector_num,

                                    int nb_sectors)

{

    int64_t cluster_num, nb_clusters;

    if (iscsilun->allocationmap == NULL) {

        return;

    }

    cluster_num = sector_num / iscsilun->cluster_sectors;

    nb_clusters = DIV_ROUND_UP(sector_num + nb_sectors,

                               iscsilun->cluster_sectors) - cluster_num;

    bitmap_set(iscsilun->allocationmap, cluster_num, nb_clusters);

}


int cpu_exec(CPUArchState *env)

{

    CPUState *cpu = ENV_GET_CPU(env);

    CPUClass *cc = CPU_GET_CLASS(cpu);

#ifdef TARGET_I386

    X86CPU *x86_cpu = X86_CPU(cpu);

#endif

    int ret, interrupt_request;

    TranslationBlock *tb;

    uint8_t *tc_ptr;

    uintptr_t next_tb;

    SyncClocks sc;

    /* This must be volatile so it is not trashed by longjmp() */

    volatile bool have_tb_lock = false;

    if (cpu->halted) {

        if (!cpu_has_work(cpu)) {

            return EXCP_HALTED;

        }

        cpu->halted = 0;

    }

    current_cpu = cpu;

    /* As long as current_cpu is null, up to the assignment just above,

     * requests by other threads to exit the execution loop are expected to

     * be issued using the exit_request global. We must make sure that our

     * evaluation of the global value is performed past the current_cpu

     * value transition point, which requires a memory barrier as well as

     * an instruction scheduling constraint on modern architectures.  */

    smp_mb();

    if (unlikely(exit_request)) {

        cpu->exit_request = 1;

    }

    cc->cpu_exec_enter(cpu);

    cpu->exception_index = -1;

    /* Calculate difference between guest clock and host clock.

     * This delay includes the delay of the last cycle, so

     * what we have to do is sleep until it is 0. As for the

     * advance/delay we gain here, we try to fix it next time.

     */

    init_delay_params(&sc, cpu);

    /* prepare setjmp context for exception handling */

    for(;;) {

        if (sigsetjmp(cpu->jmp_env, 0) == 0) {

            /* if an exception is pending, we execute it here */

            if (cpu->exception_index >= 0) {

                if (cpu->exception_index >= EXCP_INTERRUPT) {

                    /* exit request from the cpu execution loop */

                    ret = cpu->exception_index;

                    if (ret == EXCP_DEBUG) {

                        cpu_handle_debug_exception(env);

                    }

                    break;

                } else {

#if defined(CONFIG_USER_ONLY)

                    /* if user mode only, we simulate a fake exception

                       which will be handled outside the cpu execution

                       loop */

#if defined(TARGET_I386)

                    cc->do_interrupt(cpu);

#endif

                    ret = cpu->exception_index;

                    break;

#else

                    cc->do_interrupt(cpu);

                    cpu->exception_index = -1;

#endif

                }

            }

            next_tb = 0; /* force lookup of first TB */

            for(;;) {

                interrupt_request = cpu->interrupt_request;

                if (unlikely(interrupt_request)) {

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

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

                        interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;

                    }

                    if (interrupt_request & CPU_INTERRUPT_DEBUG) {

                        cpu->interrupt_request &= ~CPU_INTERRUPT_DEBUG;

                        cpu->exception_index = EXCP_DEBUG;

                        cpu_loop_exit(cpu);

                    }

                    if (interrupt_request & CPU_INTERRUPT_HALT) {

                        cpu->interrupt_request &= ~CPU_INTERRUPT_HALT;

                        cpu->halted = 1;

                        cpu->exception_index = EXCP_HLT;

                        cpu_loop_exit(cpu);

                    }

#if defined(TARGET_I386)

                    if (interrupt_request & CPU_INTERRUPT_INIT) {

                        cpu_svm_check_intercept_param(env, SVM_EXIT_INIT, 0);

                        do_cpu_init(x86_cpu);

                        cpu->exception_index = EXCP_HALTED;

                        cpu_loop_exit(cpu);

                    }

#else

                    if (interrupt_request & CPU_INTERRUPT_RESET) {

                        cpu_reset(cpu);

                    }

#endif

                    /* The target hook has 3 exit conditions:

                       False when the interrupt isn't processed,

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

                       and via longjmp via cpu_loop_exit.  */

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

                        next_tb = 0;

                    }

                    /* Don't use the cached interrupt_request value,

                       do_interrupt may have updated the EXITTB flag. */

                    if (cpu->interrupt_request & CPU_INTERRUPT_EXITTB) {

                        cpu->interrupt_request &= ~CPU_INTERRUPT_EXITTB;

                        /* ensure that no TB jump will be modified as

                           the program flow was changed */

                        next_tb = 0;

                    }

                }

                if (unlikely(cpu->exit_request)) {

                    cpu->exit_request = 0;

                    cpu->exception_index = EXCP_INTERRUPT;

                    cpu_loop_exit(cpu);

                }

                spin_lock(&tcg_ctx.tb_ctx.tb_lock);

                have_tb_lock = true;

                tb = tb_find_fast(env);

                /* Note: we do it here to avoid a gcc bug on Mac OS X when

                   doing it in tb_find_slow */

                if (tcg_ctx.tb_ctx.tb_invalidated_flag) {

                    /* as some TB could have been invalidated because

                       of memory exceptions while generating the code, we

                       must recompute the hash index here */

                    next_tb = 0;

                    tcg_ctx.tb_ctx.tb_invalidated_flag = 0;

                }

                if (qemu_loglevel_mask(CPU_LOG_EXEC)) {

                    qemu_log("Trace %p [" TARGET_FMT_lx "] %s\n",

                             tb->tc_ptr, tb->pc, lookup_symbol(tb->pc));

                }

                /* see if we can patch the calling TB. When the TB

                   spans two pages, we cannot safely do a direct

                   jump. */

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

                    tb_add_jump((TranslationBlock *)(next_tb & ~TB_EXIT_MASK),

                                next_tb & TB_EXIT_MASK, tb);

                }

                have_tb_lock = false;

                spin_unlock(&tcg_ctx.tb_ctx.tb_lock);

                /* cpu_interrupt might be called while translating the

                   TB, but before it is linked into a potentially

                   infinite loop and becomes env->current_tb. Avoid

                   starting execution if there is a pending interrupt. */

                cpu->current_tb = tb;

                barrier();

                if (likely(!cpu->exit_request)) {

                    trace_exec_tb(tb, tb->pc);

                    tc_ptr = tb->tc_ptr;

                    /* execute the generated code */

                    next_tb = cpu_tb_exec(cpu, tc_ptr);

                    switch (next_tb & TB_EXIT_MASK) {

                    case TB_EXIT_REQUESTED:

                        /* Something asked us to stop executing

                         * chained TBs; just continue round the main

                         * loop. Whatever requested the exit will also

                         * have set something else (eg exit_request or

                         * interrupt_request) which we will handle

                         * next time around the loop.

                         */

                        tb = (TranslationBlock *)(next_tb & ~TB_EXIT_MASK);

                        next_tb = 0;

                        break;

                    case TB_EXIT_ICOUNT_EXPIRED:

                    {

                        /* Instruction counter expired.  */

                        int insns_left;

                        tb = (TranslationBlock *)(next_tb & ~TB_EXIT_MASK);

                        insns_left = cpu->icount_decr.u32;

                        if (cpu->icount_extra && insns_left >= 0) {

                            /* Refill decrementer and continue execution.  */

                            cpu->icount_extra += insns_left;

                            if (cpu->icount_extra > 0xffff) {

                                insns_left = 0xffff;

                            } else {

                                insns_left = cpu->icount_extra;

                            }

                            cpu->icount_extra -= insns_left;

                            cpu->icount_decr.u16.low = insns_left;

                        } else {

                            if (insns_left > 0) {

                                /* Execute remaining instructions.  */

                                cpu_exec_nocache(env, insns_left, tb);

                                align_clocks(&sc, cpu);

                            }

                            cpu->exception_index = EXCP_INTERRUPT;

                            next_tb = 0;

                            cpu_loop_exit(cpu);

                        }

                        break;

                    }

                    default:

                        break;

                    }

                }

                cpu->current_tb = NULL;

                /* Try to align the host and virtual clocks

                   if the guest is in advance */

                align_clocks(&sc, cpu);

                /* reset soft MMU for next block (it can currently

                   only be set by a memory fault) */

            } /* for(;;) */

        } else {

            /* Reload env after longjmp - the compiler may have smashed all

             * local variables as longjmp is marked 'noreturn'. */

            cpu = current_cpu;

            env = cpu->env_ptr;

            cc = CPU_GET_CLASS(cpu);

#ifdef TARGET_I386

            x86_cpu = X86_CPU(cpu);

#endif

            if (have_tb_lock) {

                spin_unlock(&tcg_ctx.tb_ctx.tb_lock);

                have_tb_lock = false;

            }

        }

    } /* for(;;) */

    cc->cpu_exec_exit(cpu);

    /* fail safe : never use current_cpu outside cpu_exec() */

    current_cpu = NULL;

    return ret;

}


static void test_qemu_strtosz_metric(void)

{

    const char *str = "12345k";

    char *endptr = NULL;

    int64_t res;

    res = qemu_strtosz_metric(str, &endptr);

    g_assert_cmpint(res, ==, 12345000);

    g_assert(endptr == str + 6);

}


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

                                         long width, long height,

                                         long lumStride, long chromStride, long dstStride)

{

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

}


int ff_h263_decode_mb(MpegEncContext *s,
                      int16_t block[6][64])
{
    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
    int16_t *mot_val;
    const int xy= s->mb_x + s->mb_y * s->mb_stride;
    int cbpb = 0, pb_mv_count = 0;
    av_assert2(!s->h263_pred);
    if (s->pict_type == AV_PICTURE_TYPE_P) {
        do{
            if (get_bits1(&s->gb)) {
                /* skip mb */
                s->mb_intra = 0;
                for(i=0;i<6;i++)
                    s->block_last_index[i] = -1;
                s->mv_dir = MV_DIR_FORWARD;
                s->mv_type = MV_TYPE_16X16;
                s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
                s->mv[0][0][0] = 0;
                s->mv[0][0][1] = 0;
                s->mb_skipped = !(s->obmc | s->loop_filter);
                goto end;
            cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
            if (cbpc < 0){
                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
        }while(cbpc == 20);
        s->bdsp.clear_blocks(s->block[0]);
        dquant = cbpc & 8;
        s->mb_intra = ((cbpc & 4) != 0);
        if (s->mb_intra) goto intra;
        if(s->pb_frame && get_bits1(&s->gb))
            pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
        if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
            cbpy ^= 0xF;
        cbp = (cbpc & 3) | (cbpy << 2);
        if (dquant) {
            h263_decode_dquant(s);
        s->mv_dir = MV_DIR_FORWARD;
        if ((cbpc & 16) == 0) {
            s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
            /* 16x16 motion prediction */
            s->mv_type = MV_TYPE_16X16;
            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
            if (s->umvplus)
               mx = h263p_decode_umotion(s, pred_x);
            else
               mx = ff_h263_decode_motion(s, pred_x, 1);
            if (mx >= 0xffff)
            if (s->umvplus)
               my = h263p_decode_umotion(s, pred_y);
            else
               my = ff_h263_decode_motion(s, pred_y, 1);
            if (my >= 0xffff)
            s->mv[0][0][0] = mx;
            s->mv[0][0][1] = my;
            if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
        } else {
            s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
            s->mv_type = MV_TYPE_8X8;
            for(i=0;i<4;i++) {
                mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
                if (s->umvplus)
                    mx = h263p_decode_umotion(s, pred_x);
                else
                    mx = ff_h263_decode_motion(s, pred_x, 1);
                if (mx >= 0xffff)
                if (s->umvplus)
                    my = h263p_decode_umotion(s, pred_y);
                else
                    my = ff_h263_decode_motion(s, pred_y, 1);
                if (my >= 0xffff)
                s->mv[0][i][0] = mx;
                s->mv[0][i][1] = my;
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
                mot_val[0] = mx;
                mot_val[1] = my;
    } else if(s->pict_type==AV_PICTURE_TYPE_B) {
        int mb_type;
        const int stride= s->b8_stride;
        int16_t *mot_val0 = s->current_picture.motion_val[0][2 * (s->mb_x + s->mb_y * stride)];
        int16_t *mot_val1 = s->current_picture.motion_val[1][2 * (s->mb_x + s->mb_y * stride)];
//        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;
        //FIXME ugly
        mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+2*stride]= mot_val0[2+2*stride]=
        mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+2*stride]= mot_val0[3+2*stride]=
        mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+2*stride]= mot_val1[2+2*stride]=
        mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+2*stride]= mot_val1[3+2*stride]= 0;
        do{
            mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);
            if (mb_type < 0){
                av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);
            mb_type= h263_mb_type_b_map[ mb_type ];
        }while(!mb_type);
        s->mb_intra = IS_INTRA(mb_type);
        if(HAS_CBP(mb_type)){
            s->bdsp.clear_blocks(s->block[0]);
            cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);
            if(s->mb_intra){
                dquant = IS_QUANT(mb_type);
                goto intra;
            cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
            if (cbpy < 0){
                av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
            if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)
                cbpy ^= 0xF;
            cbp = (cbpc & 3) | (cbpy << 2);
        }else
            cbp=0;
        av_assert2(!s->mb_intra);
        if(IS_QUANT(mb_type)){
            h263_decode_dquant(s);
        if(IS_DIRECT(mb_type)){
            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
            mb_type |= set_direct_mv(s);
        }else{
            s->mv_dir = 0;
            s->mv_type= MV_TYPE_16X16;
//FIXME UMV
            if(USES_LIST(mb_type, 0)){
                int16_t *mot_val= ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
                s->mv_dir = MV_DIR_FORWARD;
                if (s->umvplus)
                    mx = h263p_decode_umotion(s, pred_x);
                else
                    mx = ff_h263_decode_motion(s, pred_x, 1);
                if (mx >= 0xffff)
                if (s->umvplus)
                    my = h263p_decode_umotion(s, pred_y);
                else
                    my = ff_h263_decode_motion(s, pred_y, 1);
                if (my >= 0xffff)
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
                    skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
                s->mv[0][0][0] = mx;
                s->mv[0][0][1] = my;
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
            if(USES_LIST(mb_type, 1)){
                int16_t *mot_val= ff_h263_pred_motion(s, 0, 1, &pred_x, &pred_y);
                s->mv_dir |= MV_DIR_BACKWARD;
                if (s->umvplus)
                    mx = h263p_decode_umotion(s, pred_x);
                else
                    mx = ff_h263_decode_motion(s, pred_x, 1);
                if (mx >= 0xffff)
                if (s->umvplus)
                    my = h263p_decode_umotion(s, pred_y);
                else
                    my = ff_h263_decode_motion(s, pred_y, 1);
                if (my >= 0xffff)
                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
                    skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
                s->mv[1][0][0] = mx;
                s->mv[1][0][1] = my;
                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;
                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;
        s->current_picture.mb_type[xy] = mb_type;
    } else { /* I-Frame */
        do{
            cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
            if (cbpc < 0){
                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
        }while(cbpc == 8);
        s->bdsp.clear_blocks(s->block[0]);
        dquant = cbpc & 4;
        s->mb_intra = 1;
intra:
        s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
        if (s->h263_aic) {
            s->ac_pred = get_bits1(&s->gb);
            if(s->ac_pred){
                s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
                s->h263_aic_dir = get_bits1(&s->gb);
        }else
            s->ac_pred = 0;
        if(s->pb_frame && get_bits1(&s->gb))
            pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);
        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
        if(cbpy<0){
            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
        cbp = (cbpc & 3) | (cbpy << 2);
        if (dquant) {
            h263_decode_dquant(s);
        pb_mv_count += !!s->pb_frame;
    while(pb_mv_count--){
        ff_h263_decode_motion(s, 0, 1);
        ff_h263_decode_motion(s, 0, 1);
    /* decode each block */
    for (i = 0; i < 6; i++) {
        if (h263_decode_block(s, block[i], i, cbp&32) < 0)
            return -1;
        cbp+=cbp;
    if(s->pb_frame && h263_skip_b_part(s, cbpb) < 0)
        return -1;
    if(s->obmc && !s->mb_intra){
        if(s->pict_type == AV_PICTURE_TYPE_P && s->mb_x+1<s->mb_width && s->mb_num_left != 1)
            preview_obmc(s);
end:
        /* per-MB end of slice check */
    {
        int v= show_bits(&s->gb, 16);
        if (get_bits_left(&s->gb) < 16) {
            v >>= 16 - get_bits_left(&s->gb);
        if(v==0)
            return SLICE_END;
    return SLICE_OK;


int register_savevm(const char *idstr,

                    int instance_id,

                    int version_id,

                    SaveStateHandler *save_state,

                    LoadStateHandler *load_state,

                    void *opaque)

{

    SaveStateEntry *se, **pse;

    se = qemu_malloc(sizeof(SaveStateEntry));

    if (!se)

        return -1;

    pstrcpy(se->idstr, sizeof(se->idstr), idstr);

    se->instance_id = (instance_id == -1) ? 0 : instance_id;

    se->version_id = version_id;

    se->save_state = save_state;

    se->load_state = load_state;

    se->opaque = opaque;

    se->next = NULL;

    /* add at the end of list */

    pse = &first_se;

    while (*pse != NULL) {

        if (instance_id == -1

                && strcmp(se->idstr, (*pse)->idstr) == 0

                && se->instance_id <= (*pse)->instance_id)

            se->instance_id = (*pse)->instance_id + 1;

        pse = &(*pse)->next;

    }

    *pse = se;

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = arm_mptimer_realize;

    dc->vmsd = &vmstate_arm_mptimer;

    dc->reset = arm_mptimer_reset;

    dc->no_user = 1;

    dc->props = arm_mptimer_properties;

}


static int decode_mb_cavlc(H264Context *h){

    MpegEncContext * const s = &h->s;

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

    int partition_count;

    unsigned int mb_type, cbp;

    int dct8x8_allowed= h->pps.transform_8x8_mode;

    s->dsp.clear_blocks(h->mb); //FIXME avoid if already clear (move after skip handlong?

    tprintf(s->avctx, "pic:%d mb:%d/%d\n", h->frame_num, s->mb_x, s->mb_y);

    cbp = 0; /* avoid warning. FIXME: find a solution without slowing

                down the code */

    if(h->slice_type != I_TYPE && h->slice_type != SI_TYPE){

        if(s->mb_skip_run==-1)

            s->mb_skip_run= get_ue_golomb(&s->gb);

        if (s->mb_skip_run--) {

            if(FRAME_MBAFF && (s->mb_y&1) == 0){

                if(s->mb_skip_run==0)

                    h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);

                else

                    predict_field_decoding_flag(h);

            }

            decode_mb_skip(h);

            return 0;

        }

    }

    if(FRAME_MBAFF){

        if( (s->mb_y&1) == 0 )

            h->mb_mbaff = h->mb_field_decoding_flag = get_bits1(&s->gb);

    }else

        h->mb_field_decoding_flag= (s->picture_structure!=PICT_FRAME);

    h->prev_mb_skipped= 0;

    mb_type= get_ue_golomb(&s->gb);

    if(h->slice_type == B_TYPE){

        if(mb_type < 23){

            partition_count= b_mb_type_info[mb_type].partition_count;

            mb_type=         b_mb_type_info[mb_type].type;

        }else{

            mb_type -= 23;

            goto decode_intra_mb;

        }

    }else if(h->slice_type == P_TYPE /*|| h->slice_type == SP_TYPE */){

        if(mb_type < 5){

            partition_count= p_mb_type_info[mb_type].partition_count;

            mb_type=         p_mb_type_info[mb_type].type;

        }else{

            mb_type -= 5;

            goto decode_intra_mb;

        }

    }else{

       assert(h->slice_type == I_TYPE);

decode_intra_mb:

        if(mb_type > 25){

            av_log(h->s.avctx, AV_LOG_ERROR, "mb_type %d in %c slice too large at %d %d\n", mb_type, av_get_pict_type_char(h->slice_type), s->mb_x, s->mb_y);

            return -1;

        }

        partition_count=0;

        cbp= i_mb_type_info[mb_type].cbp;

        h->intra16x16_pred_mode= i_mb_type_info[mb_type].pred_mode;

        mb_type= i_mb_type_info[mb_type].type;

    }

    if(MB_FIELD)

        mb_type |= MB_TYPE_INTERLACED;

    h->slice_table[ mb_xy ]= h->slice_num;

    if(IS_INTRA_PCM(mb_type)){

        unsigned int x, y;

        // We assume these blocks are very rare so we do not optimize it.

        align_get_bits(&s->gb);

        // The pixels are stored in the same order as levels in h->mb array.

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

            const int index= 4*(y&3) + 32*((y>>2)&1) + 128*(y>>3);

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

                tprintf(s->avctx, "LUMA ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));

                h->mb[index + (x&3) + 16*((x>>2)&1) + 64*(x>>3)]= get_bits(&s->gb, 8);

            }

        }

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

            const int index= 256 + 4*(y&3) + 32*(y>>2);

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

                tprintf(s->avctx, "CHROMA U ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));

                h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);

            }

        }

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

            const int index= 256 + 64 + 4*(y&3) + 32*(y>>2);

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

                tprintf(s->avctx, "CHROMA V ICPM LEVEL (%3d)\n", show_bits(&s->gb, 8));

                h->mb[index + (x&3) + 16*(x>>2)]= get_bits(&s->gb, 8);

            }

        }

        // In deblocking, the quantizer is 0

        s->current_picture.qscale_table[mb_xy]= 0;

        h->chroma_qp = get_chroma_qp(h->pps.chroma_qp_index_offset, 0);

        // All coeffs are present

        memset(h->non_zero_count[mb_xy], 16, 16);

        s->current_picture.mb_type[mb_xy]= mb_type;

        return 0;

    }

    if(MB_MBAFF){

        h->ref_count[0] <<= 1;

        h->ref_count[1] <<= 1;

    }

    fill_caches(h, mb_type, 0);

    //mb_pred

    if(IS_INTRA(mb_type)){

            int pred_mode;

//            init_top_left_availability(h);

            if(IS_INTRA4x4(mb_type)){

                int i;

                int di = 1;

                if(dct8x8_allowed && get_bits1(&s->gb)){

                    mb_type |= MB_TYPE_8x8DCT;

                    di = 4;

                }

//                fill_intra4x4_pred_table(h);

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

                    int mode= pred_intra_mode(h, i);

                    if(!get_bits1(&s->gb)){

                        const int rem_mode= get_bits(&s->gb, 3);

                        mode = rem_mode + (rem_mode >= mode);

                    }

                    if(di==4)

                        fill_rectangle( &h->intra4x4_pred_mode_cache[ scan8[i] ], 2, 2, 8, mode, 1 );

                    else

                        h->intra4x4_pred_mode_cache[ scan8[i] ] = mode;

                }

                write_back_intra_pred_mode(h);

                if( check_intra4x4_pred_mode(h) < 0)

                    return -1;

            }else{

                h->intra16x16_pred_mode= check_intra_pred_mode(h, h->intra16x16_pred_mode);

                if(h->intra16x16_pred_mode < 0)

                    return -1;

            }

            pred_mode= check_intra_pred_mode(h, get_ue_golomb(&s->gb));

            if(pred_mode < 0)

                return -1;

            h->chroma_pred_mode= pred_mode;

    }else if(partition_count==4){

        int i, j, sub_partition_count[4], list, ref[2][4];

        if(h->slice_type == B_TYPE){

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

                h->sub_mb_type[i]= get_ue_golomb(&s->gb);

                if(h->sub_mb_type[i] >=13){

                    av_log(h->s.avctx, AV_LOG_ERROR, "B sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);

                    return -1;

                }

                sub_partition_count[i]= b_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;

                h->sub_mb_type[i]=      b_sub_mb_type_info[ h->sub_mb_type[i] ].type;

            }

            if(   IS_DIRECT(h->sub_mb_type[0]) || IS_DIRECT(h->sub_mb_type[1])

               || IS_DIRECT(h->sub_mb_type[2]) || IS_DIRECT(h->sub_mb_type[3])) {

                pred_direct_motion(h, &mb_type);

                h->ref_cache[0][scan8[4]] =

                h->ref_cache[1][scan8[4]] =

                h->ref_cache[0][scan8[12]] =

                h->ref_cache[1][scan8[12]] = PART_NOT_AVAILABLE;

            }

        }else{

            assert(h->slice_type == P_TYPE || h->slice_type == SP_TYPE); //FIXME SP correct ?

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

                h->sub_mb_type[i]= get_ue_golomb(&s->gb);

                if(h->sub_mb_type[i] >=4){

                    av_log(h->s.avctx, AV_LOG_ERROR, "P sub_mb_type %u out of range at %d %d\n", h->sub_mb_type[i], s->mb_x, s->mb_y);

                    return -1;

                }

                sub_partition_count[i]= p_sub_mb_type_info[ h->sub_mb_type[i] ].partition_count;

                h->sub_mb_type[i]=      p_sub_mb_type_info[ h->sub_mb_type[i] ].type;

            }

        }

        for(list=0; list<h->list_count; list++){

            int ref_count= IS_REF0(mb_type) ? 1 : h->ref_count[list];

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

                if(IS_DIRECT(h->sub_mb_type[i])) continue;

                if(IS_DIR(h->sub_mb_type[i], 0, list)){

                    unsigned int tmp = get_te0_golomb(&s->gb, ref_count); //FIXME init to 0 before and skip?

                    if(tmp>=ref_count){

                        av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", tmp);

                        return -1;

                    }

                    ref[list][i]= tmp;

                }else{

                 //FIXME

                    ref[list][i] = -1;

                }

            }

        }

        if(dct8x8_allowed)

            dct8x8_allowed = get_dct8x8_allowed(h);

        for(list=0; list<h->list_count; list++){

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

                if(IS_DIRECT(h->sub_mb_type[i])) {

                    h->ref_cache[list][ scan8[4*i] ] = h->ref_cache[list][ scan8[4*i]+1 ];

                    continue;

                }

                h->ref_cache[list][ scan8[4*i]   ]=h->ref_cache[list][ scan8[4*i]+1 ]=

                h->ref_cache[list][ scan8[4*i]+8 ]=h->ref_cache[list][ scan8[4*i]+9 ]= ref[list][i];

                if(IS_DIR(h->sub_mb_type[i], 0, list)){

                    const int sub_mb_type= h->sub_mb_type[i];

                    const int block_width= (sub_mb_type & (MB_TYPE_16x16|MB_TYPE_16x8)) ? 2 : 1;

                    for(j=0; j<sub_partition_count[i]; j++){

                        int mx, my;

                        const int index= 4*i + block_width*j;

                        int16_t (* mv_cache)[2]= &h->mv_cache[list][ scan8[index] ];

                        pred_motion(h, index, block_width, list, h->ref_cache[list][ scan8[index] ], &mx, &my);

                        mx += get_se_golomb(&s->gb);

                        my += get_se_golomb(&s->gb);

                        tprintf(s->avctx, "final mv:%d %d\n", mx, my);

                        if(IS_SUB_8X8(sub_mb_type)){

                            mv_cache[ 1 ][0]=

                            mv_cache[ 8 ][0]= mv_cache[ 9 ][0]= mx;

                            mv_cache[ 1 ][1]=

                            mv_cache[ 8 ][1]= mv_cache[ 9 ][1]= my;

                        }else if(IS_SUB_8X4(sub_mb_type)){

                            mv_cache[ 1 ][0]= mx;

                            mv_cache[ 1 ][1]= my;

                        }else if(IS_SUB_4X8(sub_mb_type)){

                            mv_cache[ 8 ][0]= mx;

                            mv_cache[ 8 ][1]= my;

                        }

                        mv_cache[ 0 ][0]= mx;

                        mv_cache[ 0 ][1]= my;

                    }

                }else{

                    uint32_t *p= (uint32_t *)&h->mv_cache[list][ scan8[4*i] ][0];

                    p[0] = p[1]=

                    p[8] = p[9]= 0;

                }

            }

        }

    }else if(IS_DIRECT(mb_type)){

        pred_direct_motion(h, &mb_type);

        dct8x8_allowed &= h->sps.direct_8x8_inference_flag;

    }else{

        int list, mx, my, i;

         //FIXME we should set ref_idx_l? to 0 if we use that later ...

        if(IS_16X16(mb_type)){

            for(list=0; list<h->list_count; list++){

                    unsigned int val;

                    if(IS_DIR(mb_type, 0, list)){

                        val= get_te0_golomb(&s->gb, h->ref_count[list]);

                        if(val >= h->ref_count[list]){

                            av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);

                            return -1;

                        }

                    }else

                        val= LIST_NOT_USED&0xFF;

                    fill_rectangle(&h->ref_cache[list][ scan8[0] ], 4, 4, 8, val, 1);

            }

            for(list=0; list<h->list_count; list++){

                unsigned int val;

                if(IS_DIR(mb_type, 0, list)){

                    pred_motion(h, 0, 4, list, h->ref_cache[list][ scan8[0] ], &mx, &my);

                    mx += get_se_golomb(&s->gb);

                    my += get_se_golomb(&s->gb);

                    tprintf(s->avctx, "final mv:%d %d\n", mx, my);

                    val= pack16to32(mx,my);

                }else

                    val=0;

                fill_rectangle(h->mv_cache[list][ scan8[0] ], 4, 4, 8, val, 4);

            }

        }

        else if(IS_16X8(mb_type)){

            for(list=0; list<h->list_count; list++){

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

                        unsigned int val;

                        if(IS_DIR(mb_type, i, list)){

                            val= get_te0_golomb(&s->gb, h->ref_count[list]);

                            if(val >= h->ref_count[list]){

                                av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);

                                return -1;

                            }

                        }else

                            val= LIST_NOT_USED&0xFF;

                        fill_rectangle(&h->ref_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 1);

                    }

            }

            for(list=0; list<h->list_count; list++){

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

                    unsigned int val;

                    if(IS_DIR(mb_type, i, list)){

                        pred_16x8_motion(h, 8*i, list, h->ref_cache[list][scan8[0] + 16*i], &mx, &my);

                        mx += get_se_golomb(&s->gb);

                        my += get_se_golomb(&s->gb);

                        tprintf(s->avctx, "final mv:%d %d\n", mx, my);

                        val= pack16to32(mx,my);

                    }else

                        val=0;

                    fill_rectangle(h->mv_cache[list][ scan8[0] + 16*i ], 4, 2, 8, val, 4);

                }

            }

        }else{

            assert(IS_8X16(mb_type));

            for(list=0; list<h->list_count; list++){

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

                        unsigned int val;

                        if(IS_DIR(mb_type, i, list)){ //FIXME optimize

                            val= get_te0_golomb(&s->gb, h->ref_count[list]);

                            if(val >= h->ref_count[list]){

                                av_log(h->s.avctx, AV_LOG_ERROR, "ref %u overflow\n", val);

                                return -1;

                            }

                        }else

                            val= LIST_NOT_USED&0xFF;

                        fill_rectangle(&h->ref_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 1);

                    }

            }

            for(list=0; list<h->list_count; list++){

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

                    unsigned int val;

                    if(IS_DIR(mb_type, i, list)){

                        pred_8x16_motion(h, i*4, list, h->ref_cache[list][ scan8[0] + 2*i ], &mx, &my);

                        mx += get_se_golomb(&s->gb);

                        my += get_se_golomb(&s->gb);

                        tprintf(s->avctx, "final mv:%d %d\n", mx, my);

                        val= pack16to32(mx,my);

                    }else

                        val=0;

                    fill_rectangle(h->mv_cache[list][ scan8[0] + 2*i ], 2, 4, 8, val, 4);

                }

            }

        }

    }

    if(IS_INTER(mb_type))

        write_back_motion(h, mb_type);

    if(!IS_INTRA16x16(mb_type)){

        cbp= get_ue_golomb(&s->gb);

        if(cbp > 47){

            av_log(h->s.avctx, AV_LOG_ERROR, "cbp too large (%u) at %d %d\n", cbp, s->mb_x, s->mb_y);

            return -1;

        }

        if(IS_INTRA4x4(mb_type))

            cbp= golomb_to_intra4x4_cbp[cbp];

        else

            cbp= golomb_to_inter_cbp[cbp];

    }

    h->cbp = cbp;

    if(dct8x8_allowed && (cbp&15) && !IS_INTRA(mb_type)){

        if(get_bits1(&s->gb))

            mb_type |= MB_TYPE_8x8DCT;

    }

    s->current_picture.mb_type[mb_xy]= mb_type;

    if(cbp || IS_INTRA16x16(mb_type)){

        int i8x8, i4x4, chroma_idx;

        int chroma_qp, dquant;

        GetBitContext *gb= IS_INTRA(mb_type) ? h->intra_gb_ptr : h->inter_gb_ptr;

        const uint8_t *scan, *scan8x8, *dc_scan;

//        fill_non_zero_count_cache(h);

        if(IS_INTERLACED(mb_type)){

            scan8x8= s->qscale ? h->field_scan8x8_cavlc : h->field_scan8x8_cavlc_q0;

            scan= s->qscale ? h->field_scan : h->field_scan_q0;

            dc_scan= luma_dc_field_scan;

        }else{

            scan8x8= s->qscale ? h->zigzag_scan8x8_cavlc : h->zigzag_scan8x8_cavlc_q0;

            scan= s->qscale ? h->zigzag_scan : h->zigzag_scan_q0;

            dc_scan= luma_dc_zigzag_scan;

        }

        dquant= get_se_golomb(&s->gb);

        if( dquant > 25 || dquant < -26 ){

            av_log(h->s.avctx, AV_LOG_ERROR, "dquant out of range (%d) at %d %d\n", dquant, s->mb_x, s->mb_y);

            return -1;

        }

        s->qscale += dquant;

        if(((unsigned)s->qscale) > 51){

            if(s->qscale<0) s->qscale+= 52;

            else            s->qscale-= 52;

        }

        h->chroma_qp= chroma_qp= get_chroma_qp(h->pps.chroma_qp_index_offset, s->qscale);

        if(IS_INTRA16x16(mb_type)){

            if( decode_residual(h, h->intra_gb_ptr, h->mb, LUMA_DC_BLOCK_INDEX, dc_scan, h->dequant4_coeff[0][s->qscale], 16) < 0){

                return -1; //FIXME continue if partitioned and other return -1 too

            }

            assert((cbp&15) == 0 || (cbp&15) == 15);

            if(cbp&15){

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

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

                        const int index= i4x4 + 4*i8x8;

                        if( decode_residual(h, h->intra_gb_ptr, h->mb + 16*index, index, scan + 1, h->dequant4_coeff[0][s->qscale], 15) < 0 ){

                            return -1;

                        }

                    }

                }

            }else{

                fill_rectangle(&h->non_zero_count_cache[scan8[0]], 4, 4, 8, 0, 1);

            }

        }else{

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

                if(cbp & (1<<i8x8)){

                    if(IS_8x8DCT(mb_type)){

                        DCTELEM *buf = &h->mb[64*i8x8];

                        uint8_t *nnz;

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

                            if( decode_residual(h, gb, buf, i4x4+4*i8x8, scan8x8+16*i4x4,

                                                h->dequant8_coeff[IS_INTRA( mb_type ) ? 0:1][s->qscale], 16) <0 )

                                return -1;

                        }

                        nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];

                        nnz[0] += nnz[1] + nnz[8] + nnz[9];

                    }else{

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

                            const int index= i4x4 + 4*i8x8;

                            if( decode_residual(h, gb, h->mb + 16*index, index, scan, h->dequant4_coeff[IS_INTRA( mb_type ) ? 0:3][s->qscale], 16) <0 ){

                                return -1;

                            }

                        }

                    }

                }else{

                    uint8_t * const nnz= &h->non_zero_count_cache[ scan8[4*i8x8] ];

                    nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;

                }

            }

        }

        if(cbp&0x30){

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

                if( decode_residual(h, gb, h->mb + 256 + 16*4*chroma_idx, CHROMA_DC_BLOCK_INDEX, chroma_dc_scan, NULL, 4) < 0){

                    return -1;

                }

        }

        if(cbp&0x20){

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

                const uint32_t *qmul = h->dequant4_coeff[chroma_idx+1+(IS_INTRA( mb_type ) ? 0:3)][chroma_qp];

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

                    const int index= 16 + 4*chroma_idx + i4x4;

                    if( decode_residual(h, gb, h->mb + 16*index, index, scan + 1, qmul, 15) < 0){

                        return -1;

                    }

                }

            }

        }else{

            uint8_t * const nnz= &h->non_zero_count_cache[0];

            nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =

            nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;

        }

    }else{

        uint8_t * const nnz= &h->non_zero_count_cache[0];

        fill_rectangle(&nnz[scan8[0]], 4, 4, 8, 0, 1);

        nnz[ scan8[16]+0 ] = nnz[ scan8[16]+1 ] =nnz[ scan8[16]+8 ] =nnz[ scan8[16]+9 ] =

        nnz[ scan8[20]+0 ] = nnz[ scan8[20]+1 ] =nnz[ scan8[20]+8 ] =nnz[ scan8[20]+9 ] = 0;

    }

    s->current_picture.qscale_table[mb_xy]= s->qscale;

    write_back_non_zero_count(h);

    if(MB_MBAFF){

        h->ref_count[0] >>= 1;

        h->ref_count[1] >>= 1;

    }

    return 0;

}


void pci_default_write_config(PCIDevice *d,

                              uint32_t address, uint32_t val, int len)

{

    int can_write, i;

    uint32_t end, addr;

    if (len == 4 && ((address >= 0x10 && address < 0x10 + 4 * 6) ||

                     (address >= 0x30 && address < 0x34))) {

        PCIIORegion *r;

        int reg;

        if ( address >= 0x30 ) {

            reg = PCI_ROM_SLOT;

        }else{

            reg = (address - 0x10) >> 2;

        }

        r = &d->io_regions[reg];

        if (r->size == 0)

            goto default_config;

        /* compute the stored value */

        if (reg == PCI_ROM_SLOT) {

            /* keep ROM enable bit */

            val &= (~(r->size - 1)) | 1;

        } else {

            val &= ~(r->size - 1);

            val |= r->type;

        }

        *(uint32_t *)(d->config + address) = cpu_to_le32(val);

        pci_update_mappings(d);

        return;

    }

 default_config:

    /* not efficient, but simple */

    addr = address;

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

        /* default read/write accesses */

        switch(d->config[0x0e]) {

        case 0x00:

        case 0x80:

            switch(addr) {

            case 0x00:

            case 0x01:

            case 0x02:

            case 0x03:

            case 0x08:

            case 0x09:

            case 0x0a:

            case 0x0b:

            case 0x0e:

            case 0x10 ... 0x27: /* base */

            case 0x30 ... 0x33: /* rom */

            case 0x3d:

                can_write = 0;

                break;

            default:

                can_write = 1;

                break;

            }

            break;

        default:

        case 0x01:

            switch(addr) {

            case 0x00:

            case 0x01:

            case 0x02:

            case 0x03:

            case 0x08:

            case 0x09:

            case 0x0a:

            case 0x0b:

            case 0x0e:

            case 0x38 ... 0x3b: /* rom */

            case 0x3d:

                can_write = 0;

                break;

            default:

                can_write = 1;

                break;

            }

            break;

        }

        if (can_write) {

            d->config[addr] = val;

        }

        addr++;

        val >>= 8;

    }

    end = address + len;

    if (end > PCI_COMMAND && address < (PCI_COMMAND + 2)) {

        /* if the command register is modified, we must modify the mappings */

        pci_update_mappings(d);

    }

}


static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s,

                             uint32_t length)

{

    int v, i;

    if (s->color_type == PNG_COLOR_TYPE_PALETTE) {

        if (length > 256 || !(s->state & PNG_PLTE))

            return AVERROR_INVALIDDATA;

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

            v = bytestream2_get_byte(&s->gb);

            s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24);

        }

    } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) {

        if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) ||

            (s->color_type == PNG_COLOR_TYPE_RGB && length != 6))

            return AVERROR_INVALIDDATA;

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

            /* only use the least significant bits */

            v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth);

            if (s->bit_depth > 8)

                AV_WB16(&s->transparent_color_be[2 * i], v);

            else

                s->transparent_color_be[i] = v;

        }

    } else {

        return AVERROR_INVALIDDATA;

    }

    bytestream2_skip(&s->gb, 4); /* crc */

    s->has_trns = 1;

    return 0;

}


static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,

                                       int S)

{

    unsigned bit;

    if (s->extra_bits) {

        S <<= s->extra_bits;

        if (s->got_extra_bits &&

            get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {

            S   |= get_bits_long(&s->gb_extra_bits, s->extra_bits);

            *crc = *crc * 9 + (S & 0xffff) * 3 + ((unsigned)S >> 16);

        }

    }

    bit = (S & s->and) | s->or;

    bit = ((S + bit) << s->shift) - bit;

    if (s->hybrid)

        bit = av_clip(bit, s->hybrid_minclip, s->hybrid_maxclip);

    return bit << s->post_shift;

}


target_ulong helper_ldl(CPUMIPSState *env, target_ulong arg1,

                        target_ulong arg2, int mem_idx)

{

    uint64_t tmp;

    tmp = do_lbu(env, arg2, mem_idx);

    arg1 = (arg1 & 0x00FFFFFFFFFFFFFFULL) | (tmp << 56);

    if (GET_LMASK64(arg2) <= 6) {

        tmp = do_lbu(env, GET_OFFSET(arg2, 1), mem_idx);

        arg1 = (arg1 & 0xFF00FFFFFFFFFFFFULL) | (tmp << 48);

    }

    if (GET_LMASK64(arg2) <= 5) {

        tmp = do_lbu(env, GET_OFFSET(arg2, 2), mem_idx);

        arg1 = (arg1 & 0xFFFF00FFFFFFFFFFULL) | (tmp << 40);

    }

    if (GET_LMASK64(arg2) <= 4) {

        tmp = do_lbu(env, GET_OFFSET(arg2, 3), mem_idx);

        arg1 = (arg1 & 0xFFFFFF00FFFFFFFFULL) | (tmp << 32);

    }

    if (GET_LMASK64(arg2) <= 3) {

        tmp = do_lbu(env, GET_OFFSET(arg2, 4), mem_idx);

        arg1 = (arg1 & 0xFFFFFFFF00FFFFFFULL) | (tmp << 24);

    }

    if (GET_LMASK64(arg2) <= 2) {

        tmp = do_lbu(env, GET_OFFSET(arg2, 5), mem_idx);

        arg1 = (arg1 & 0xFFFFFFFFFF00FFFFULL) | (tmp << 16);

    }

    if (GET_LMASK64(arg2) <= 1) {

        tmp = do_lbu(env, GET_OFFSET(arg2, 6), mem_idx);

        arg1 = (arg1 & 0xFFFFFFFFFFFF00FFULL) | (tmp << 8);

    }

    if (GET_LMASK64(arg2) == 0) {

        tmp = do_lbu(env, GET_OFFSET(arg2, 7), mem_idx);

        arg1 = (arg1 & 0xFFFFFFFFFFFFFF00ULL) | tmp;

    }

    return arg1;

}


static int load_matrix(MpegEncContext *s, uint16_t matrix0[64], uint16_t matrix1[64], int intra)

{

    int i;

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

        int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];

        int v = get_bits(&s->gb, 8);

        if (v == 0) {

            av_log(s->avctx, AV_LOG_ERROR, "matrix damaged\n");

            return -1;

        }

        if (intra && i == 0 && v != 8) {

            av_log(s->avctx, AV_LOG_ERROR, "intra matrix specifies invalid DC quantizer %d, ignoring\n", v);

            v = 8; // needed by pink.mpg / issue1046

        }

        matrix0[j] = v;

        if (matrix1)

            matrix1[j] = v;

    }

    return 0;

}


static void child_handler(int sig)

{

    int status;

    while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;

}


static int copy_from(IpvideoContext *s, AVFrame *src, AVFrame *dst, int delta_x, int delta_y)

{

    int current_offset = s->pixel_ptr - dst->data[0];

    int motion_offset = current_offset + delta_y * dst->linesize[0]

                       + delta_x * (1 + s->is_16bpp);

    if (motion_offset < 0) {

        av_log(s->avctx, AV_LOG_ERROR, " Interplay video: motion offset < 0 (%d)\n", motion_offset);

        return AVERROR_INVALIDDATA;

    } else if (motion_offset > s->upper_motion_limit_offset) {

        av_log(s->avctx, AV_LOG_ERROR, " Interplay video: motion offset above limit (%d >= %d)\n",

            motion_offset, s->upper_motion_limit_offset);

        return AVERROR_INVALIDDATA;

    }

    if (src->data[0] == NULL) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid decode type, corrupted header?\n");

        return AVERROR(EINVAL);

    }

    s->hdsp.put_pixels_tab[!s->is_16bpp][0](s->pixel_ptr, src->data[0] + motion_offset,

                                            dst->linesize[0], 8);

    return 0;

}


static void imx_epit_reset(DeviceState *dev)

{

    IMXEPITState *s = IMX_EPIT(dev);

    /*

     * Soft reset doesn't touch some bits; hard reset clears them

     */

    s->cr &= (CR_EN|CR_ENMOD|CR_STOPEN|CR_DOZEN|CR_WAITEN|CR_DBGEN);

    s->sr = 0;

    s->lr = TIMER_MAX;

    s->cmp = 0;

    s->cnt = 0;

    /* stop both timers */

    ptimer_stop(s->timer_cmp);

    ptimer_stop(s->timer_reload);

    /* compute new frequency */

    imx_epit_set_freq(s);

    /* init both timers to TIMER_MAX */

    ptimer_set_limit(s->timer_cmp, TIMER_MAX, 1);

    ptimer_set_limit(s->timer_reload, TIMER_MAX, 1);

    if (s->freq && (s->cr & CR_EN)) {

        /* if the timer is still enabled, restart it */

        ptimer_run(s->timer_reload, 0);

    }

}


static void quit_timers(void)

{

    alarm_timer->stop(alarm_timer);

    alarm_timer = NULL;

}


static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
    BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
    int64_t align, QEMUIOVector *qiov, int flags)
{
    BlockDriverState *bs = child->bs;
    BlockDriver *drv = bs->drv;
    bool waited;
    int ret;
    int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
    uint64_t bytes_remaining = bytes;
    int max_transfer;
    if (bdrv_has_readonly_bitmaps(bs)) {
        return -EPERM;
    assert(is_power_of_2(align));
    assert((offset & (align - 1)) == 0);
    assert((bytes & (align - 1)) == 0);
    assert(!qiov || bytes == qiov->size);
    assert((bs->open_flags & BDRV_O_NO_IO) == 0);
    assert(!(flags & ~BDRV_REQ_MASK));
    max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
                                   align);
    waited = wait_serialising_requests(req);
    assert(!waited || !req->serialising);
    assert(req->overlap_offset <= offset);
    assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
    assert(child->perm & BLK_PERM_WRITE);
    assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
    ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
    if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
        !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
        qemu_iovec_is_zero(qiov)) {
        flags |= BDRV_REQ_ZERO_WRITE;
        if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
            flags |= BDRV_REQ_MAY_UNMAP;
    if (ret < 0) {
        /* Do nothing, write notifier decided to fail this request */
    } else if (flags & BDRV_REQ_ZERO_WRITE) {
        bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
        ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
    } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
        ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
    } else if (bytes <= max_transfer) {
        bdrv_debug_event(bs, BLKDBG_PWRITEV);
        ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
    } else {
        bdrv_debug_event(bs, BLKDBG_PWRITEV);
        while (bytes_remaining) {
            int num = MIN(bytes_remaining, max_transfer);
            QEMUIOVector local_qiov;
            int local_flags = flags;
            assert(num);
            if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
                !(bs->supported_write_flags & BDRV_REQ_FUA)) {
                /* If FUA is going to be emulated by flush, we only
                 * need to flush on the last iteration */
                local_flags &= ~BDRV_REQ_FUA;
            qemu_iovec_init(&local_qiov, qiov->niov);
            qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
            ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
                                      num, &local_qiov, local_flags);
            qemu_iovec_destroy(&local_qiov);
            if (ret < 0) {
                break;
            bytes_remaining -= num;
    bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
    atomic_inc(&bs->write_gen);
    bdrv_set_dirty(bs, offset, bytes);
    stat64_max(&bs->wr_highest_offset, offset + bytes);
    if (ret >= 0) {
        bs->total_sectors = MAX(bs->total_sectors, end_sector);
        ret = 0;
    return ret;


static BlockDriverAIOCB *raw_aio_read(BlockDriverState *bs,

        int64_t sector_num, uint8_t *buf, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    RawAIOCB *acb;

    /*

     * If O_DIRECT is used and the buffer is not aligned fall back

     * to synchronous IO.

     */

    BDRVRawState *s = bs->opaque;

    if (unlikely(s->aligned_buf != NULL && ((uintptr_t) buf % 512))) {

        QEMUBH *bh;

        acb = qemu_aio_get(bs, cb, opaque);

        acb->ret = raw_pread(bs, 512 * sector_num, buf, 512 * nb_sectors);

        bh = qemu_bh_new(raw_aio_em_cb, acb);

        qemu_bh_schedule(bh);

        return &acb->common;

    }

    acb = raw_aio_setup(bs, sector_num, buf, nb_sectors, cb, opaque);

    if (!acb)

        return NULL;

    if (aio_read(&acb->aiocb) < 0) {

        qemu_aio_release(acb);

        return NULL;

    }

    return &acb->common;

}


static int coroutine_fn bdrv_co_do_readv(BdrvChild *child,

    int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,

    BdrvRequestFlags flags)

{

    if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {

        return -EINVAL;

    }

    return bdrv_co_preadv(child->bs, sector_num << BDRV_SECTOR_BITS,

                          nb_sectors << BDRV_SECTOR_BITS, qiov, flags);

}


static void sigchld_handler(int signal)

{

    qemu_bh_schedule(sigchld_bh);

}


static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)

{

    MpegTSFilter *tss;

    PESContext *pes;

    /* if no pid found, then add a pid context */

    pes = av_mallocz(sizeof(PESContext));

    if (!pes)

        return 0;

    pes->ts = ts;

    pes->stream = ts->stream;

    pes->pid = pid;

    pes->pcr_pid = pcr_pid;

    pes->stream_type = stream_type;

    pes->state = MPEGTS_SKIP;

    pes->pts = AV_NOPTS_VALUE;

    pes->dts = AV_NOPTS_VALUE;

    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);

    if (!tss) {

        av_free(pes);

        return 0;

    }

    return pes;

}


void mpeg_motion_internal(MpegEncContext *s,

                 uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,

                 int field_based, int bottom_field, int field_select,

                 uint8_t **ref_picture, op_pixels_func (*pix_op)[4],

                 int motion_x, int motion_y, int h, int is_mpeg12, int mb_y)

{

    uint8_t *ptr_y, *ptr_cb, *ptr_cr;

    int dxy, uvdxy, mx, my, src_x, src_y,

        uvsrc_x, uvsrc_y, v_edge_pos;

    emuedge_linesize_type uvlinesize, linesize;

#if 0

if(s->quarter_sample)

{

    motion_x>>=1;

    motion_y>>=1;

}

#endif

    v_edge_pos = s->v_edge_pos >> field_based;

    linesize   = s->current_picture.f.linesize[0] << field_based;

    uvlinesize = s->current_picture.f.linesize[1] << field_based;

    dxy = ((motion_y & 1) << 1) | (motion_x & 1);

    src_x = s->mb_x* 16               + (motion_x >> 1);

    src_y =(   mb_y<<(4-field_based)) + (motion_y >> 1);

    if (!is_mpeg12 && s->out_format == FMT_H263) {

        if((s->workaround_bugs & FF_BUG_HPEL_CHROMA) && field_based){

            mx = (motion_x>>1)|(motion_x&1);

            my = motion_y >>1;

            uvdxy = ((my & 1) << 1) | (mx & 1);

            uvsrc_x = s->mb_x* 8               + (mx >> 1);

            uvsrc_y =(   mb_y<<(3-field_based))+ (my >> 1);

        }else{

            uvdxy = dxy | (motion_y & 2) | ((motion_x & 2) >> 1);

            uvsrc_x = src_x>>1;

            uvsrc_y = src_y>>1;

        }

    }else if(!is_mpeg12 && s->out_format == FMT_H261){//even chroma mv's are full pel in H261

        mx = motion_x / 4;

        my = motion_y / 4;

        uvdxy = 0;

        uvsrc_x = s->mb_x*8 + mx;

        uvsrc_y =    mb_y*8 + my;

    } else {

        if(s->chroma_y_shift){

            mx = motion_x / 2;

            my = motion_y / 2;

            uvdxy = ((my & 1) << 1) | (mx & 1);

            uvsrc_x = s->mb_x* 8               + (mx >> 1);

            uvsrc_y =(   mb_y<<(3-field_based))+ (my >> 1);

        } else {

            if(s->chroma_x_shift){

            //Chroma422

                mx = motion_x / 2;

                uvdxy = ((motion_y & 1) << 1) | (mx & 1);

                uvsrc_x = s->mb_x* 8           + (mx >> 1);

                uvsrc_y = src_y;

            } else {

            //Chroma444

                uvdxy = dxy;

                uvsrc_x = src_x;

                uvsrc_y = src_y;

            }

        }

    }

    ptr_y  = ref_picture[0] + src_y * linesize + src_x;

    ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;

    ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;

    if(   (unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x&1) - 16, 0)

       || (unsigned)src_y > FFMAX(   v_edge_pos - (motion_y&1) - h , 0)){

            if(is_mpeg12 || s->codec_id == AV_CODEC_ID_MPEG2VIDEO ||

               s->codec_id == AV_CODEC_ID_MPEG1VIDEO){

                av_log(s->avctx,AV_LOG_DEBUG,

                        "MPEG motion vector out of boundary (%d %d)\n", src_x, src_y);

                return;

            }

            s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize,

                                17, 17+field_based,

                                src_x, src_y<<field_based,

                                s->h_edge_pos, s->v_edge_pos);

            ptr_y = s->edge_emu_buffer;

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

                uint8_t *uvbuf= s->edge_emu_buffer+18*s->linesize;

                s->vdsp.emulated_edge_mc(uvbuf ,

                                    ptr_cb, s->uvlinesize,

                                    9, 9+field_based,

                                    uvsrc_x, uvsrc_y<<field_based,

                                    s->h_edge_pos>>1, s->v_edge_pos>>1);

                s->vdsp.emulated_edge_mc(uvbuf+16,

                                    ptr_cr, s->uvlinesize,

                                    9, 9+field_based,

                                    uvsrc_x, uvsrc_y<<field_based,

                                    s->h_edge_pos>>1, s->v_edge_pos>>1);

                ptr_cb= uvbuf;

                ptr_cr= uvbuf+16;

            }

    }

    if(bottom_field){ //FIXME use this for field pix too instead of the obnoxious hack which changes picture.data

        dest_y += s->linesize;

        dest_cb+= s->uvlinesize;

        dest_cr+= s->uvlinesize;

    }

    if(field_select){

        ptr_y += s->linesize;

        ptr_cb+= s->uvlinesize;

        ptr_cr+= s->uvlinesize;

    }

    pix_op[0][dxy](dest_y, ptr_y, linesize, h);

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

        pix_op[s->chroma_x_shift][uvdxy]

                (dest_cb, ptr_cb, uvlinesize, h >> s->chroma_y_shift);

        pix_op[s->chroma_x_shift][uvdxy]

                (dest_cr, ptr_cr, uvlinesize, h >> s->chroma_y_shift);

    }

    if(!is_mpeg12 && (CONFIG_H261_ENCODER || CONFIG_H261_DECODER) &&

         s->out_format == FMT_H261){

        ff_h261_loop_filter(s);

    }

}


static void s390_virtio_irq(S390CPU *cpu, int config_change, uint64_t token)

{

    if (kvm_enabled()) {

        kvm_s390_virtio_irq(cpu, config_change, token);

    } else {

        cpu_inject_ext(cpu, VIRTIO_EXT_CODE, config_change, token);

    }

}


int ffurl_alloc(URLContext **puc, const char *filename, int flags,

                const AVIOInterruptCB *int_cb)

{

    URLProtocol *up = NULL;

    char proto_str[128], proto_nested[128], *ptr;

    size_t proto_len = strspn(filename, URL_SCHEME_CHARS);

    if (filename[proto_len] != ':' || is_dos_path(filename))

        strcpy(proto_str, "file");

    else

        av_strlcpy(proto_str, filename,

                   FFMIN(proto_len + 1, sizeof(proto_str)));

    av_strlcpy(proto_nested, proto_str, sizeof(proto_nested));

    if ((ptr = strchr(proto_nested, '+')))

        *ptr = '\0';

    while (up = ffurl_protocol_next(up)) {

        if (!strcmp(proto_str, up->name))

            return url_alloc_for_protocol(puc, up, filename, flags, int_cb);

        if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME &&

            !strcmp(proto_nested, up->name))

            return url_alloc_for_protocol(puc, up, filename, flags, int_cb);

    }

    *puc = NULL;

    return AVERROR_PROTOCOL_NOT_FOUND;

}


BlockDriverState *bdrv_next(BlockDriverState *bs)

{

    if (!bs) {

        return QTAILQ_FIRST(&bdrv_states);

    }

    return QTAILQ_NEXT(bs, device_list);

}


void mcf_uart_write(void *opaque, target_phys_addr_t addr,

                    uint64_t val, unsigned size)

{

    mcf_uart_state *s = (mcf_uart_state *)opaque;

    switch (addr & 0x3f) {

    case 0x00:

        s->mr[s->current_mr] = val;

        s->current_mr = 1;

        break;

    case 0x04:

        /* CSR is ignored.  */

        break;

    case 0x08: /* Command Register.  */

        mcf_do_command(s, val);

        break;

    case 0x0c: /* Transmit Buffer.  */

        s->sr &= ~MCF_UART_TxEMP;

        s->tb = val;

        mcf_uart_do_tx(s);

        break;

    case 0x10:

        /* ACR is ignored.  */

        break;

    case 0x14:

        s->imr = val;

        break;

    default:

        break;

    }

    mcf_uart_update(s);

}