static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)

{

    const int mb_x= s->mb_x;

    const int mb_y= s->mb_y;

    int i;

#if 0

        if (s->interlaced_dct) {

            dct_linesize = s->linesize * 2;

            dct_offset = s->linesize;

        } else {

            dct_linesize = s->linesize;

            dct_offset = s->linesize * 8;

        }

#endif

    if (s->mb_intra) {

        UINT8 *ptr;

        int wrap;

        wrap = s->linesize;

        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;

        get_pixels(s->block[0], ptr               , wrap);

        get_pixels(s->block[1], ptr            + 8, wrap);

        get_pixels(s->block[2], ptr + 8 * wrap    , wrap);

        get_pixels(s->block[3], ptr + 8 * wrap + 8, wrap);

        wrap >>=1;

        ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;

        get_pixels(s->block[4], ptr, wrap);

        ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;

        get_pixels(s->block[5], ptr, wrap);

    }else{

        op_pixels_func *op_pix;

        qpel_mc_func *op_qpix;

        UINT8 *dest_y, *dest_cb, *dest_cr;

        UINT8 *ptr;

        int wrap;

        dest_y  = s->current_picture[0] + (mb_y * 16 * s->linesize       ) + mb_x * 16;

        dest_cb = s->current_picture[1] + (mb_y * 8  * (s->linesize >> 1)) + mb_x * 8;

        dest_cr = s->current_picture[2] + (mb_y * 8  * (s->linesize >> 1)) + mb_x * 8;

        if ((!s->no_rounding) || s->pict_type==B_TYPE){

            op_pix = put_pixels_tab;

            op_qpix= qpel_mc_rnd_tab;

        }else{

            op_pix = put_no_rnd_pixels_tab;

            op_qpix= qpel_mc_no_rnd_tab;

        }

        if (s->mv_dir & MV_DIR_FORWARD) {

            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture, op_pix, op_qpix);

           if ((!s->no_rounding) || s->pict_type==B_TYPE)

                op_pix = avg_pixels_tab;

            else

                op_pix = avg_no_rnd_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_BACKWARD) {

            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture, op_pix, op_qpix);

        }

        wrap = s->linesize;

        ptr = s->new_picture[0] + (mb_y * 16 * wrap) + mb_x * 16;

        diff_pixels(s->block[0], ptr               , dest_y               , wrap);

        diff_pixels(s->block[1], ptr            + 8, dest_y            + 8, wrap);

        diff_pixels(s->block[2], ptr + 8 * wrap    , dest_y + 8 * wrap    , wrap);

        diff_pixels(s->block[3], ptr + 8 * wrap + 8, dest_y + 8 * wrap + 8, wrap);

        wrap >>=1;

        ptr = s->new_picture[1] + (mb_y * 8 * wrap) + mb_x * 8;

        diff_pixels(s->block[4], ptr, dest_cb, wrap);

        ptr = s->new_picture[2] + (mb_y * 8 * wrap) + mb_x * 8;

        diff_pixels(s->block[5], ptr, dest_cr, wrap);

    }

#if 0

            {

                float adap_parm;

                adap_parm = ((s->avg_mb_var << 1) + s->mb_var[s->mb_width*mb_y+mb_x] + 1.0) /

                            ((s->mb_var[s->mb_width*mb_y+mb_x] << 1) + s->avg_mb_var + 1.0);

                printf("\ntype=%c qscale=%2d adap=%0.2f dquant=%4.2f var=%4d avgvar=%4d",

                        (s->mb_type[s->mb_width*mb_y+mb_x] > 0) ? 'I' : 'P',

                        s->qscale, adap_parm, s->qscale*adap_parm,

                        s->mb_var[s->mb_width*mb_y+mb_x], s->avg_mb_var);

            }

#endif

    /* DCT & quantize */

    if (s->h263_msmpeg4) {

        msmpeg4_dc_scale(s);

    } else if (s->h263_pred) {

        h263_dc_scale(s);

    } else {

        /* default quantization values */

        s->y_dc_scale = 8;

        s->c_dc_scale = 8;

    }

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

        s->block_last_index[i] = dct_quantize(s, s->block[i], i, s->qscale);

    }

    /* huffman encode */

    switch(s->out_format) {

    case FMT_MPEG1:

        mpeg1_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case FMT_H263:

        if (s->h263_msmpeg4)

            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);

        else if(s->h263_pred)

            mpeg4_encode_mb(s, s->block, motion_x, motion_y);

        else

            h263_encode_mb(s, s->block, motion_x, motion_y);

        break;

    case FMT_MJPEG:

        mjpeg_encode_mb(s, s->block);

        break;

    }

}


static int acpi_load_old(QEMUFile *f, void *opaque, int version_id)

{

    PIIX4PMState *s = opaque;

    int ret, i;

    uint16_t temp;

    ret = pci_device_load(&s->dev, f);

    if (ret < 0) {

        return ret;

    }

    qemu_get_be16s(f, &s->ar.pm1.evt.sts);

    qemu_get_be16s(f, &s->ar.pm1.evt.en);

    qemu_get_be16s(f, &s->ar.pm1.cnt.cnt);

    ret = vmstate_load_state(f, &vmstate_apm, opaque, 1);

    if (ret) {

        return ret;

    }

    qemu_get_timer(f, s->ar.tmr.timer);

    qemu_get_sbe64s(f, &s->ar.tmr.overflow_time);

    qemu_get_be16s(f, (uint16_t *)s->ar.gpe.sts);

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

        qemu_get_be16s(f, &temp);

    }

    qemu_get_be16s(f, (uint16_t *)s->ar.gpe.en);

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

        qemu_get_be16s(f, &temp);

    }

    ret = vmstate_load_state(f, &vmstate_pci_status, opaque, 1);

    return ret;

}


static int debugcon_parse(const char *devname)

{

    QemuOpts *opts;

    if (!qemu_chr_new("debugcon", devname, NULL)) {

        exit(1);

    }

    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1);

    if (!opts) {

        fprintf(stderr, "qemu: already have a debugcon device\n");

        exit(1);

    }

    qemu_opt_set(opts, "driver", "isa-debugcon");

    qemu_opt_set(opts, "chardev", "debugcon");

    return 0;

}


static CCIDBus *ccid_bus_new(DeviceState *dev)

{

    CCIDBus *bus;

    bus = FROM_QBUS(CCIDBus, qbus_create(&ccid_bus_info, dev, NULL));

    bus->qbus.allow_hotplug = 1;

    return bus;

}


bool bitmap_test_and_clear_atomic(unsigned long *map, long start, long nr)
{
    unsigned long *p = map + BIT_WORD(start);
    const long size = start + nr;
    int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
    unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);
    unsigned long dirty = 0;
    unsigned long old_bits;
    /* First word */
    if (nr - bits_to_clear > 0) {
        old_bits = atomic_fetch_and(p, ~mask_to_clear);
        dirty |= old_bits & mask_to_clear;
        nr -= bits_to_clear;
        bits_to_clear = BITS_PER_LONG;
        mask_to_clear = ~0UL;
        p++;
    }
    /* Full words */
    if (bits_to_clear == BITS_PER_LONG) {
        while (nr >= BITS_PER_LONG) {
            if (*p) {
                old_bits = atomic_xchg(p, 0);
                dirty |= old_bits;
            }
            nr -= BITS_PER_LONG;
            p++;
        }
    }
    /* Last word */
    if (nr) {
        mask_to_clear &= BITMAP_LAST_WORD_MASK(size);
        old_bits = atomic_fetch_and(p, ~mask_to_clear);
        dirty |= old_bits & mask_to_clear;
    } else {
        if (!dirty) {
            smp_mb();
        }
    }
    return dirty != 0;
}


int ff_dca_lbr_parse(DCALbrDecoder *s, uint8_t *data, DCAExssAsset *asset)

{

    struct {

        LBRChunk    lfe;

        LBRChunk    tonal;

        LBRChunk    tonal_grp[5];

        LBRChunk    grid1[DCA_LBR_CHANNELS / 2];

        LBRChunk    hr_grid[DCA_LBR_CHANNELS / 2];

        LBRChunk    ts1[DCA_LBR_CHANNELS / 2];

        LBRChunk    ts2[DCA_LBR_CHANNELS / 2];

    } chunk = { 0 };

    GetByteContext gb;

    int i, ch, sb, sf, ret, group, chunk_id, chunk_len;

    bytestream2_init(&gb, data + asset->lbr_offset, asset->lbr_size);

    // LBR sync word

    if (bytestream2_get_be32(&gb) != DCA_SYNCWORD_LBR) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR sync word\n");

        return AVERROR_INVALIDDATA;

    }

    // LBR header type

    switch (bytestream2_get_byte(&gb)) {

    case LBR_HEADER_SYNC_ONLY:

        if (!s->sample_rate) {

            av_log(s->avctx, AV_LOG_ERROR, "LBR decoder not initialized\n");

            return AVERROR_INVALIDDATA;

        }

        break;

    case LBR_HEADER_DECODER_INIT:

        if ((ret = parse_decoder_init(s, &gb)) < 0) {

            s->sample_rate = 0;

            return ret;

        }

        break;

    default:

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

        return AVERROR_INVALIDDATA;

    }

    // LBR frame chunk header

    chunk_id = bytestream2_get_byte(&gb);

    chunk_len = (chunk_id & 0x80) ? bytestream2_get_be16(&gb) : bytestream2_get_byte(&gb);

    if (chunk_len > bytestream2_get_bytes_left(&gb)) {

        chunk_len = bytestream2_get_bytes_left(&gb);

        av_log(s->avctx, AV_LOG_WARNING, "LBR frame chunk was truncated\n");

        if (s->avctx->err_recognition & AV_EF_EXPLODE)

            return AVERROR_INVALIDDATA;

    }

    bytestream2_init(&gb, gb.buffer, chunk_len);

    switch (chunk_id & 0x7f) {

    case LBR_CHUNK_FRAME:

        if (s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL)) {

            int checksum = bytestream2_get_be16(&gb);

            uint16_t res = chunk_id;

            res += (chunk_len >> 8) & 0xff;

            res += chunk_len & 0xff;

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

                res += gb.buffer[i];

            if (checksum != res) {

                av_log(s->avctx, AV_LOG_WARNING, "Invalid LBR checksum\n");

                if (s->avctx->err_recognition & AV_EF_EXPLODE)

                    return AVERROR_INVALIDDATA;

            }

        } else {

            bytestream2_skip(&gb, 2);

        }

        break;

    case LBR_CHUNK_FRAME_NO_CSUM:

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR frame chunk ID\n");

        return AVERROR_INVALIDDATA;

    }

    // Clear current frame

    memset(s->quant_levels, 0, sizeof(s->quant_levels));

    memset(s->sb_indices, 0xff, sizeof(s->sb_indices));

    memset(s->sec_ch_sbms, 0, sizeof(s->sec_ch_sbms));

    memset(s->sec_ch_lrms, 0, sizeof(s->sec_ch_lrms));

    memset(s->ch_pres, 0, sizeof(s->ch_pres));

    memset(s->grid_1_scf, 0, sizeof(s->grid_1_scf));

    memset(s->grid_2_scf, 0, sizeof(s->grid_2_scf));

    memset(s->grid_3_avg, 0, sizeof(s->grid_3_avg));

    memset(s->grid_3_scf, 0, sizeof(s->grid_3_scf));

    memset(s->grid_3_pres, 0, sizeof(s->grid_3_pres));

    memset(s->tonal_scf, 0, sizeof(s->tonal_scf));

    memset(s->lfe_data, 0, sizeof(s->lfe_data));

    s->part_stereo_pres = 0;

    s->framenum = (s->framenum + 1) & 31;

    for (ch = 0; ch < s->nchannels; ch++) {

        for (sb = 0; sb < s->nsubbands / 4; sb++) {

            s->part_stereo[ch][sb][0] = s->part_stereo[ch][sb][4];

            s->part_stereo[ch][sb][4] = 16;

        }

    }

    memset(s->lpc_coeff[s->framenum & 1], 0, sizeof(s->lpc_coeff[0]));

    for (group = 0; group < 5; group++) {

        for (sf = 0; sf < 1 << group; sf++) {

            int sf_idx = ((s->framenum << group) + sf) & 31;

            s->tonal_bounds[group][sf_idx][0] =

            s->tonal_bounds[group][sf_idx][1] = s->ntones;

        }

    }

    // Parse chunk headers

    while (bytestream2_get_bytes_left(&gb) > 0) {

        chunk_id = bytestream2_get_byte(&gb);

        chunk_len = (chunk_id & 0x80) ? bytestream2_get_be16(&gb) : bytestream2_get_byte(&gb);

        chunk_id &= 0x7f;

        if (chunk_len > bytestream2_get_bytes_left(&gb)) {

            chunk_len = bytestream2_get_bytes_left(&gb);

            av_log(s->avctx, AV_LOG_WARNING, "LBR chunk %#x was truncated\n", chunk_id);

            if (s->avctx->err_recognition & AV_EF_EXPLODE)

                return AVERROR_INVALIDDATA;

        }

        switch (chunk_id) {

        case LBR_CHUNK_LFE:

            chunk.lfe.len  = chunk_len;

            chunk.lfe.data = gb.buffer;

            break;

        case LBR_CHUNK_SCF:

        case LBR_CHUNK_TONAL:

        case LBR_CHUNK_TONAL_SCF:

            chunk.tonal.id   = chunk_id;

            chunk.tonal.len  = chunk_len;

            chunk.tonal.data = gb.buffer;

            break;

        case LBR_CHUNK_TONAL_GRP_1:

        case LBR_CHUNK_TONAL_GRP_2:

        case LBR_CHUNK_TONAL_GRP_3:

        case LBR_CHUNK_TONAL_GRP_4:

        case LBR_CHUNK_TONAL_GRP_5:

            i = LBR_CHUNK_TONAL_GRP_5 - chunk_id;

            chunk.tonal_grp[i].id   = i;

            chunk.tonal_grp[i].len  = chunk_len;

            chunk.tonal_grp[i].data = gb.buffer;

            break;

        case LBR_CHUNK_TONAL_SCF_GRP_1:

        case LBR_CHUNK_TONAL_SCF_GRP_2:

        case LBR_CHUNK_TONAL_SCF_GRP_3:

        case LBR_CHUNK_TONAL_SCF_GRP_4:

        case LBR_CHUNK_TONAL_SCF_GRP_5:

            i = LBR_CHUNK_TONAL_SCF_GRP_5 - chunk_id;

            chunk.tonal_grp[i].id   = i;

            chunk.tonal_grp[i].len  = chunk_len;

            chunk.tonal_grp[i].data = gb.buffer;

            break;

        case LBR_CHUNK_RES_GRID_LR:

        case LBR_CHUNK_RES_GRID_LR + 1:

        case LBR_CHUNK_RES_GRID_LR + 2:

            i = chunk_id - LBR_CHUNK_RES_GRID_LR;

            chunk.grid1[i].len  = chunk_len;

            chunk.grid1[i].data = gb.buffer;

            break;

        case LBR_CHUNK_RES_GRID_HR:

        case LBR_CHUNK_RES_GRID_HR + 1:

        case LBR_CHUNK_RES_GRID_HR + 2:

            i = chunk_id - LBR_CHUNK_RES_GRID_HR;

            chunk.hr_grid[i].len  = chunk_len;

            chunk.hr_grid[i].data = gb.buffer;

            break;

        case LBR_CHUNK_RES_TS_1:

        case LBR_CHUNK_RES_TS_1 + 1:

        case LBR_CHUNK_RES_TS_1 + 2:

            i = chunk_id - LBR_CHUNK_RES_TS_1;

            chunk.ts1[i].len  = chunk_len;

            chunk.ts1[i].data = gb.buffer;

            break;

        case LBR_CHUNK_RES_TS_2:

        case LBR_CHUNK_RES_TS_2 + 1:

        case LBR_CHUNK_RES_TS_2 + 2:

            i = chunk_id - LBR_CHUNK_RES_TS_2;

            chunk.ts2[i].len  = chunk_len;

            chunk.ts2[i].data = gb.buffer;

            break;

        }

        bytestream2_skip(&gb, chunk_len);

    }

    // Parse the chunks

    ret = parse_lfe_chunk(s, &chunk.lfe);

    ret |= parse_tonal_chunk(s, &chunk.tonal);

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

        ret |= parse_tonal_group(s, &chunk.tonal_grp[i]);

    for (i = 0; i < (s->nchannels + 1) / 2; i++) {

        int ch1 = i * 2;

        int ch2 = FFMIN(ch1 + 1, s->nchannels - 1);

        if (parse_grid_1_chunk (s, &chunk.grid1  [i], ch1, ch2) < 0 ||

            parse_high_res_grid(s, &chunk.hr_grid[i], ch1, ch2) < 0) {

            ret = -1;

            continue;

        }

        // TS chunks depend on both grids. TS_2 depends on TS_1.

        if (!chunk.grid1[i].len || !chunk.hr_grid[i].len || !chunk.ts1[i].len)

            continue;

        if (parse_ts1_chunk(s, &chunk.ts1[i], ch1, ch2) < 0 ||

            parse_ts2_chunk(s, &chunk.ts2[i], ch1, ch2) < 0) {

            ret = -1;

            continue;

        }

    }

    if (ret < 0 && (s->avctx->err_recognition & AV_EF_EXPLODE))

        return AVERROR_INVALIDDATA;

    return 0;

}


static int blk_mig_save_bulked_block(Monitor *mon, QEMUFile *f)

{

    int64_t completed_sector_sum = 0;

    BlkMigDevState *bmds;

    int progress;

    int ret = 0;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {

        if (bmds->bulk_completed == 0) {

            if (mig_save_device_bulk(mon, f, bmds) == 1) {

                /* completed bulk section for this device */

                bmds->bulk_completed = 1;

            }

            completed_sector_sum += bmds->completed_sectors;

            ret = 1;

            break;

        } else {

            completed_sector_sum += bmds->completed_sectors;

        }

    }

    progress = completed_sector_sum * 100 / block_mig_state.total_sector_sum;

    if (progress != block_mig_state.prev_progress) {

        block_mig_state.prev_progress = progress;

        qemu_put_be64(f, (progress << BDRV_SECTOR_BITS)

                         | BLK_MIG_FLAG_PROGRESS);

        monitor_printf(mon, "Completed %d %%\r", progress);

        monitor_flush(mon);

    }

    return ret;

}


int net_init_tap(const NetClientOptions *opts, const char *name,
                 NetClientState *peer)
{
    const NetdevTapOptions *tap;
    int fd, vnet_hdr = 0, i = 0, queues;
    /* for the no-fd, no-helper case */
    const char *script = NULL; /* suppress wrong "uninit'd use" gcc warning */
    const char *downscript = NULL;
    const char *vhostfdname;
    char ifname[128];
    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP);
    tap = opts->tap;
    queues = tap->has_queues ? tap->queues : 1;
    vhostfdname = tap->has_vhostfd ? tap->vhostfd : NULL;
    if (tap->has_fd) {
        if (tap->has_ifname || tap->has_script || tap->has_downscript ||
            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||
            tap->has_fds) {
            error_report("ifname=, script=, downscript=, vnet_hdr=, "
                         "helper=, queues=, and fds= are invalid with fd=");
        fd = monitor_handle_fd_param(cur_mon, tap->fd);
        if (fd == -1) {
        fcntl(fd, F_SETFL, O_NONBLOCK);
        vnet_hdr = tap_probe_vnet_hdr(fd);
        if (net_init_tap_one(tap, peer, "tap", name, NULL,
                             script, downscript,
                             vhostfdname, vnet_hdr, fd)) {
    } else if (tap->has_fds) {
        char *fds[MAX_TAP_QUEUES];
        char *vhost_fds[MAX_TAP_QUEUES];
        int nfds, nvhosts;
        if (tap->has_ifname || tap->has_script || tap->has_downscript ||
            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||
            tap->has_fd) {
            error_report("ifname=, script=, downscript=, vnet_hdr=, "
                         "helper=, queues=, and fd= are invalid with fds=");
        nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES);
        if (tap->has_vhostfds) {
            nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES);
            if (nfds != nvhosts) {
                error_report("The number of fds passed does not match the "
                             "number of vhostfds passed");
        for (i = 0; i < nfds; i++) {
            fd = monitor_handle_fd_param(cur_mon, fds[i]);
            if (fd == -1) {
            fcntl(fd, F_SETFL, O_NONBLOCK);
            if (i == 0) {
                vnet_hdr = tap_probe_vnet_hdr(fd);
            } else if (vnet_hdr != tap_probe_vnet_hdr(fd)) {
                error_report("vnet_hdr not consistent across given tap fds");
            if (net_init_tap_one(tap, peer, "tap", name, ifname,
                                 script, downscript,
                                 tap->has_vhostfds ? vhost_fds[i] : NULL,
                                 vnet_hdr, fd)) {
    } else if (tap->has_helper) {
        if (tap->has_ifname || tap->has_script || tap->has_downscript ||
            tap->has_vnet_hdr || tap->has_queues || tap->has_fds) {
            error_report("ifname=, script=, downscript=, and vnet_hdr= "
                         "queues=, and fds= are invalid with helper=");
        fd = net_bridge_run_helper(tap->helper, DEFAULT_BRIDGE_INTERFACE);
        if (fd == -1) {
        fcntl(fd, F_SETFL, O_NONBLOCK);
        vnet_hdr = tap_probe_vnet_hdr(fd);
        if (net_init_tap_one(tap, peer, "bridge", name, ifname,
                             script, downscript, vhostfdname,
                             vnet_hdr, fd)) {
    } else {
        script = tap->has_script ? tap->script : DEFAULT_NETWORK_SCRIPT;
        downscript = tap->has_downscript ? tap->downscript :
            DEFAULT_NETWORK_DOWN_SCRIPT;
        if (tap->has_ifname) {
            pstrcpy(ifname, sizeof ifname, tap->ifname);
        } else {
            ifname[0] = '\0';
        for (i = 0; i < queues; i++) {
            fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script,
                              ifname, sizeof ifname, queues > 1);
            if (fd == -1) {
            if (queues > 1 && i == 0 && !tap->has_ifname) {
                if (tap_fd_get_ifname(fd, ifname)) {
                    error_report("Fail to get ifname");
            if (net_init_tap_one(tap, peer, "tap", name, ifname,
                                 i >= 1 ? "no" : script,
                                 i >= 1 ? "no" : downscript,
                                 vhostfdname, vnet_hdr, fd)) {
    return 0;


static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,

                   uint8_t *properties)

{

    int compno;

    if (bytestream2_get_bytes_left(&s->g) < 1)

        return AVERROR_INVALIDDATA;

    compno              = bytestream2_get_byteu(&s->g);

    properties[compno] |= HAD_QCC;

    return get_qcx(s, n - 1, q + compno);

}


static void vfio_pci_load_rom(VFIODevice *vdev)

{

    struct vfio_region_info reg_info = {

        .argsz = sizeof(reg_info),

        .index = VFIO_PCI_ROM_REGION_INDEX

    };

    uint64_t size;

    off_t off = 0;

    size_t bytes;

    if (ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info)) {

        error_report("vfio: Error getting ROM info: %m");

        return;

    }

    DPRINTF("Device %04x:%02x:%02x.%x ROM:\n", vdev->host.domain,

            vdev->host.bus, vdev->host.slot, vdev->host.function);

    DPRINTF("  size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",

            (unsigned long)reg_info.size, (unsigned long)reg_info.offset,

            (unsigned long)reg_info.flags);

    vdev->rom_size = size = reg_info.size;

    vdev->rom_offset = reg_info.offset;

    if (!vdev->rom_size) {

        error_report("vfio-pci: Cannot read device rom at "

                    "%04x:%02x:%02x.%x\n",

                    vdev->host.domain, vdev->host.bus, vdev->host.slot,

                    vdev->host.function);

        error_printf("Device option ROM contents are probably invalid "

                    "(check dmesg).\nSkip option ROM probe with rombar=0, "

                    "or load from file with romfile=\n");

        return;

    }

    vdev->rom = g_malloc(size);

    memset(vdev->rom, 0xff, size);

    while (size) {

        bytes = pread(vdev->fd, vdev->rom + off, size, vdev->rom_offset + off);

        if (bytes == 0) {

            break;

        } else if (bytes > 0) {

            off += bytes;

            size -= bytes;

        } else {

            if (errno == EINTR || errno == EAGAIN) {

                continue;

            }

            error_report("vfio: Error reading device ROM: %m");

            break;

        }

    }

}


static void tcg_out_op (TCGContext *s, TCGOpcode opc, const TCGArg *args,

                        const int *const_args)

{

    int c;

    switch (opc) {

    case INDEX_op_exit_tb:

        tcg_out_movi (s, TCG_TYPE_I64, TCG_REG_R3, args[0]);

        tcg_out_b (s, 0, (tcg_target_long) tb_ret_addr);

        break;

    case INDEX_op_goto_tb:

        if (s->tb_jmp_offset) {

            /* direct jump method */

            s->tb_jmp_offset[args[0]] = s->code_ptr - s->code_buf;

            s->code_ptr += 28;

        }

        else {

            tcg_abort ();

        }

        s->tb_next_offset[args[0]] = s->code_ptr - s->code_buf;

        break;

    case INDEX_op_br:

        {

            TCGLabel *l = &s->labels[args[0]];

            if (l->has_value) {

                tcg_out_b (s, 0, l->u.value);

            }

            else {

                uint32_t val = *(uint32_t *) s->code_ptr;

                /* Thanks to Andrzej Zaborowski */

                tcg_out32 (s, B | (val & 0x3fffffc));

                tcg_out_reloc (s, s->code_ptr - 4, R_PPC_REL24, args[0], 0);

            }

        }

        break;

    case INDEX_op_call:

        tcg_out_call (s, args[0], const_args[0]);

        break;

    case INDEX_op_jmp:

        if (const_args[0]) {

            tcg_out_b (s, 0, args[0]);

        }

        else {

            tcg_out32 (s, MTSPR | RS (args[0]) | CTR);

            tcg_out32 (s, BCCTR | BO_ALWAYS);

        }

        break;

    case INDEX_op_movi_i32:

        tcg_out_movi (s, TCG_TYPE_I32, args[0], args[1]);

        break;

    case INDEX_op_movi_i64:

        tcg_out_movi (s, TCG_TYPE_I64, args[0], args[1]);

        break;

    case INDEX_op_ld8u_i32:

    case INDEX_op_ld8u_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LBZ, LBZX);

        break;

    case INDEX_op_ld8s_i32:

    case INDEX_op_ld8s_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LBZ, LBZX);

        tcg_out32 (s, EXTSB | RS (args[0]) | RA (args[0]));

        break;

    case INDEX_op_ld16u_i32:

    case INDEX_op_ld16u_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LHZ, LHZX);

        break;

    case INDEX_op_ld16s_i32:

    case INDEX_op_ld16s_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LHA, LHAX);

        break;

    case INDEX_op_ld_i32:

    case INDEX_op_ld32u_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], LWZ, LWZX);

        break;

    case INDEX_op_ld32s_i64:

        tcg_out_ldsta (s, args[0], args[1], args[2], LWA, LWAX);

        break;

    case INDEX_op_ld_i64:

        tcg_out_ldsta (s, args[0], args[1], args[2], LD, LDX);

        break;

    case INDEX_op_st8_i32:

    case INDEX_op_st8_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], STB, STBX);

        break;

    case INDEX_op_st16_i32:

    case INDEX_op_st16_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], STH, STHX);

        break;

    case INDEX_op_st_i32:

    case INDEX_op_st32_i64:

        tcg_out_ldst (s, args[0], args[1], args[2], STW, STWX);

        break;

    case INDEX_op_st_i64:

        tcg_out_ldsta (s, args[0], args[1], args[2], STD, STDX);

        break;

    case INDEX_op_add_i32:

        if (const_args[2])

            ppc_addi32 (s, args[0], args[1], args[2]);

        else

            tcg_out32 (s, ADD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_sub_i32:

        if (const_args[2])

            ppc_addi32 (s, args[0], args[1], -args[2]);

        else

            tcg_out32 (s, SUBF | TAB (args[0], args[2], args[1]));

        break;

    case INDEX_op_and_i64:

    case INDEX_op_and_i32:

        if (const_args[2]) {

            if ((args[2] & 0xffff) == args[2])

                tcg_out32 (s, ANDI | RS (args[1]) | RA (args[0]) | args[2]);

            else if ((args[2] & 0xffff0000) == args[2])

                tcg_out32 (s, ANDIS | RS (args[1]) | RA (args[0])

                           | ((args[2] >> 16) & 0xffff));

            else {

                tcg_out_movi (s, (opc == INDEX_op_and_i32

                                  ? TCG_TYPE_I32

                                  : TCG_TYPE_I64),

                              0, args[2]);

                tcg_out32 (s, AND | SAB (args[1], args[0], 0));

            }

        }

        else

            tcg_out32 (s, AND | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_or_i64:

    case INDEX_op_or_i32:

        if (const_args[2]) {

            if (args[2] & 0xffff) {

                tcg_out32 (s, ORI | RS (args[1]) | RA (args[0])

                           | (args[2] & 0xffff));

                if (args[2] >> 16)

                    tcg_out32 (s, ORIS | RS (args[0])  | RA (args[0])

                               | ((args[2] >> 16) & 0xffff));

            }

            else {

                tcg_out32 (s, ORIS | RS (args[1])  | RA (args[0])

                           | ((args[2] >> 16) & 0xffff));

            }

        }

        else

            tcg_out32 (s, OR | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_xor_i64:

    case INDEX_op_xor_i32:

        if (const_args[2]) {

            if ((args[2] & 0xffff) == args[2])

                tcg_out32 (s, XORI | RS (args[1])  | RA (args[0])

                           | (args[2] & 0xffff));

            else if ((args[2] & 0xffff0000) == args[2])

                tcg_out32 (s, XORIS | RS (args[1])  | RA (args[0])

                           | ((args[2] >> 16) & 0xffff));

            else {

                tcg_out_movi (s, (opc == INDEX_op_and_i32

                                  ? TCG_TYPE_I32

                                  : TCG_TYPE_I64),

                              0, args[2]);

                tcg_out32 (s, XOR | SAB (args[1], args[0], 0));

            }

        }

        else

            tcg_out32 (s, XOR | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_mul_i32:

        if (const_args[2]) {

            if (args[2] == (int16_t) args[2])

                tcg_out32 (s, MULLI | RT (args[0]) | RA (args[1])

                           | (args[2] & 0xffff));

            else {

                tcg_out_movi (s, TCG_TYPE_I32, 0, args[2]);

                tcg_out32 (s, MULLW | TAB (args[0], args[1], 0));

            }

        }

        else

            tcg_out32 (s, MULLW | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_div_i32:

        tcg_out32 (s, DIVW | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_divu_i32:

        tcg_out32 (s, DIVWU | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_rem_i32:

        tcg_out32 (s, DIVW | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLW | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_remu_i32:

        tcg_out32 (s, DIVWU | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLW | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_shl_i32:

        if (const_args[2]) {

            tcg_out32 (s, (RLWINM

                           | RA (args[0])

                           | RS (args[1])

                           | SH (args[2])

                           | MB (0)

                           | ME (31 - args[2])

                           )

                );

        }

        else

            tcg_out32 (s, SLW | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_shr_i32:

        if (const_args[2]) {

            tcg_out32 (s, (RLWINM

                           | RA (args[0])

                           | RS (args[1])

                           | SH (32 - args[2])

                           | MB (args[2])

                           | ME (31)

                           )

                );

        }

        else

            tcg_out32 (s, SRW | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_sar_i32:

        if (const_args[2])

            tcg_out32 (s, SRAWI | RS (args[1]) | RA (args[0]) | SH (args[2]));

        else

            tcg_out32 (s, SRAW | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_brcond_i32:

        tcg_out_brcond (s, args[2], args[0], args[1], const_args[1], args[3], 0);

        break;

    case INDEX_op_brcond_i64:

        tcg_out_brcond (s, args[2], args[0], args[1], const_args[1], args[3], 1);

        break;

    case INDEX_op_neg_i32:

    case INDEX_op_neg_i64:

        tcg_out32 (s, NEG | RT (args[0]) | RA (args[1]));

        break;

    case INDEX_op_not_i32:

    case INDEX_op_not_i64:

        tcg_out32 (s, NOR | SAB (args[1], args[0], args[1]));

        break;

    case INDEX_op_add_i64:

        if (const_args[2])

            ppc_addi64 (s, args[0], args[1], args[2]);

        else

            tcg_out32 (s, ADD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_sub_i64:

        if (const_args[2])

            ppc_addi64 (s, args[0], args[1], -args[2]);

        else

            tcg_out32 (s, SUBF | TAB (args[0], args[2], args[1]));

        break;

    case INDEX_op_shl_i64:

        if (const_args[2])

            tcg_out_rld (s, RLDICR, args[0], args[1], args[2], 63 - args[2]);

        else

            tcg_out32 (s, SLD | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_shr_i64:

        if (const_args[2])

            tcg_out_rld (s, RLDICL, args[0], args[1], 64 - args[2], args[2]);

        else

            tcg_out32 (s, SRD | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_sar_i64:

        if (const_args[2]) {

            int sh = SH (args[2] & 0x1f) | (((args[2] >> 5) & 1) << 1);

            tcg_out32 (s, SRADI | RA (args[0]) | RS (args[1]) | sh);

        }

        else

            tcg_out32 (s, SRAD | SAB (args[1], args[0], args[2]));

        break;

    case INDEX_op_mul_i64:

        tcg_out32 (s, MULLD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_div_i64:

        tcg_out32 (s, DIVD | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_divu_i64:

        tcg_out32 (s, DIVDU | TAB (args[0], args[1], args[2]));

        break;

    case INDEX_op_rem_i64:

        tcg_out32 (s, DIVD | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLD | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_remu_i64:

        tcg_out32 (s, DIVDU | TAB (0, args[1], args[2]));

        tcg_out32 (s, MULLD | TAB (0, 0, args[2]));

        tcg_out32 (s, SUBF | TAB (args[0], 0, args[1]));

        break;

    case INDEX_op_qemu_ld8u:

        tcg_out_qemu_ld (s, args, 0);

        break;

    case INDEX_op_qemu_ld8s:

        tcg_out_qemu_ld (s, args, 0 | 4);

        break;

    case INDEX_op_qemu_ld16u:

        tcg_out_qemu_ld (s, args, 1);

        break;

    case INDEX_op_qemu_ld16s:

        tcg_out_qemu_ld (s, args, 1 | 4);

        break;

    case INDEX_op_qemu_ld32:

    case INDEX_op_qemu_ld32u:

        tcg_out_qemu_ld (s, args, 2);

        break;

    case INDEX_op_qemu_ld32s:

        tcg_out_qemu_ld (s, args, 2 | 4);

        break;

    case INDEX_op_qemu_ld64:

        tcg_out_qemu_ld (s, args, 3);

        break;

    case INDEX_op_qemu_st8:

        tcg_out_qemu_st (s, args, 0);

        break;

    case INDEX_op_qemu_st16:

        tcg_out_qemu_st (s, args, 1);

        break;

    case INDEX_op_qemu_st32:

        tcg_out_qemu_st (s, args, 2);

        break;

    case INDEX_op_qemu_st64:

        tcg_out_qemu_st (s, args, 3);

        break;

    case INDEX_op_ext8s_i32:

    case INDEX_op_ext8s_i64:

        c = EXTSB;

        goto gen_ext;

    case INDEX_op_ext16s_i32:

    case INDEX_op_ext16s_i64:

        c = EXTSH;

        goto gen_ext;

    case INDEX_op_ext32s_i64:

        c = EXTSW;

        goto gen_ext;

    gen_ext:

        tcg_out32 (s, c | RS (args[1]) | RA (args[0]));

        break;

    case INDEX_op_ext32u_i64:

        tcg_out_rld (s, RLDICR, args[0], args[1], 0, 32);

        break;

    case INDEX_op_setcond_i32:

        tcg_out_setcond (s, TCG_TYPE_I32, args[3], args[0], args[1], args[2],

                         const_args[2]);

        break;

    case INDEX_op_setcond_i64:

        tcg_out_setcond (s, TCG_TYPE_I64, args[3], args[0], args[1], args[2],

                         const_args[2]);

        break;

    default:

        tcg_dump_ops (s, stderr);

        tcg_abort ();

    }

}


static int fdctrl_init_common(FDCtrl *fdctrl)

{

    int i, j;

    static int command_tables_inited = 0;

    /* Fill 'command_to_handler' lookup table */

    if (!command_tables_inited) {

        command_tables_inited = 1;

        for (i = ARRAY_SIZE(handlers) - 1; i >= 0; i--) {

            for (j = 0; j < sizeof(command_to_handler); j++) {

                if ((j & handlers[i].mask) == handlers[i].value) {

                    command_to_handler[j] = i;

                }

            }

        }

    }

    FLOPPY_DPRINTF("init controller\n");

    fdctrl->fifo = qemu_memalign(512, FD_SECTOR_LEN);

    fdctrl->fifo_size = 512;

    fdctrl->result_timer = qemu_new_timer(vm_clock,

                                          fdctrl_result_timer, fdctrl);

    fdctrl->version = 0x90; /* Intel 82078 controller */

    fdctrl->config = FD_CONFIG_EIS | FD_CONFIG_EFIFO; /* Implicit seek, polling & FIFO enabled */

    fdctrl->num_floppies = MAX_FD;

    if (fdctrl->dma_chann != -1)

        DMA_register_channel(fdctrl->dma_chann, &fdctrl_transfer_handler, fdctrl);

    fdctrl_connect_drives(fdctrl);

    return 0;

}


static int32_t scsi_send_command(SCSIRequest *req, uint8_t *cmd)

{

    SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, req->dev);

    SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);

    int ret;

    scsi_req_enqueue(req);

    if (cmd[0] != REQUEST_SENSE &&

        (req->lun != s->lun || (cmd[1] >> 5) != s->lun)) {

        DPRINTF("Unimplemented LUN %d\n", req->lun ? req->lun : cmd[1] >> 5);

        s->sensebuf[0] = 0x70;

        s->sensebuf[1] = 0x00;

        s->sensebuf[2] = ILLEGAL_REQUEST;

        s->sensebuf[3] = 0x00;

        s->sensebuf[4] = 0x00;

        s->sensebuf[5] = 0x00;

        s->sensebuf[6] = 0x00;

        s->senselen = 7;

        s->driver_status = SG_ERR_DRIVER_SENSE;

        r->req.status = CHECK_CONDITION;

        scsi_req_complete(&r->req);

        return 0;

    }

    if (-1 == scsi_req_parse(&r->req, cmd)) {

        BADF("Unsupported command length, command %x\n", cmd[0]);

        scsi_req_dequeue(&r->req);

        scsi_req_unref(&r->req);

        return 0;

    }

    scsi_req_fixup(&r->req);

    DPRINTF("Command: lun=%d tag=0x%x len %zd data=0x%02x", lun, tag,

            r->req.cmd.xfer, cmd[0]);

#ifdef DEBUG_SCSI

    {

        int i;

        for (i = 1; i < r->req.cmd.len; i++) {

            printf(" 0x%02x", cmd[i]);

        }

        printf("\n");

    }

#endif

    if (r->req.cmd.xfer == 0) {

        if (r->buf != NULL)

            qemu_free(r->buf);

        r->buflen = 0;

        r->buf = NULL;

        ret = execute_command(s->bs, r, SG_DXFER_NONE, scsi_command_complete);

        if (ret == -1) {

            scsi_command_complete(r, -EINVAL);

        }

        return 0;

    }

    if (r->buflen != r->req.cmd.xfer) {

        if (r->buf != NULL)

            qemu_free(r->buf);

        r->buf = qemu_malloc(r->req.cmd.xfer);

        r->buflen = r->req.cmd.xfer;

    }

    memset(r->buf, 0, r->buflen);

    r->len = r->req.cmd.xfer;

    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {

        r->len = 0;

        return -r->req.cmd.xfer;

    } else {

        return r->req.cmd.xfer;

    }

}


static void vfio_probe_ati_bar2_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIOConfigMirrorQuirk *mirror;

    /* Only enable on newer devices where BAR2 is 64bit */

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_ATI, PCI_ANY_ID) ||

        !vdev->has_vga || nr != 2 || !vdev->bars[2].mem64) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    mirror = quirk->data = g_malloc0(sizeof(*mirror));

    mirror->mem = quirk->mem = g_malloc0(sizeof(MemoryRegion));

    quirk->nr_mem = 1;

    mirror->vdev = vdev;

    mirror->offset = 0x4000;

    mirror->bar = nr;

    memory_region_init_io(mirror->mem, OBJECT(vdev),

                          &vfio_generic_mirror_quirk, mirror,

                          "vfio-ati-bar2-4000-quirk", PCI_CONFIG_SPACE_SIZE);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        mirror->offset, mirror->mem, 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    trace_vfio_quirk_ati_bar2_probe(vdev->vbasedev.name);

}


static int copy_packet_data(AVPacket *pkt, const AVPacket *src, int dup)

{

    pkt->data      = NULL;

    pkt->side_data = NULL;

    if (pkt->buf) {

        AVBufferRef *ref = av_buffer_ref(src->buf);

        if (!ref)

            return AVERROR(ENOMEM);

        pkt->buf  = ref;

        pkt->data = ref->data;

    } else {

        DUP_DATA(pkt->data, src->data, pkt->size, 1, ALLOC_BUF);

    }

    if (pkt->side_data_elems && dup)

        pkt->side_data = src->side_data;

    if (pkt->side_data_elems && !dup) {

        return av_copy_packet_side_data(pkt, src);

    }

    return 0;

failed_alloc:

    av_packet_unref(pkt);

    return AVERROR(ENOMEM);

}


static void ffm_seek1(AVFormatContext *s, int64_t pos1)

{

    FFMContext *ffm = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t pos;

    pos = FFMIN(pos1, ffm->file_size - FFM_PACKET_SIZE);

    pos = FFMAX(pos, FFM_PACKET_SIZE);

    av_dlog(s, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);

    avio_seek(pb, pos, SEEK_SET);

}


int ff_h264_decode_ref_pic_list_reordering(H264Context *h, H264SliceContext *sl)

{

    int list, index, pic_structure;

    print_short_term(h);

    print_long_term(h);

    h264_initialise_ref_list(h, sl);

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

        if (get_bits1(&sl->gb)) {    // ref_pic_list_modification_flag_l[01]

            int pred = h->curr_pic_num;

            for (index = 0; ; index++) {

                unsigned int modification_of_pic_nums_idc = get_ue_golomb_31(&sl->gb);

                unsigned int pic_id;

                int i;

                H264Picture *ref = NULL;

                if (modification_of_pic_nums_idc == 3)

                    break;

                if (index >= sl->ref_count[list]) {

                    av_log(h->avctx, AV_LOG_ERROR, "reference count overflow\n");

                    return -1;

                }

                switch (modification_of_pic_nums_idc) {

                case 0:

                case 1: {

                    const unsigned int abs_diff_pic_num = get_ue_golomb(&sl->gb) + 1;

                    int frame_num;

                    if (abs_diff_pic_num > h->max_pic_num) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "abs_diff_pic_num overflow\n");

                        return AVERROR_INVALIDDATA;

                    }

                    if (modification_of_pic_nums_idc == 0)

                        pred -= abs_diff_pic_num;

                    else

                        pred += abs_diff_pic_num;

                    pred &= h->max_pic_num - 1;

                    frame_num = pic_num_extract(h, pred, &pic_structure);

                    for (i = h->short_ref_count - 1; i >= 0; i--) {

                        ref = h->short_ref[i];

                        assert(ref->reference);

                        assert(!ref->long_ref);

                        if (ref->frame_num == frame_num &&

                            (ref->reference & pic_structure))

                            break;

                    }

                    if (i >= 0)

                        ref->pic_id = pred;

                    break;

                }

                case 2: {

                    int long_idx;

                    pic_id = get_ue_golomb(&sl->gb); // long_term_pic_idx

                    long_idx = pic_num_extract(h, pic_id, &pic_structure);

                    if (long_idx > 31) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "long_term_pic_idx overflow\n");

                        return AVERROR_INVALIDDATA;

                    }

                    ref = h->long_ref[long_idx];

                    assert(!(ref && !ref->reference));

                    if (ref && (ref->reference & pic_structure) && !mismatches_ref(h, ref)) {

                        ref->pic_id = pic_id;

                        assert(ref->long_ref);

                        i = 0;

                    } else {

                        i = -1;

                    }

                    break;

                }

                default:

                    av_log(h->avctx, AV_LOG_ERROR,

                           "illegal modification_of_pic_nums_idc %u\n",

                           modification_of_pic_nums_idc);

                    return AVERROR_INVALIDDATA;

                }

                if (i < 0) {

                    av_log(h->avctx, AV_LOG_ERROR,

                           "reference picture missing during reorder\n");

                    memset(&sl->ref_list[list][index], 0, sizeof(sl->ref_list[0][0])); // FIXME

                } else {

                    for (i = index; i + 1 < sl->ref_count[list]; i++) {

                        if (sl->ref_list[list][i].parent &&

                            ref->long_ref == sl->ref_list[list][i].parent->long_ref &&

                            ref->pic_id   == sl->ref_list[list][i].pic_id)

                            break;

                    }

                    for (; i > index; i--) {

                        sl->ref_list[list][i] = sl->ref_list[list][i - 1];

                    }

                    ref_from_h264pic(&sl->ref_list[list][index], ref);

                    if (FIELD_PICTURE(h)) {

                        pic_as_field(&sl->ref_list[list][index], pic_structure);

                    }

                }

            }

        }

    }

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

        for (index = 0; index < sl->ref_count[list]; index++) {

            if (   !sl->ref_list[list][index].parent

                || (!FIELD_PICTURE(h) && (sl->ref_list[list][index].reference&3) != 3)) {

                int i;

                av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture\n");

                for (i = 0; i < FF_ARRAY_ELEMS(h->last_pocs); i++)

                    h->last_pocs[i] = INT_MIN;

                return -1;

            }

            av_assert0(av_buffer_get_ref_count(sl->ref_list[list][index].parent->f->buf[0]) > 0);

        }

    }

    return 0;

}


static inline void dxt5_block_internal(uint8_t *dst, ptrdiff_t stride,

                                       const uint8_t *block)

{

    int x, y;

    uint32_t colors[4];

    uint8_t alpha_indices[16];

    uint16_t color0 = AV_RL16(block + 8);

    uint16_t color1 = AV_RL16(block + 10);

    uint32_t code   = AV_RL32(block + 12);

    uint8_t alpha0  = *(block);

    uint8_t alpha1  = *(block + 1);

    decompress_indices(alpha_indices, block + 2);

    extract_color(colors, color0, color1, 1, 0);

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

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

            int alpha_code = alpha_indices[x + y * 4];

            uint32_t pixel;

            uint8_t alpha;

            if (alpha_code == 0) {

                alpha = alpha0;

            } else if (alpha_code == 1) {

                alpha = alpha1;

            } else {

                if (alpha0 > alpha1) {

                    alpha = (uint8_t) (((8 - alpha_code) * alpha0 +

                                        (alpha_code - 1) * alpha1) / 7);

                } else {

                    if (alpha_code == 6) {

                        alpha = 0;

                    } else if (alpha_code == 7) {

                        alpha = 255;

                    } else {

                        alpha = (uint8_t) (((6 - alpha_code) * alpha0 +

                                            (alpha_code - 1) * alpha1) / 5);

                    }

                }

            }

            pixel = colors[code & 3] | (alpha << 24);

            code >>= 2;

            AV_WL32(dst + x * 4, pixel);

        }

        dst += stride;

    }

}


void OPPROTO op_POWER_sre (void)

{

    T1 &= 0x1FUL;

    env->spr[SPR_MQ] = rotl32(T0, 32 - T1);

    T0 = Ts0 >> T1;

    RETURN();

}


static int h263_decode_block(MpegEncContext * s, int16_t * block,

                             int n, int coded)

{

    int level, i, j, run;

    RLTable *rl = &ff_h263_rl_inter;

    const uint8_t *scan_table;

    GetBitContext gb= s->gb;

    scan_table = s->intra_scantable.permutated;

    if (s->h263_aic && s->mb_intra) {

        rl = &ff_rl_intra_aic;

        i = 0;

        if (s->ac_pred) {

            if (s->h263_aic_dir)

                scan_table = s->intra_v_scantable.permutated; /* left */

            else

                scan_table = s->intra_h_scantable.permutated; /* top */

        }

    } else if (s->mb_intra) {

        /* DC coef */

        if (CONFIG_RV10_DECODER && s->codec_id == AV_CODEC_ID_RV10) {

          if (s->rv10_version == 3 && s->pict_type == AV_PICTURE_TYPE_I) {

            int component, diff;

            component = (n <= 3 ? 0 : n - 4 + 1);

            level = s->last_dc[component];

            if (s->rv10_first_dc_coded[component]) {

                diff = ff_rv_decode_dc(s, n);

                if (diff == 0xffff)

                    return -1;

                level += diff;

                level = level & 0xff; /* handle wrap round */

                s->last_dc[component] = level;

            } else {

                s->rv10_first_dc_coded[component] = 1;

            }

          } else {

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

                if (level == 255)

                    level = 128;

          }

        }else{

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

            if((level&0x7F) == 0){

                av_log(s->avctx, AV_LOG_ERROR, "illegal dc %d at %d %d\n", level, s->mb_x, s->mb_y);

                if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT))

                    return -1;

            }

            if (level == 255)

                level = 128;

        }

        block[0] = level;

        i = 1;

    } else {

        i = 0;

    }

    if (!coded) {

        if (s->mb_intra && s->h263_aic)

            goto not_coded;

        s->block_last_index[n] = i - 1;

        return 0;

    }

retry:

    {

    OPEN_READER(re, &s->gb);

    i--; // offset by -1 to allow direct indexing of scan_table

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);

        if (run == 66) {

            if (level){

                CLOSE_READER(re, &s->gb);

                av_log(s->avctx, AV_LOG_ERROR, "illegal ac vlc code at %dx%d\n", s->mb_x, s->mb_y);

                return -1;

            }

            /* escape */

            if (CONFIG_FLV_DECODER && s->h263_flv > 1) {

                int is11 = SHOW_UBITS(re, &s->gb, 1);

                SKIP_CACHE(re, &s->gb, 1);

                run = SHOW_UBITS(re, &s->gb, 7) + 1;

                if (is11) {

                    SKIP_COUNTER(re, &s->gb, 1 + 7);

                    UPDATE_CACHE(re, &s->gb);

                    level = SHOW_SBITS(re, &s->gb, 11);

                    SKIP_COUNTER(re, &s->gb, 11);

                } else {

                    SKIP_CACHE(re, &s->gb, 7);

                    level = SHOW_SBITS(re, &s->gb, 7);

                    SKIP_COUNTER(re, &s->gb, 1 + 7 + 7);

                }

            } else {

                run = SHOW_UBITS(re, &s->gb, 7) + 1;

                SKIP_CACHE(re, &s->gb, 7);

                level = (int8_t)SHOW_UBITS(re, &s->gb, 8);

                SKIP_COUNTER(re, &s->gb, 7 + 8);

                if(level == -128){

                    UPDATE_CACHE(re, &s->gb);

                    if (s->codec_id == AV_CODEC_ID_RV10) {

                        /* XXX: should patch encoder too */

                        level = SHOW_SBITS(re, &s->gb, 12);

                        SKIP_COUNTER(re, &s->gb, 12);

                    }else{

                        level = SHOW_UBITS(re, &s->gb, 5);

                        SKIP_CACHE(re, &s->gb, 5);

                        level |= SHOW_SBITS(re, &s->gb, 6)<<5;

                        SKIP_COUNTER(re, &s->gb, 5 + 6);

                    }

                }

            }

        } else {

            if (SHOW_UBITS(re, &s->gb, 1))

                level = -level;

            SKIP_COUNTER(re, &s->gb, 1);

        }

        i += run;

        if (i >= 64){

            CLOSE_READER(re, &s->gb);

            // redo update without last flag, revert -1 offset

            i = i - run + ((run-1)&63) + 1;

            if (i < 64) {

                // only last marker, no overrun

                block[scan_table[i]] = level;

                break;

            }

            if(s->alt_inter_vlc && rl == &ff_h263_rl_inter && !s->mb_intra){

                //Looks like a hack but no, it's the way it is supposed to work ...

                rl = &ff_rl_intra_aic;

                i = 0;

                s->gb= gb;

                s->bdsp.clear_block(block);

                goto retry;

            }

            av_log(s->avctx, AV_LOG_ERROR, "run overflow at %dx%d i:%d\n", s->mb_x, s->mb_y, s->mb_intra);

            return -1;

        }

        j = scan_table[i];

        block[j] = level;

    }

    }

not_coded:

    if (s->mb_intra && s->h263_aic) {

        ff_h263_pred_acdc(s, block, n);

        i = 63;

    }

    s->block_last_index[n] = i;

    return 0;

}


void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)

{

    BdrvOpBlocker *blocker;

    assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);

    blocker = g_malloc0(sizeof(BdrvOpBlocker));

    blocker->reason = reason;

    QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);

}


TraceEvent *trace_event_iter_next(TraceEventIter *iter)

{

    while (iter->event < TRACE_EVENT_COUNT) {

        TraceEvent *ev = &(trace_events[iter->event]);

        iter->event++;

        if (!iter->pattern ||

            pattern_glob(iter->pattern,

                         trace_event_get_name(ev))) {

            return ev;

        }

    }

    return NULL;

}


static av_cold int ape_decode_init(AVCodecContext *avctx)

{

    APEContext *s = avctx->priv_data;

    int i;

    if (avctx->extradata_size != 6) {

        av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");

        return AVERROR(EINVAL);

    }

    if (avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");

        return AVERROR(EINVAL);

    }

    s->bps = avctx->bits_per_coded_sample;

    switch (s->bps) {

    case 8:

        avctx->sample_fmt = AV_SAMPLE_FMT_U8;

        break;

    case 16:

        avctx->sample_fmt = AV_SAMPLE_FMT_S16;

        break;

    case 24:

        avctx->sample_fmt = AV_SAMPLE_FMT_S32;

        break;

    default:

        av_log_ask_for_sample(avctx, "Unsupported bits per coded sample %d\n",

                              s->bps);

        return AVERROR_PATCHWELCOME;

    }

    s->avctx             = avctx;

    s->channels          = avctx->channels;

    s->fileversion       = AV_RL16(avctx->extradata);

    s->compression_level = AV_RL16(avctx->extradata + 2);

    s->flags             = AV_RL16(avctx->extradata + 4);

    av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",

           s->compression_level, s->flags);

    if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {

        av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",

               s->compression_level);

        return AVERROR_INVALIDDATA;

    }

    s->fset = s->compression_level / 1000 - 1;

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

        if (!ape_filter_orders[s->fset][i])

            break;

        FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],

                         (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,

                         filter_alloc_fail);

    }

    ff_dsputil_init(&s->dsp, avctx);

    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;

    avcodec_get_frame_defaults(&s->frame);

    avctx->coded_frame = &s->frame;

    return 0;

filter_alloc_fail:

    ape_decode_close(avctx);

    return AVERROR(ENOMEM);

}


static double lfo_get_value(SimpleLFO *lfo)

{

    double phs = FFMIN(100, lfo->phase / FFMIN(1.99, FFMAX(0.01, lfo->pwidth)) + lfo->offset);

    double val;

    if (phs > 1)

        phs = fmod(phs, 1.);

    switch (lfo->mode) {

    case SINE:

        val = sin(phs * 2 * M_PI);

        break;

    case TRIANGLE:

        if (phs > 0.75)

            val = (phs - 0.75) * 4 - 1;

        else if (phs > 0.25)

            val = -4 * phs + 2;

        else

            val = phs * 4;

        break;

    case SQUARE:

        val = phs < 0.5 ? -1 : +1;

        break;

    case SAWUP:

        val = phs * 2 - 1;

        break;

    case SAWDOWN:

        val = 1 - phs * 2;

        break;

    }

    return val * lfo->amount;

}


static int srt_get_duration(uint8_t **buf)

{

    int i, duration = 0;

    for (i=0; i<2 && !duration; i++) {

        int s_hour, s_min, s_sec, s_hsec, e_hour, e_min, e_sec, e_hsec;

        if (sscanf(*buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",

                   &s_hour, &s_min, &s_sec, &s_hsec,

                   &e_hour, &e_min, &e_sec, &e_hsec) == 8) {

            s_min  +=   60*s_hour;      e_min  +=   60*e_hour;

            s_sec  +=   60*s_min;       e_sec  +=   60*e_min;

            s_hsec += 1000*s_sec;       e_hsec += 1000*e_sec;

            duration = e_hsec - s_hsec;

        }

        *buf += strcspn(*buf, "\n") + 1;

    }

    return duration;

}


static int vaapi_encode_mjpeg_init_picture_params(AVCodecContext *avctx,

                                                  VAAPIEncodePicture *pic)

{

    VAAPIEncodeContext               *ctx = avctx->priv_data;

    VAEncPictureParameterBufferJPEG *vpic = pic->codec_picture_params;

    VAAPIEncodeMJPEGContext         *priv = ctx->priv_data;

    vpic->reconstructed_picture = pic->recon_surface;

    vpic->coded_buf = pic->output_buffer;

    vpic->picture_width  = ctx->input_width;

    vpic->picture_height = ctx->input_height;

    vpic->pic_flags.bits.profile      = 0;

    vpic->pic_flags.bits.progressive  = 0;

    vpic->pic_flags.bits.huffman      = 1;

    vpic->pic_flags.bits.interleaved  = 0;

    vpic->pic_flags.bits.differential = 0;

    vpic->sample_bit_depth = 8;

    vpic->num_scan = 1;

    vpic->num_components = 3;

    vpic->component_id[0] = 1;

    vpic->component_id[1] = 2;

    vpic->component_id[2] = 3;

    priv->component_subsample_h[0] = 2;

    priv->component_subsample_v[0] = 2;

    priv->component_subsample_h[1] = 1;

    priv->component_subsample_v[1] = 1;

    priv->component_subsample_h[2] = 1;

    priv->component_subsample_v[2] = 1;

    vpic->quantiser_table_selector[0] = 0;

    vpic->quantiser_table_selector[1] = 1;

    vpic->quantiser_table_selector[2] = 1;

    vpic->quality = priv->quality;

    pic->nb_slices = 1;

    return 0;

}


static int hdcd_scan(HDCDContext *ctx, hdcd_state_t *state, const int32_t *samples, int max, int stride)

{

    int cdt_active = 0;

    /* code detect timer */

    int result;

    if (state->sustain > 0) {

        cdt_active = 1;

        if (state->sustain <= max) {

            state->control = 0;

            max = state->sustain;

        }

        state->sustain -= max;

    }

    result = 0;

    while (result < max) {

        int flag;

        int consumed = hdcd_integrate(ctx, state, &flag, samples, max - result, stride);

        result += consumed;

        if (flag > 0) {

            /* reset timer if code detected in channel */

            hdcd_sustain_reset(state);

            break;

        }

        samples += consumed * stride;

    }

    /* code detect timer expired */

    if (cdt_active && state->sustain == 0)

        state->count_sustain_expired++;

    return result;

}


static int swf_write_audio(AVFormatContext *s,

                           AVCodecContext *enc, const uint8_t *buf, int size)

{

    SWFContext *swf = s->priv_data;

    int c = 0;

    /* Flash Player limit */

    if ( swf->swf_frame_number >= 16000 ) {

        return 0;

    }

    if (enc->codec_id == CODEC_ID_MP3 ) {

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

            swf->audio_fifo[(swf->audio_out_pos+c)%AUDIO_FIFO_SIZE] = buf[c];

        }

        swf->audio_size += size;

        swf->audio_out_pos += size;

        swf->audio_out_pos %= AUDIO_FIFO_SIZE;

    }

    /* if audio only stream make sure we add swf frames */

    if ( swf->video_type == 0 ) {

        swf_write_video(s, enc, 0, 0);

    }

    return 0;

}


static int64_t mp3_sync(AVFormatContext *s, int64_t target_pos, int flags)

{

    int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;

    int64_t best_pos;

    int best_score, i, j;

    int64_t ret;

    avio_seek(s->pb, FFMAX(target_pos - SEEK_WINDOW, 0), SEEK_SET);

    ret = avio_seek(s->pb, target_pos, SEEK_SET);

    if (ret < 0)

        return ret;

#define MIN_VALID 3

    best_pos = target_pos;

    best_score = 999;

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

        int64_t pos = target_pos + (dir > 0 ? i - SEEK_WINDOW/4 : -i);

        int64_t candidate = -1;

        int score = 999;

        if (pos < 0)

            continue;

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

            ret = check(s->pb, pos);

            if(ret < 0)

                break;

            if ((target_pos - pos)*dir <= 0 && abs(MIN_VALID/2-j) < score) {

                candidate = pos;

                score = abs(MIN_VALID/2-j);

            }

            pos += ret;

        }

        if (best_score > score && j == MIN_VALID) {

            best_pos = candidate;

            best_score = score;

            if(score == 0)

                break;

        }

    }

    return avio_seek(s->pb, best_pos, SEEK_SET);

}


void test_segs(void)

{

    struct modify_ldt_ldt_s ldt;

    long long ldt_table[3];

    int res, res2;

    char tmp;

    struct {

        uint32_t offset;

        uint16_t seg;

    } __attribute__((packed)) segoff;

    ldt.entry_number = 1;

    ldt.base_addr = (unsigned long)&seg_data1;

    ldt.limit = (sizeof(seg_data1) + 0xfff) >> 12;

    ldt.seg_32bit = 1;

    ldt.contents = MODIFY_LDT_CONTENTS_DATA;

    ldt.read_exec_only = 0;

    ldt.limit_in_pages = 1;

    ldt.seg_not_present = 0;

    ldt.useable = 1;

    modify_ldt(1, &ldt, sizeof(ldt)); /* write ldt entry */

    ldt.entry_number = 2;

    ldt.base_addr = (unsigned long)&seg_data2;

    ldt.limit = (sizeof(seg_data2) + 0xfff) >> 12;

    ldt.seg_32bit = 1;

    ldt.contents = MODIFY_LDT_CONTENTS_DATA;

    ldt.read_exec_only = 0;

    ldt.limit_in_pages = 1;

    ldt.seg_not_present = 0;

    ldt.useable = 1;

    modify_ldt(1, &ldt, sizeof(ldt)); /* write ldt entry */

    modify_ldt(0, &ldt_table, sizeof(ldt_table)); /* read ldt entries */

#if 0

    {

        int i;

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

            printf("%d: %016Lx\n", i, ldt_table[i]);

    }

#endif

    /* do some tests with fs or gs */

    asm volatile ("movl %0, %%fs" : : "r" (MK_SEL(1)));

    seg_data1[1] = 0xaa;

    seg_data2[1] = 0x55;

    asm volatile ("fs movzbl 0x1, %0" : "=r" (res));

    printf("FS[1] = %02x\n", res);

    asm volatile ("pushl %%gs\n"

                  "movl %1, %%gs\n"

                  "gs movzbl 0x1, %0\n"

                  "popl %%gs\n"

                  : "=r" (res)

                  : "r" (MK_SEL(2)));

    printf("GS[1] = %02x\n", res);

    /* tests with ds/ss (implicit segment case) */

    tmp = 0xa5;

    asm volatile ("pushl %%ebp\n\t"

                  "pushl %%ds\n\t"

                  "movl %2, %%ds\n\t"

                  "movl %3, %%ebp\n\t"

                  "movzbl 0x1, %0\n\t"

                  "movzbl (%%ebp), %1\n\t"

                  "popl %%ds\n\t"

                  "popl %%ebp\n\t"

                  : "=r" (res), "=r" (res2)

                  : "r" (MK_SEL(1)), "r" (&tmp));

    printf("DS[1] = %02x\n", res);

    printf("SS[tmp] = %02x\n", res2);

    segoff.seg = MK_SEL(2);

    segoff.offset = 0xabcdef12;

    asm volatile("lfs %2, %0\n\t"

                 "movl %%fs, %1\n\t"

                 : "=r" (res), "=g" (res2)

                 : "m" (segoff));

    printf("FS:reg = %04x:%08x\n", res2, res);

    TEST_LR("larw", "w", MK_SEL(2), 0x0100);

    TEST_LR("larl", "", MK_SEL(2), 0x0100);

    TEST_LR("lslw", "w", MK_SEL(2), 0);

    TEST_LR("lsll", "", MK_SEL(2), 0);

    TEST_LR("larw", "w", 0xfff8, 0);

    TEST_LR("larl", "", 0xfff8, 0);

    TEST_LR("lslw", "w", 0xfff8, 0);

    TEST_LR("lsll", "", 0xfff8, 0);

    TEST_ARPL("arpl", "w", 0x12345678 | 3, 0x762123c | 1);

    TEST_ARPL("arpl", "w", 0x12345678 | 1, 0x762123c | 3);

    TEST_ARPL("arpl", "w", 0x12345678 | 1, 0x762123c | 1);

}


static void cpu_notify_map_clients(void)

{

    MapClient *client;

    while (!LIST_EMPTY(&map_client_list)) {

        client = LIST_FIRST(&map_client_list);

        client->callback(client->opaque);

        cpu_unregister_map_client(client);

    }

}


vcard_free(VCard *vcard)

{

    VCardApplet *current_applet = NULL;

    VCardApplet *next_applet = NULL;

    if (vcard == NULL) {

        return;

    }

    vcard->reference_count--;

    if (vcard->reference_count != 0) {

        return;

    }

    if (vcard->vcard_private_free) {

        (*vcard->vcard_private_free)(vcard->vcard_private);

        vcard->vcard_private_free = 0;

        vcard->vcard_private = 0;

    }

    for (current_applet = vcard->applet_list; current_applet;

                                        current_applet = next_applet) {

        next_applet = current_applet->next;

        vcard_delete_applet(current_applet);

    }

    vcard_buffer_response_delete(vcard->vcard_buffer_response);

    g_free(vcard);

}


static inline bool valid_ptex(PowerPCCPU *cpu, target_ulong ptex)

{

    /*

     * hash value/pteg group index is normalized by htab_mask

     */

    if (((ptex & ~7ULL) / HPTES_PER_GROUP) & ~cpu->env.htab_mask) {

        return false;

    }

    return true;

}


gen_intermediate_code_internal(SuperHCPU *cpu, TranslationBlock *tb,

                               bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUSH4State *env = &cpu->env;

    DisasContext ctx;

    target_ulong pc_start;

    static uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int i, ii;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    ctx.pc = pc_start;

    ctx.flags = (uint32_t)tb->flags;

    ctx.bstate = BS_NONE;

    ctx.memidx = (ctx.flags & SR_MD) == 0 ? 1 : 0;

    /* We don't know if the delayed pc came from a dynamic or static branch,

       so assume it is a dynamic branch.  */

    ctx.delayed_pc = -1; /* use delayed pc from env pointer */

    ctx.tb = tb;

    ctx.singlestep_enabled = cs->singlestep_enabled;

    ctx.features = env->features;

    ctx.has_movcal = (ctx.flags & TB_FLAG_PENDING_MOVCA);

    ii = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_tb_start();

    while (ctx.bstate == BS_NONE && tcg_ctx.gen_opc_ptr < gen_opc_end) {

        if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) {

            QTAILQ_FOREACH(bp, &cs->breakpoints, entry) {

                if (ctx.pc == bp->pc) {

		    /* We have hit a breakpoint - make sure PC is up-to-date */

		    tcg_gen_movi_i32(cpu_pc, ctx.pc);

                    gen_helper_debug(cpu_env);

                    ctx.bstate = BS_BRANCH;

		    break;

		}

	    }

	}

        if (search_pc) {

            i = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (ii < i) {

                ii++;

                while (ii < i)

                    tcg_ctx.gen_opc_instr_start[ii++] = 0;

            }

            tcg_ctx.gen_opc_pc[ii] = ctx.pc;

            gen_opc_hflags[ii] = ctx.flags;

            tcg_ctx.gen_opc_instr_start[ii] = 1;

            tcg_ctx.gen_opc_icount[ii] = num_insns;

        }

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

            gen_io_start();

#if 0

	fprintf(stderr, "Loading opcode at address 0x%08x\n", ctx.pc);

	fflush(stderr);

#endif

        ctx.opcode = cpu_lduw_code(env, ctx.pc);

	decode_opc(&ctx);

        num_insns++;

	ctx.pc += 2;

	if ((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0)

	    break;

        if (cs->singlestep_enabled) {

	    break;

        }

        if (num_insns >= max_insns)

            break;

        if (singlestep)

            break;

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    if (cs->singlestep_enabled) {

        tcg_gen_movi_i32(cpu_pc, ctx.pc);

        gen_helper_debug(cpu_env);

    } else {

	switch (ctx.bstate) {

        case BS_STOP:

            /* gen_op_interrupt_restart(); */

            /* fall through */

        case BS_NONE:

            if (ctx.flags) {

                gen_store_flags(ctx.flags | DELAY_SLOT_CLEARME);

	    }

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_EXCP:

            /* gen_op_interrupt_restart(); */

            tcg_gen_exit_tb(0);

            break;

        case BS_BRANCH:

        default:

            break;

	}

    }

    gen_tb_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        i = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        ii++;

        while (ii <= i)

            tcg_ctx.gen_opc_instr_start[ii++] = 0;

    } else {

        tb->size = ctx.pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

	qemu_log("IN:\n");	/* , lookup_symbol(pc_start)); */

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

	qemu_log("\n");

    }

#endif

}


static uint32_t get_level1_table_address(CPUARMState *env, uint32_t address)

{

    uint32_t table;

    if (address & env->cp15.c2_mask)

        table = env->cp15.ttbr1_el1 & 0xffffc000;

    else

        table = env->cp15.ttbr0_el1 & env->cp15.c2_base_mask;

    table |= (address >> 18) & 0x3ffc;

    return table;

}


static int do_setcontext(struct target_ucontext *ucp, CPUPPCState *env, int sig)

{

    struct target_mcontext *mcp;

    target_ulong mcp_addr;

    sigset_t blocked;

    target_sigset_t set;

    if (copy_from_user(&set, h2g(ucp) + offsetof(struct target_ucontext, tuc_sigmask),

                       sizeof (set)))

        return 1;

#if defined(TARGET_PPC64)

    fprintf (stderr, "do_setcontext: not implemented\n");

    return 0;

#else

    if (__get_user(mcp_addr, &ucp->tuc_regs))

        return 1;

    if (!lock_user_struct(VERIFY_READ, mcp, mcp_addr, 1))

        return 1;

    target_to_host_sigset_internal(&blocked, &set);

    do_sigprocmask(SIG_SETMASK, &blocked, NULL);

    if (restore_user_regs(env, mcp, sig))

        goto sigsegv;

    unlock_user_struct(mcp, mcp_addr, 1);

    return 0;

sigsegv:

    unlock_user_struct(mcp, mcp_addr, 1);

    return 1;

#endif

}


static void bdrv_co_drain_bh_cb(void *opaque)

{

    BdrvCoDrainData *data = opaque;

    Coroutine *co = data->co;

    BlockDriverState *bs = data->bs;

    bdrv_dec_in_flight(bs);

    bdrv_drain_poll(bs);

    data->done = true;

    qemu_coroutine_enter(co);

}


QEMUTimerList *timerlist_new(QEMUClockType type,

                             QEMUTimerListNotifyCB *cb,

                             void *opaque)

{

    QEMUTimerList *timer_list;

    QEMUClock *clock = qemu_clock_ptr(type);

    timer_list = g_malloc0(sizeof(QEMUTimerList));

    qemu_event_init(&timer_list->timers_done_ev, true);

    timer_list->clock = clock;

    timer_list->notify_cb = cb;

    timer_list->notify_opaque = opaque;

    qemu_mutex_init(&timer_list->active_timers_lock);

    QLIST_INSERT_HEAD(&clock->timerlists, timer_list, list);

    return timer_list;

}


void cpu_check_irqs(CPUSPARCState *env)

{

    uint32_t pil = env->pil_in |

                  (env->softint & ~(SOFTINT_TIMER | SOFTINT_STIMER));

    /* check if TM or SM in SOFTINT are set

       setting these also causes interrupt 14 */

    if (env->softint & (SOFTINT_TIMER | SOFTINT_STIMER)) {

        pil |= 1 << 14;

    }

    /* The bit corresponding to psrpil is (1<< psrpil), the next bit

       is (2 << psrpil). */

    if (pil < (2 << env->psrpil)){

        if (env->interrupt_request & CPU_INTERRUPT_HARD) {

            CPUIRQ_DPRINTF("Reset CPU IRQ (current interrupt %x)\n",

                           env->interrupt_index);

            env->interrupt_index = 0;

            cpu_reset_interrupt(env, CPU_INTERRUPT_HARD);

        }

        return;

    }

    if (cpu_interrupts_enabled(env)) {

        unsigned int i;

        for (i = 15; i > env->psrpil; i--) {

            if (pil & (1 << i)) {

                int old_interrupt = env->interrupt_index;

                int new_interrupt = TT_EXTINT | i;

                if (env->tl > 0 && cpu_tsptr(env)->tt > new_interrupt) {

                    CPUIRQ_DPRINTF("Not setting CPU IRQ: TL=%d "

                                   "current %x >= pending %x\n",

                                   env->tl, cpu_tsptr(env)->tt, new_interrupt);

                } else if (old_interrupt != new_interrupt) {

                    env->interrupt_index = new_interrupt;

                    CPUIRQ_DPRINTF("Set CPU IRQ %d old=%x new=%x\n", i,

                                   old_interrupt, new_interrupt);

                    cpu_interrupt(env, CPU_INTERRUPT_HARD);

                }

                break;

            }

        }

    } else if (env->interrupt_request & CPU_INTERRUPT_HARD) {

        CPUIRQ_DPRINTF("Interrupts disabled, pil=%08x pil_in=%08x softint=%08x "

                       "current interrupt %x\n",

                       pil, env->pil_in, env->softint, env->interrupt_index);

        env->interrupt_index = 0;

        cpu_reset_interrupt(env, CPU_INTERRUPT_HARD);

    }

}


static void *qemu_kvm_cpu_thread_fn(void *arg)

{

    CPUState *env = arg;

    int r;

    qemu_mutex_lock(&qemu_global_mutex);

    qemu_thread_self(env->thread);

    r = kvm_init_vcpu(env);

    if (r < 0) {

        fprintf(stderr, "kvm_init_vcpu failed: %s\n", strerror(-r));

        exit(1);

    }

    qemu_kvm_init_cpu_signals(env);

    /* signal CPU creation */

    env->created = 1;

    qemu_cond_signal(&qemu_cpu_cond);

    /* and wait for machine initialization */

    while (!qemu_system_ready)

        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);

    while (1) {

        if (cpu_can_run(env))

            qemu_cpu_exec(env);

        qemu_kvm_wait_io_event(env);

    }

    return NULL;

}


static long do_sigreturn_v2(CPUARMState *env)

{

    abi_ulong frame_addr;

    struct sigframe_v2 *frame = NULL;

    /*

     * Since we stacked the signal on a 64-bit boundary,

     * then 'sp' should be word aligned here.  If it's

     * not, then the user is trying to mess with us.

     */

    frame_addr = env->regs[13];

    trace_user_do_sigreturn(env, frame_addr);

    if (frame_addr & 7) {

        goto badframe;

    }

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    if (do_sigframe_return_v2(env, frame_addr, &frame->uc)) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->regs[0];

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV /* , current */);

    return 0;

}


static int v9fs_synth_open(FsContext *ctx, V9fsPath *fs_path,

                           int flags, V9fsFidOpenState *fs)

{

    V9fsSynthOpenState *synth_open;

    V9fsSynthNode *node = *(V9fsSynthNode **)fs_path->data;

    synth_open = g_malloc(sizeof(*synth_open));

    synth_open->node = node;

    node->open_count++;

    fs->private = synth_open;

    return 0;

}


static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int bS[4], int qp ) {

    int i, d;

    const int index_a = clip( qp + h->slice_alpha_c0_offset, 0, 51 );

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[clip( qp + h->slice_beta_offset, 0, 51 )];

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

        if( bS[i] == 0 ) {

            pix += 2 * stride;

            continue;

        }

        /* 2px edge length (because we use same bS than the one for luma) */

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

        {

            const uint8_t p0 = pix[-1];

            const uint8_t p1 = pix[-2];

            const uint8_t q0 = pix[0];

            const uint8_t q1 = pix[1];

            if( abs( p0 - q0 ) >= alpha ||

                abs( p1 - p0 ) >= beta ||

                abs( q1 - q0 ) >= beta ) {

                pix += stride;

                continue;

            }

            if( bS[i] < 4 ) {

                const int tc = tc0_table[index_a][bS[i] - 1] + 1;

                const int i_delta = clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );

                pix[-1] = clip( p0 + i_delta, 0, 255 );    /* p0' */

                pix[0]  = clip( q0 - i_delta, 0, 255 );    /* q0' */

            } else {

                pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;   /* p0' */

                pix[0]  = ( 2*q1 + q0 + p1 + 2 ) >> 2;   /* q0' */

            }

            pix += stride;

        }

    }

}


static void rtl8139_transfer_frame(RTL8139State *s, const uint8_t *buf, int size, int do_interrupt)

{

    if (!size)

    {

        DEBUG_PRINT(("RTL8139: +++ empty ethernet frame\n"));

        return;

    }

    if (TxLoopBack == (s->TxConfig & TxLoopBack))

    {

        DEBUG_PRINT(("RTL8139: +++ transmit loopback mode\n"));

        rtl8139_do_receive(s, buf, size, do_interrupt);

    }

    else

    {

        qemu_send_packet(s->vc, buf, size);

    }

}


static void sclp_execute(SCCB *sccb, uint64_t code)

{

    S390SCLPDevice *sdev = get_event_facility();

    switch (code & SCLP_CMD_CODE_MASK) {

    case SCLP_CMDW_READ_SCP_INFO:

    case SCLP_CMDW_READ_SCP_INFO_FORCED:

        read_SCP_info(sccb);

        break;

    case SCLP_CMDW_READ_CPU_INFO:

        sclp_read_cpu_info(sccb);

        break;

    default:

        sdev->sclp_command_handler(sdev->ef, sccb, code);

        break;

    }

}


static int blk_prw(BlockBackend *blk, int64_t offset, uint8_t *buf,

                   int64_t bytes, CoroutineEntry co_entry,

                   BdrvRequestFlags flags)

{

    AioContext *aio_context;

    QEMUIOVector qiov;

    struct iovec iov;

    Coroutine *co;

    BlkRwCo rwco;

    iov = (struct iovec) {

        .iov_base = buf,

        .iov_len = bytes,

    };

    qemu_iovec_init_external(&qiov, &iov, 1);

    rwco = (BlkRwCo) {

        .blk    = blk,

        .offset = offset,

        .qiov   = &qiov,

        .flags  = flags,

        .ret    = NOT_DONE,

    };

    co = qemu_coroutine_create(co_entry, &rwco);

    qemu_coroutine_enter(co);

    aio_context = blk_get_aio_context(blk);

    while (rwco.ret == NOT_DONE) {

        aio_poll(aio_context, true);

    }

    return rwco.ret;

}


static int unix_listen_saddr(UnixSocketAddress *saddr,

                             bool update_addr,

                             Error **errp)

{

    struct sockaddr_un un;

    int sock, fd;

    sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

        error_setg_errno(errp, errno, "Failed to create Unix socket");

        return -1;

    }

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

    un.sun_family = AF_UNIX;

    if (saddr->path && strlen(saddr->path)) {

        snprintf(un.sun_path, sizeof(un.sun_path), "%s", saddr->path);

    } else {

        const char *tmpdir = getenv("TMPDIR");

        tmpdir = tmpdir ? tmpdir : "/tmp";

        if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",

                     tmpdir) >= sizeof(un.sun_path)) {

            error_setg_errno(errp, errno,

                             "TMPDIR environment variable (%s) too large", tmpdir);

            goto err;

        }

        /*

         * This dummy fd usage silences the mktemp() unsecure warning.

         * Using mkstemp() doesn't make things more secure here

         * though.  bind() complains about existing files, so we have

         * to unlink first and thus re-open the race window.  The

         * worst case possible is bind() failing, i.e. a DoS attack.

         */

        fd = mkstemp(un.sun_path);

        if (fd < 0) {

            error_setg_errno(errp, errno,

                             "Failed to make a temporary socket name in %s", tmpdir);

            goto err;

        }

        close(fd);

        if (update_addr) {

            g_free(saddr->path);

            saddr->path = g_strdup(un.sun_path);

        }

    }

    if (unlink(un.sun_path) < 0 && errno != ENOENT) {

        error_setg_errno(errp, errno,

                         "Failed to unlink socket %s", un.sun_path);

        goto err;

    }

    if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {

        error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);

        goto err;

    }

    if (listen(sock, 1) < 0) {

        error_setg_errno(errp, errno, "Failed to listen on socket");

        goto err;

    }

    return sock;

err:

    closesocket(sock);

    return -1;

}


static void mirror_start_job(const char *job_id, BlockDriverState *bs,

                             BlockDriverState *target, const char *replaces,

                             int64_t speed, uint32_t granularity,

                             int64_t buf_size,

                             BlockMirrorBackingMode backing_mode,

                             BlockdevOnError on_source_error,

                             BlockdevOnError on_target_error,

                             bool unmap,

                             BlockCompletionFunc *cb,

                             void *opaque, Error **errp,

                             const BlockJobDriver *driver,

                             bool is_none_mode, BlockDriverState *base)

{

    MirrorBlockJob *s;

    if (granularity == 0) {

        granularity = bdrv_get_default_bitmap_granularity(target);

    }

    assert ((granularity & (granularity - 1)) == 0);

    if (buf_size < 0) {

        error_setg(errp, "Invalid parameter 'buf-size'");

        return;

    }

    if (buf_size == 0) {

        buf_size = DEFAULT_MIRROR_BUF_SIZE;

    }

    s = block_job_create(job_id, driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->target = blk_new();

    blk_insert_bs(s->target, target);

    s->replaces = g_strdup(replaces);

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->is_none_mode = is_none_mode;

    s->backing_mode = backing_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = ROUND_UP(buf_size, granularity);

    s->unmap = unmap;

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);

    if (!s->dirty_bitmap) {

        g_free(s->replaces);

        blk_unref(s->target);

        block_job_unref(&s->common);

        return;

    }

    bdrv_op_block_all(target, s->common.blocker);

    s->common.co = qemu_coroutine_create(mirror_run, s);

    trace_mirror_start(bs, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co);

}


int RENAME(swri_resample)(ResampleContext *c, DELEM *dst, const DELEM *src, int *consumed, int src_size, int dst_size, int update_ctx){

    int dst_index, i;

    int index= c->index;

    int frac= c->frac;

    int dst_incr_frac= c->dst_incr % c->src_incr;

    int dst_incr=      c->dst_incr / c->src_incr;

    av_assert1(c->filter_shift == FILTER_SHIFT);

    av_assert1(c->felem_size == sizeof(FELEM));

    if (c->filter_length == 1 && c->phase_shift == 0) {

        int64_t index2= (1LL<<32)*c->frac/c->src_incr + (1LL<<32)*index;

        int64_t incr= (1LL<<32) * c->dst_incr / c->src_incr;

        int new_size = (src_size * (int64_t)c->src_incr - frac + c->dst_incr - 1) / c->dst_incr;

        dst_size= FFMIN(dst_size, new_size);

        for(dst_index=0; dst_index < dst_size; dst_index++){

            dst[dst_index] = src[index2>>32];

            index2 += incr;

        }

        index += dst_index * dst_incr;

        index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;

        frac   = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;

        av_assert2(index >= 0);

        *consumed= index;

        index = 0;

    } else if (index >= 0) {

        int64_t end_index = (1LL + src_size - c->filter_length) << c->phase_shift;

        int64_t delta_frac = (end_index - index) * c->src_incr - c->frac;

        int delta_n = (delta_frac + c->dst_incr - 1) / c->dst_incr;

        int n = FFMIN(dst_size, delta_n);

        int sample_index;

        if (!c->linear) {

            sample_index = index >> c->phase_shift;

            index &= c->phase_mask;

            for (dst_index = 0; dst_index < n; dst_index++) {

                FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index;

#ifdef COMMON_CORE

                COMMON_CORE

#else

                FELEM2 val=0;

                for (i = 0; i < c->filter_length; i++) {

                    val += src[sample_index + i] * (FELEM2)filter[i];

                }

                OUT(dst[dst_index], val);

#endif

                frac += dst_incr_frac;

                index += dst_incr;

                if (frac >= c->src_incr) {

                    frac -= c->src_incr;

                    index++;

                }

                sample_index += index >> c->phase_shift;

                index &= c->phase_mask;

            }

        } else {

            sample_index = index >> c->phase_shift;

            index &= c->phase_mask;

            for (dst_index = 0; dst_index < n; dst_index++) {

                FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index;

                FELEM2 val=0, v2 = 0;

#ifdef LINEAR_CORE

                LINEAR_CORE

#else

                for (i = 0; i < c->filter_length; i++) {

                    val += src[sample_index + i] * (FELEM2)filter[i];

                    v2  += src[sample_index + i] * (FELEM2)filter[i + c->filter_alloc];

                }

#endif

                val += (v2 - val) * (FELEML) frac / c->src_incr;

                OUT(dst[dst_index], val);

                frac += dst_incr_frac;

                index += dst_incr;

                if (frac >= c->src_incr) {

                    frac -= c->src_incr;

                    index++;

                }

                sample_index += index >> c->phase_shift;

                index &= c->phase_mask;

            }

        }

        *consumed = sample_index;

    } else {

        int sample_index = 0;

        for(dst_index=0; dst_index < dst_size; dst_index++){

            FELEM *filter;

            FELEM2 val=0;

            sample_index += index >> c->phase_shift;

            index &= c->phase_mask;

            filter = ((FELEM*)c->filter_bank) + c->filter_alloc*index;

            if(sample_index + c->filter_length > src_size || -sample_index >= src_size){

                break;

            }else if(sample_index < 0){

                for(i=0; i<c->filter_length; i++)

                    val += src[FFABS(sample_index + i)] * (FELEM2)filter[i];

                OUT(dst[dst_index], val);

            }else if(c->linear){

                FELEM2 v2=0;

#ifdef LINEAR_CORE

                LINEAR_CORE

#else

                for(i=0; i<c->filter_length; i++){

                    val += src[sample_index + i] * (FELEM2)filter[i];

                    v2  += src[sample_index + i] * (FELEM2)filter[i + c->filter_alloc];

                }

#endif

                val+=(v2-val)*(FELEML)frac / c->src_incr;

                OUT(dst[dst_index], val);

            }else{

#ifdef COMMON_CORE

                COMMON_CORE

#else

                for(i=0; i<c->filter_length; i++){

                    val += src[sample_index + i] * (FELEM2)filter[i];

                }

                OUT(dst[dst_index], val);

#endif

            }

            frac += dst_incr_frac;

            index += dst_incr;

            if(frac >= c->src_incr){

                frac -= c->src_incr;

                index++;

            }

        }

        *consumed= FFMAX(sample_index, 0);

        index += FFMIN(sample_index, 0) << c->phase_shift;

    }

    if(update_ctx){

        c->frac= frac;

        c->index= index;

    }

    return dst_index;

}


static uint32_t gic_dist_readb(void *opaque, hwaddr offset)

{

    GICState *s = (GICState *)opaque;

    uint32_t res;

    int irq;

    int i;

    int cpu;

    int cm;

    int mask;

    cpu = gic_get_current_cpu(s);

    cm = 1 << cpu;

    if (offset < 0x100) {

        if (offset == 0)

            return s->enabled;

        if (offset == 4)

            return ((s->num_irq / 32) - 1) | ((NUM_CPU(s) - 1) << 5);

        if (offset < 0x08)

            return 0;

        if (offset >= 0x80) {

            /* Interrupt Security , RAZ/WI */

            return 0;

        }

        goto bad_reg;

    } else if (offset < 0x200) {

        /* Interrupt Set/Clear Enable.  */

        if (offset < 0x180)

            irq = (offset - 0x100) * 8;

        else

            irq = (offset - 0x180) * 8;

        irq += GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

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

            if (GIC_TEST_ENABLED(irq + i, cm)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x300) {

        /* Interrupt Set/Clear Pending.  */

        if (offset < 0x280)

            irq = (offset - 0x200) * 8;

        else

            irq = (offset - 0x280) * 8;

        irq += GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

        mask = (irq < GIC_INTERNAL) ?  cm : ALL_CPU_MASK;

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

            if (GIC_TEST_PENDING(irq + i, mask)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x400) {

        /* Interrupt Active.  */

        irq = (offset - 0x300) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

        mask = (irq < GIC_INTERNAL) ?  cm : ALL_CPU_MASK;

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

            if (GIC_TEST_ACTIVE(irq + i, mask)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x800) {

        /* Interrupt Priority.  */

        irq = (offset - 0x400) + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = GIC_GET_PRIORITY(irq, cpu);

    } else if (offset < 0xc00) {

        /* Interrupt CPU Target.  */

        if (s->num_cpu == 1 && s->revision != REV_11MPCORE) {

            /* For uniprocessor GICs these RAZ/WI */

            res = 0;

        } else {

            irq = (offset - 0x800) + GIC_BASE_IRQ;

            if (irq >= s->num_irq) {

                goto bad_reg;

            }

            if (irq >= 29 && irq <= 31) {

                res = cm;

            } else {

                res = GIC_TARGET(irq);

            }

        }

    } else if (offset < 0xf00) {

        /* Interrupt Configuration.  */

        irq = (offset - 0xc00) * 2 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

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

            if (GIC_TEST_MODEL(irq + i))

                res |= (1 << (i * 2));

            if (GIC_TEST_EDGE_TRIGGER(irq + i))

                res |= (2 << (i * 2));

        }

    } else if (offset < 0xfe0) {

        goto bad_reg;

    } else /* offset >= 0xfe0 */ {

        if (offset & 3) {

            res = 0;

        } else {

            res = gic_id[(offset - 0xfe0) >> 2];

        }

    }

    return res;

bad_reg:

    qemu_log_mask(LOG_GUEST_ERROR,

                  "gic_dist_readb: Bad offset %x\n", (int)offset);

    return 0;

}


MemoryRegionSection memory_region_find(MemoryRegion *mr,

                                       hwaddr addr, uint64_t size)

{

    MemoryRegionSection ret = { .mr = NULL };

    MemoryRegion *root;

    AddressSpace *as;

    AddrRange range;

    FlatView *view;

    FlatRange *fr;

    addr += mr->addr;

    for (root = mr; root->parent; ) {

        root = root->parent;

        addr += root->addr;

    }

    as = memory_region_to_address_space(root);

    range = addrrange_make(int128_make64(addr), int128_make64(size));

    view = as->current_map;

    fr = flatview_lookup(view, range);

    if (!fr) {

        return ret;

    }

    while (fr > view->ranges && addrrange_intersects(fr[-1].addr, range)) {

        --fr;

    }

    ret.mr = fr->mr;

    ret.address_space = as;

    range = addrrange_intersection(range, fr->addr);

    ret.offset_within_region = fr->offset_in_region;

    ret.offset_within_region += int128_get64(int128_sub(range.start,

                                                        fr->addr.start));

    ret.size = range.size;

    ret.offset_within_address_space = int128_get64(range.start);

    ret.readonly = fr->readonly;

    memory_region_ref(ret.mr);

    return ret;

}


static void omap_tcmi_write(void *opaque, target_phys_addr_t addr,

                            uint64_t value, unsigned size)

{

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

    if (size != 4) {

        return omap_badwidth_write32(opaque, addr, value);

    }

    switch (addr) {

    case 0x00:	/* IMIF_PRIO */

    case 0x04:	/* EMIFS_PRIO */

    case 0x08:	/* EMIFF_PRIO */

    case 0x10:	/* EMIFS_CS0_CONFIG */

    case 0x14:	/* EMIFS_CS1_CONFIG */

    case 0x18:	/* EMIFS_CS2_CONFIG */

    case 0x1c:	/* EMIFS_CS3_CONFIG */

    case 0x20:	/* EMIFF_SDRAM_CONFIG */

    case 0x24:	/* EMIFF_MRS */

    case 0x28:	/* TIMEOUT1 */

    case 0x2c:	/* TIMEOUT2 */

    case 0x30:	/* TIMEOUT3 */

    case 0x3c:	/* EMIFF_SDRAM_CONFIG_2 */

    case 0x40:	/* EMIFS_CFG_DYN_WAIT */

        s->tcmi_regs[addr >> 2] = value;

        break;

    case 0x0c:	/* EMIFS_CONFIG */

        s->tcmi_regs[addr >> 2] = (value & 0xf) | (1 << 4);

        break;

    default:

        OMAP_BAD_REG(addr);

    }

}


static av_cold int xbm_encode_init(AVCodecContext *avctx)

{

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    return 0;

}


static inline void RENAME(yuvPlanartoyuy2)(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, long vertLumPerChroma)

{

    long y;

    const x86_reg chromWidth= width>>1;

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

#if COMPILE_TEMPLATE_MMX

        //FIXME handle 2 lines at once (fewer prefetches, reuse some chroma, but very likely memory-limited anyway)

        __asm__ volatile(

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

            ".p2align                    4              \n\t"

            "1:                                         \n\t"

            PREFETCH"    32(%1, %%"REG_a", 2)           \n\t"

            PREFETCH"    32(%2, %%"REG_a")              \n\t"

            PREFETCH"    32(%3, %%"REG_a")              \n\t"

            "movq          (%2, %%"REG_a"), %%mm0       \n\t" // U(0)

            "movq                    %%mm0, %%mm2       \n\t" // U(0)

            "movq          (%3, %%"REG_a"), %%mm1       \n\t" // V(0)

            "punpcklbw               %%mm1, %%mm0       \n\t" // UVUV UVUV(0)

            "punpckhbw               %%mm1, %%mm2       \n\t" // UVUV UVUV(8)

            "movq        (%1, %%"REG_a",2), %%mm3       \n\t" // Y(0)

            "movq       8(%1, %%"REG_a",2), %%mm5       \n\t" // Y(8)

            "movq                    %%mm3, %%mm4       \n\t" // Y(0)

            "movq                    %%mm5, %%mm6       \n\t" // Y(8)

            "punpcklbw               %%mm0, %%mm3       \n\t" // YUYV YUYV(0)

            "punpckhbw               %%mm0, %%mm4       \n\t" // YUYV YUYV(4)

            "punpcklbw               %%mm2, %%mm5       \n\t" // YUYV YUYV(8)

            "punpckhbw               %%mm2, %%mm6       \n\t" // YUYV YUYV(12)

            MOVNTQ"                  %%mm3,   (%0, %%"REG_a", 4)    \n\t"

            MOVNTQ"                  %%mm4,  8(%0, %%"REG_a", 4)    \n\t"

            MOVNTQ"                  %%mm5, 16(%0, %%"REG_a", 4)    \n\t"

            MOVNTQ"                  %%mm6, 24(%0, %%"REG_a", 4)    \n\t"

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

            "cmp                        %4, %%"REG_a"   \n\t"

            " jb                        1b              \n\t"

            ::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)

            : "%"REG_a

        );

#else

#if ARCH_ALPHA && HAVE_MVI

#define pl2yuy2(n)                  \

    y1 = yc[n];                     \

    y2 = yc2[n];                    \

    u = uc[n];                      \

    v = vc[n];                      \

    __asm__("unpkbw %1, %0" : "=r"(y1) : "r"(y1));  \

    __asm__("unpkbw %1, %0" : "=r"(y2) : "r"(y2));  \

    __asm__("unpkbl %1, %0" : "=r"(u) : "r"(u));    \

    __asm__("unpkbl %1, %0" : "=r"(v) : "r"(v));    \

    yuv1 = (u << 8) + (v << 24);                \

    yuv2 = yuv1 + y2;               \

    yuv1 += y1;                     \

    qdst[n]  = yuv1;                \

    qdst2[n] = yuv2;

        int i;

        uint64_t *qdst = (uint64_t *) dst;

        uint64_t *qdst2 = (uint64_t *) (dst + dstStride);

        const uint32_t *yc = (uint32_t *) ysrc;

        const uint32_t *yc2 = (uint32_t *) (ysrc + lumStride);

        const uint16_t *uc = (uint16_t*) usrc, *vc = (uint16_t*) vsrc;

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

            uint64_t y1, y2, yuv1, yuv2;

            uint64_t u, v;

            /* Prefetch */

            __asm__("ldq $31,64(%0)" :: "r"(yc));

            __asm__("ldq $31,64(%0)" :: "r"(yc2));

            __asm__("ldq $31,64(%0)" :: "r"(uc));

            __asm__("ldq $31,64(%0)" :: "r"(vc));

            pl2yuy2(0);

            pl2yuy2(1);

            pl2yuy2(2);

            pl2yuy2(3);

            yc    += 4;

            yc2   += 4;

            uc    += 4;

            vc    += 4;

            qdst  += 4;

            qdst2 += 4;

        }

        y++;

        ysrc += lumStride;

        dst += dstStride;

#elif HAVE_FAST_64BIT

        int i;

        uint64_t *ldst = (uint64_t *) dst;

        const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

            uint64_t k, l;

            k = yc[0] + (uc[0] << 8) +

                (yc[1] << 16) + (vc[0] << 24);

            l = yc[2] + (uc[1] << 8) +

                (yc[3] << 16) + (vc[1] << 24);

            *ldst++ = k + (l << 32);

            yc += 4;

            uc += 2;

            vc += 2;

        }

#else

        int i, *idst = (int32_t *) dst;

        const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

#if HAVE_BIGENDIAN

            *idst++ = (yc[0] << 24)+ (uc[0] << 16) +

                (yc[1] << 8) + (vc[0] << 0);

#else

            *idst++ = yc[0] + (uc[0] << 8) +

                (yc[1] << 16) + (vc[0] << 24);

#endif

            yc += 2;

            uc++;

            vc++;

        }

#endif

#endif

        if ((y&(vertLumPerChroma-1)) == vertLumPerChroma-1) {

            usrc += chromStride;

            vsrc += chromStride;

        }

        ysrc += lumStride;

        dst  += dstStride;

    }

#if COMPILE_TEMPLATE_MMX

    __asm__(EMMS"       \n\t"

            SFENCE"     \n\t"

            :::"memory");

#endif

}