static void slavio_timer_mem_writel(void *opaque, target_phys_addr_t addr,

                                    uint32_t val)

{

    SLAVIO_TIMERState *s = opaque;

    uint32_t saddr;

    int reload = 0;

    DPRINTF("write " TARGET_FMT_plx " %08x\n", addr, val);

    saddr = (addr & TIMER_MAXADDR) >> 2;

    switch (saddr) {

    case TIMER_LIMIT:

        if (slavio_timer_is_user(s)) {

            // set user counter MSW, reset counter

            qemu_irq_lower(s->irq);

            s->limit = TIMER_MAX_COUNT64;

            DPRINTF("processor %d user timer reset\n", s->slave_index);

            ptimer_set_limit(s->timer, LIMIT_TO_PERIODS(s->limit), 1);

        } else {

            // set limit, reset counter

            qemu_irq_lower(s->irq);

            s->limit = val & TIMER_MAX_COUNT32;

            if (!s->limit)

                s->limit = TIMER_MAX_COUNT32;

            ptimer_set_limit(s->timer, s->limit >> 9, 1);

        }

        break;

    case TIMER_COUNTER:

        if (slavio_timer_is_user(s)) {

            // set user counter LSW, reset counter

            qemu_irq_lower(s->irq);

            s->limit = TIMER_MAX_COUNT64;

            DPRINTF("processor %d user timer reset\n", s->slave_index);

            ptimer_set_limit(s->timer, LIMIT_TO_PERIODS(s->limit), 1);

        } else

            DPRINTF("not user timer\n");

        break;

    case TIMER_COUNTER_NORST:

        // set limit without resetting counter

        s->limit = val & TIMER_MAX_COUNT32;

        if (!s->limit)

            s->limit = TIMER_MAX_COUNT32;

        ptimer_set_limit(s->timer, LIMIT_TO_PERIODS(s->limit), reload);

        break;

    case TIMER_STATUS:

        if (slavio_timer_is_user(s)) {

            // start/stop user counter

            if ((val & 1) && !s->running) {

                DPRINTF("processor %d user timer started\n", s->slave_index);

                ptimer_run(s->timer, 0);

                s->running = 1;

            } else if (!(val & 1) && s->running) {

                DPRINTF("processor %d user timer stopped\n", s->slave_index);

                ptimer_stop(s->timer);

                s->running = 0;

            }

        }

        break;

    case TIMER_MODE:

        if (s->master == NULL) {

            unsigned int i;

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

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

                    qemu_irq_lower(s->slave[i]->irq);

                    s->slave[i]->limit = -1ULL;

                }

                if ((val & (1 << i)) != (s->slave_mode & (1 << i))) {

                    ptimer_stop(s->slave[i]->timer);

                    ptimer_set_limit(s->slave[i]->timer,

                                     LIMIT_TO_PERIODS(s->slave[i]->limit), 1);

                    DPRINTF("processor %d timer changed\n",

                            s->slave[i]->slave_index);

                    ptimer_run(s->slave[i]->timer, 0);

                }

            }

            s->slave_mode = val & ((1 << s->num_slaves) - 1);

        } else

            DPRINTF("not system timer\n");

        break;

    default:

        DPRINTF("invalid write address " TARGET_FMT_plx "\n", addr);

        break;

    }

}


void qemu_cpu_kick(void *env)

{

    return;

}


static void temp_allocate_frame(TCGContext *s, int temp)

{

    TCGTemp *ts;

    ts = &s->temps[temp];

    s->current_frame_offset = (s->current_frame_offset + sizeof(tcg_target_long) - 1) & ~(sizeof(tcg_target_long) - 1);

    if (s->current_frame_offset + sizeof(tcg_target_long) > s->frame_end)

        tcg_abort();

    ts->mem_offset = s->current_frame_offset;

    ts->mem_reg = s->frame_reg;

    ts->mem_allocated = 1;

    s->current_frame_offset += sizeof(tcg_target_long);

}


void qmp_block_stream(const char *device, bool has_base,

                      const char *base, Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *base_bs = NULL;

    Error *local_err = NULL;

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (base) {

        base_bs = bdrv_find_backing_image(bs, base);

        if (base_bs == NULL) {

            error_set(errp, QERR_BASE_NOT_FOUND, base);

            return;

        }

    }

    stream_start(bs, base_bs, base, block_stream_cb, bs, &local_err);

    if (error_is_set(&local_err)) {

        error_propagate(errp, local_err);

        return;

    }

    /* Grab a reference so hotplug does not delete the BlockDriverState from

     * underneath us.

     */

    drive_get_ref(drive_get_by_blockdev(bs));

    trace_qmp_block_stream(bs, bs->job);

}


static void mptsas_scsi_init(PCIDevice *dev, Error **errp)

{

    DeviceState *d = DEVICE(dev);

    MPTSASState *s = MPT_SAS(dev);

    dev->config[PCI_LATENCY_TIMER] = 0;

    dev->config[PCI_INTERRUPT_PIN] = 0x01;

    memory_region_init_io(&s->mmio_io, OBJECT(s), &mptsas_mmio_ops, s,

                          "mptsas-mmio", 0x4000);

    memory_region_init_io(&s->port_io, OBJECT(s), &mptsas_port_ops, s,

                          "mptsas-io", 256);

    memory_region_init_io(&s->diag_io, OBJECT(s), &mptsas_diag_ops, s,

                          "mptsas-diag", 0x10000);

    if (s->msi != ON_OFF_AUTO_OFF &&

        msi_init(dev, 0, 1, true, false) >= 0) {

        /* TODO check for errors */

        s->msi_in_use = true;

    }

    pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &s->port_io);

    pci_register_bar(dev, 1, PCI_BASE_ADDRESS_SPACE_MEMORY |

                                 PCI_BASE_ADDRESS_MEM_TYPE_32, &s->mmio_io);

    pci_register_bar(dev, 2, PCI_BASE_ADDRESS_SPACE_MEMORY |

                                 PCI_BASE_ADDRESS_MEM_TYPE_32, &s->diag_io);

    if (!s->sas_addr) {

        s->sas_addr = ((NAA_LOCALLY_ASSIGNED_ID << 24) |

                       IEEE_COMPANY_LOCALLY_ASSIGNED) << 36;

        s->sas_addr |= (pci_bus_num(dev->bus) << 16);

        s->sas_addr |= (PCI_SLOT(dev->devfn) << 8);

        s->sas_addr |= PCI_FUNC(dev->devfn);

    }

    s->max_devices = MPTSAS_NUM_PORTS;

    s->request_bh = qemu_bh_new(mptsas_fetch_requests, s);

    QTAILQ_INIT(&s->pending);

    scsi_bus_new(&s->bus, sizeof(s->bus), &dev->qdev, &mptsas_scsi_info, NULL);

    if (!d->hotplugged) {

        scsi_bus_legacy_handle_cmdline(&s->bus, errp);

    }

}


static inline int num_effective_busses(XilinxSPIPS *s)

{

    return (s->regs[R_LQSPI_STS] & LQSPI_CFG_SEP_BUS &&

            s->regs[R_LQSPI_STS] & LQSPI_CFG_TWO_MEM) ? s->num_busses : 1;

}


FFTContext *av_fft_init(int nbits, int inverse)

{

    FFTContext *s = av_malloc(sizeof(*s));

    if (s && ff_fft_init(s, nbits, inverse))

        av_freep(&s);

    return s;

}


static void gen_set_CF_bit31(TCGv var)

{

    TCGv tmp = new_tmp();

    tcg_gen_shri_i32(tmp, var, 31);

    gen_set_CF(tmp);

    dead_tmp(tmp);

}


static int get_siz(Jpeg2000DecoderContext *s)
{
    int i;
    int ncomponents;
    uint32_t log2_chroma_wh = 0;
    const enum AVPixelFormat *possible_fmts = NULL;
    int possible_fmts_nb = 0;
    if (bytestream2_get_bytes_left(&s->g) < 36) {
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for SIZ\n");
    s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
    s->width          = bytestream2_get_be32u(&s->g); // Width
    s->height         = bytestream2_get_be32u(&s->g); // Height
    s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
    s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
    s->tile_width     = bytestream2_get_be32u(&s->g); // XTSiz
    s->tile_height    = bytestream2_get_be32u(&s->g); // YTSiz
    s->tile_offset_x  = bytestream2_get_be32u(&s->g); // XT0Siz
    s->tile_offset_y  = bytestream2_get_be32u(&s->g); // YT0Siz
    ncomponents       = bytestream2_get_be16u(&s->g); // CSiz
    if (s->image_offset_x || s->image_offset_y) {
        avpriv_request_sample(s->avctx, "Support for image offsets");
        return AVERROR_PATCHWELCOME;
    if (av_image_check_size(s->width, s->height, 0, s->avctx)) {
        avpriv_request_sample(s->avctx, "Large Dimensions");
        return AVERROR_PATCHWELCOME;
    if (ncomponents <= 0) {
        av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
    if (ncomponents > 4) {
        avpriv_request_sample(s->avctx, "Support for %d components",
                              ncomponents);
        return AVERROR_PATCHWELCOME;
    s->ncomponents = ncomponents;
    if (s->tile_width <= 0 || s->tile_height <= 0) {
        av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
               s->tile_width, s->tile_height);
    if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) {
        av_log(s->avctx, AV_LOG_ERROR, "Insufficient space for %d components in SIZ\n", s->ncomponents);
    for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
        uint8_t x    = bytestream2_get_byteu(&s->g);
        s->cbps[i]   = (x & 0x7f) + 1;
        s->precision = FFMAX(s->cbps[i], s->precision);
        s->sgnd[i]   = !!(x & 0x80);
        s->cdx[i]    = bytestream2_get_byteu(&s->g);
        s->cdy[i]    = bytestream2_get_byteu(&s->g);
        if (   !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
            || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
            av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
        log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
    s->numXtiles = ff_jpeg2000_ceildiv(s->width  - s->tile_offset_x, s->tile_width);
    s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
    if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
        s->numXtiles = s->numYtiles = 0;
        return AVERROR(EINVAL);
    s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
    if (!s->tile) {
        s->numXtiles = s->numYtiles = 0;
        return AVERROR(ENOMEM);
    for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
        Jpeg2000Tile *tile = s->tile + i;
        tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
        if (!tile->comp)
            return AVERROR(ENOMEM);
    /* compute image size with reduction factor */
    s->avctx->width  = ff_jpeg2000_ceildivpow2(s->width  - s->image_offset_x,
                                               s->reduction_factor);
    s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
                                               s->reduction_factor);
    if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
        s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
        possible_fmts = xyz_pix_fmts;
        possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
    } else {
        switch (s->colour_space) {
        case 16:
            possible_fmts = rgb_pix_fmts;
            possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
            break;
        case 17:
            possible_fmts = gray_pix_fmts;
            possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
            break;
        case 18:
            possible_fmts = yuv_pix_fmts;
            possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
            break;
        default:
            possible_fmts = all_pix_fmts;
            possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
            break;
    for (i = 0; i < possible_fmts_nb; ++i) {
        if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
            s->avctx->pix_fmt = possible_fmts[i];
            break;
    if (i == possible_fmts_nb) {
        if (ncomponents == 4 &&
            s->cdy[0] == 1 && s->cdx[0] == 1 &&
            s->cdy[1] == 1 && s->cdx[1] == 1 &&
            s->cdy[2] == s->cdy[3] && s->cdx[2] == s->cdx[3]) {
            if (s->precision == 8 && s->cdy[2] == 2 && s->cdx[2] == 2 && !s->pal8) {
                s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
                s->cdef[0] = 0;
                s->cdef[1] = 1;
                s->cdef[2] = 2;
                s->cdef[3] = 3;
                i = 0;
    if (i == possible_fmts_nb) {
        av_log(s->avctx, AV_LOG_ERROR,
               "Unknown pix_fmt, profile: %d, colour_space: %d, "
               "components: %d, precision: %d\n"
               "cdx[0]: %d, cdy[0]: %d\n"
               "cdx[1]: %d, cdy[1]: %d\n"
               "cdx[2]: %d, cdy[2]: %d\n"
               "cdx[3]: %d, cdy[3]: %d\n",
               s->avctx->profile, s->colour_space, ncomponents, s->precision,
               s->cdx[0],
               s->cdy[0],
               ncomponents > 1 ? s->cdx[1] : 0,
               ncomponents > 1 ? s->cdy[1] : 0,
               ncomponents > 2 ? s->cdx[2] : 0,
               ncomponents > 2 ? s->cdy[2] : 0,
               ncomponents > 3 ? s->cdx[3] : 0,
               ncomponents > 3 ? s->cdy[3] : 0);
        return AVERROR_PATCHWELCOME;
    s->avctx->bits_per_raw_sample = s->precision;
    return 0;


static void commit_set_speed(BlockJob *job, int64_t speed, Error **errp)

{

    CommitBlockJob *s = container_of(job, CommitBlockJob, common);

    if (speed < 0) {

        error_setg(errp, QERR_INVALID_PARAMETER, "speed");

        return;

    }

    ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);

}


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

{

	int i;

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

	{

		int r=  ((uint32_t*)src)[i]&0xFF;

		int g= (((uint32_t*)src)[i]>>8)&0xFF;

		int b= (((uint32_t*)src)[i]>>16)&0xFF;

		dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)) )>>RGB2YUV_SHIFT);

	}

}


static uint32_t s390_pci_generate_fid(Error **errp)

{

    uint32_t fid = 0;

    while (fid <= ZPCI_MAX_FID) {

        if (!s390_pci_find_dev_by_fid(fid)) {

            return fid;

        }

        if (fid == ZPCI_MAX_FID) {

            break;

        }

        fid++;

    }

    error_setg(errp, "no free fid could be found");

    return 0;

}


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

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    V9fsVirtioState *v = VIRTIO_9P(dev);

    V9fsState *s = &v->state;

    virtio_cleanup(vdev);

    v9fs_device_unrealize_common(s, errp);

}


static int ipmovie_read_packet(AVFormatContext *s,

                               AVPacket *pkt)

{

    IPMVEContext *ipmovie = (IPMVEContext *)s->priv_data;

    ByteIOContext *pb = &s->pb;

    int ret;

    ret = process_ipmovie_chunk(ipmovie, pb, pkt);

    if (ret == CHUNK_BAD)

        ret = AVERROR_INVALIDDATA;

    else if (ret == CHUNK_EOF)

        ret = AVERROR_IO;

    else if (ret == CHUNK_NOMEM)

        ret = AVERROR_NOMEM;

    else

        ret = 0;

    return ret;

}


static int opus_decode_frame(OpusStreamContext *s, const uint8_t *data, int size)

{

    int samples    = s->packet.frame_duration;

    int redundancy = 0;

    int redundancy_size, redundancy_pos;

    int ret, i, consumed;

    int delayed_samples = s->delayed_samples;

    ret = opus_rc_init(&s->rc, data, size);

    if (ret < 0)

        return ret;

    /* decode the silk frame */

    if (s->packet.mode == OPUS_MODE_SILK || s->packet.mode == OPUS_MODE_HYBRID) {

        if (!swr_is_initialized(s->swr)) {

            ret = opus_init_resample(s);

            if (ret < 0)

                return ret;

        }

        samples = ff_silk_decode_superframe(s->silk, &s->rc, s->silk_output,

                                            FFMIN(s->packet.bandwidth, OPUS_BANDWIDTH_WIDEBAND),

                                            s->packet.stereo + 1,

                                            silk_frame_duration_ms[s->packet.config]);

        if (samples < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "Error decoding a SILK frame.\n");

            return samples;

        }

        samples = swr_convert(s->swr,

                              (uint8_t**)s->out, s->packet.frame_duration,

                              (const uint8_t**)s->silk_output, samples);

        if (samples < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "Error resampling SILK data.\n");

            return samples;

        }

        s->delayed_samples += s->packet.frame_duration - samples;

    } else

        ff_silk_flush(s->silk);

    // decode redundancy information

    consumed = opus_rc_tell(&s->rc);

    if (s->packet.mode == OPUS_MODE_HYBRID && consumed + 37 <= size * 8)

        redundancy = opus_rc_p2model(&s->rc, 12);

    else if (s->packet.mode == OPUS_MODE_SILK && consumed + 17 <= size * 8)

        redundancy = 1;

    if (redundancy) {

        redundancy_pos = opus_rc_p2model(&s->rc, 1);

        if (s->packet.mode == OPUS_MODE_HYBRID)

            redundancy_size = opus_rc_unimodel(&s->rc, 256) + 2;

        else

            redundancy_size = size - (consumed + 7) / 8;

        size -= redundancy_size;

        if (size < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "Invalid redundancy frame size.\n");

            return AVERROR_INVALIDDATA;

        }

        if (redundancy_pos) {

            ret = opus_decode_redundancy(s, data + size, redundancy_size);

            if (ret < 0)

                return ret;

            ff_celt_flush(s->celt);

        }

    }

    /* decode the CELT frame */

    if (s->packet.mode == OPUS_MODE_CELT || s->packet.mode == OPUS_MODE_HYBRID) {

        float *out_tmp[2] = { s->out[0], s->out[1] };

        float **dst = (s->packet.mode == OPUS_MODE_CELT) ?

                      out_tmp : s->celt_output;

        int celt_output_samples = samples;

        int delay_samples = av_audio_fifo_size(s->celt_delay);

        if (delay_samples) {

            if (s->packet.mode == OPUS_MODE_HYBRID) {

                av_audio_fifo_read(s->celt_delay, (void**)s->celt_output, delay_samples);

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

                    s->fdsp->vector_fmac_scalar(out_tmp[i], s->celt_output[i], 1.0,

                                                delay_samples);

                    out_tmp[i] += delay_samples;

                }

                celt_output_samples -= delay_samples;

            } else {

                av_log(s->avctx, AV_LOG_WARNING,

                       "Spurious CELT delay samples present.\n");

                av_audio_fifo_drain(s->celt_delay, delay_samples);

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

                    return AVERROR_BUG;

            }

        }

        opus_raw_init(&s->rc, data + size, size);

        ret = ff_celt_decode_frame(s->celt, &s->rc, dst,

                                   s->packet.stereo + 1,

                                   s->packet.frame_duration,

                                   (s->packet.mode == OPUS_MODE_HYBRID) ? 17 : 0,

                                   celt_band_end[s->packet.bandwidth]);

        if (ret < 0)

            return ret;

        if (s->packet.mode == OPUS_MODE_HYBRID) {

            int celt_delay = s->packet.frame_duration - celt_output_samples;

            void *delaybuf[2] = { s->celt_output[0] + celt_output_samples,

                                  s->celt_output[1] + celt_output_samples };

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

                s->fdsp->vector_fmac_scalar(out_tmp[i],

                                            s->celt_output[i], 1.0,

                                            celt_output_samples);

            }

            ret = av_audio_fifo_write(s->celt_delay, delaybuf, celt_delay);

            if (ret < 0)

                return ret;

        }

    } else

        ff_celt_flush(s->celt);

    if (s->redundancy_idx) {

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

            opus_fade(s->out[i], s->out[i],

                      s->redundancy_output[i] + 120 + s->redundancy_idx,

                      ff_celt_window2 + s->redundancy_idx, 120 - s->redundancy_idx);

        s->redundancy_idx = 0;

    }

    if (redundancy) {

        if (!redundancy_pos) {

            ff_celt_flush(s->celt);

            ret = opus_decode_redundancy(s, data + size, redundancy_size);

            if (ret < 0)

                return ret;

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

                opus_fade(s->out[i] + samples - 120 + delayed_samples,

                          s->out[i] + samples - 120 + delayed_samples,

                          s->redundancy_output[i] + 120,

                          ff_celt_window2, 120 - delayed_samples);

                if (delayed_samples)

                    s->redundancy_idx = 120 - delayed_samples;

            }

        } else {

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

                memcpy(s->out[i] + delayed_samples, s->redundancy_output[i], 120 * sizeof(float));

                opus_fade(s->out[i] + 120 + delayed_samples,

                          s->redundancy_output[i] + 120,

                          s->out[i] + 120 + delayed_samples,

                          ff_celt_window2, 120);

            }

        }

    }

    return samples;

}


bool qemu_co_enter_next(CoQueue *queue)

{

    Coroutine *next;

    next = QSIMPLEQ_FIRST(&queue->entries);

    if (!next) {

        return false;

    }

    QSIMPLEQ_REMOVE_HEAD(&queue->entries, co_queue_next);

    qemu_coroutine_enter(next, NULL);

    return true;

}


static int decodeChannelSoundUnit (ATRAC3Context *q, GetBitContext *gb, channel_unit *pSnd, float *pOut, int channelNum, int codingMode)

{

    int   band, result=0, numSubbands, lastTonal, numBands;

    if (codingMode == JOINT_STEREO && channelNum == 1) {

        if (get_bits(gb,2) != 3) {

            av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");

            return -1;

        }

    } else {

        if (get_bits(gb,6) != 0x28) {

            av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");

            return -1;

        }

    }

    /* number of coded QMF bands */

    pSnd->bandsCoded = get_bits(gb,2);

    result = decodeGainControl (gb, &(pSnd->gainBlock[pSnd->gcBlkSwitch]), pSnd->bandsCoded);

    if (result) return result;

    pSnd->numComponents = decodeTonalComponents (gb, pSnd->components, pSnd->bandsCoded);

    if (pSnd->numComponents == -1) return -1;

    numSubbands = decodeSpectrum (gb, pSnd->spectrum);

    /* Merge the decoded spectrum and tonal components. */

    lastTonal = addTonalComponents (pSnd->spectrum, pSnd->numComponents, pSnd->components);

    /* calculate number of used MLT/QMF bands according to the amount of coded spectral lines */

    numBands = (subbandTab[numSubbands] - 1) >> 8;

    if (lastTonal >= 0)

        numBands = FFMAX((lastTonal + 256) >> 8, numBands);

    /* Reconstruct time domain samples. */

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

        /* Perform the IMDCT step without overlapping. */

        if (band <= numBands) {

            IMLT(&(pSnd->spectrum[band*256]), pSnd->IMDCT_buf, band&1);

        } else

            memset(pSnd->IMDCT_buf, 0, 512 * sizeof(float));

        /* gain compensation and overlapping */

        gainCompensateAndOverlap (pSnd->IMDCT_buf, &(pSnd->prevFrame[band*256]), &(pOut[band*256]),

                                    &((pSnd->gainBlock[1 - (pSnd->gcBlkSwitch)]).gBlock[band]),

                                    &((pSnd->gainBlock[pSnd->gcBlkSwitch]).gBlock[band]));

    }

    /* Swap the gain control buffers for the next frame. */

    pSnd->gcBlkSwitch ^= 1;

    return 0;

}


static target_long monitor_get_reg(const struct MonitorDef *md, int val)

{

    CPUState *env = mon_get_cpu();

    if (!env)

        return 0;

    return env->regwptr[val];

}


static void vp8_idct_dc_add4uv_c(uint8_t *dst, int16_t block[4][16], ptrdiff_t stride)

{

    vp8_idct_dc_add_c(dst+stride*0+0, block[0], stride);

    vp8_idct_dc_add_c(dst+stride*0+4, block[1], stride);

    vp8_idct_dc_add_c(dst+stride*4+0, block[2], stride);

    vp8_idct_dc_add_c(dst+stride*4+4, block[3], stride);

}


static void integratorcp_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    ARMCPU *cpu;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *ram_alias = g_new(MemoryRegion, 1);

    qemu_irq pic[32];

    DeviceState *dev;

    int i;

    if (!cpu_model) {

        cpu_model = "arm926";

    }

    cpu = cpu_arm_init(cpu_model);

    if (!cpu) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    memory_region_init_ram(ram, NULL, "integrator.ram", ram_size);

    vmstate_register_ram_global(ram);

    /* ??? On a real system the first 1Mb is mapped as SSRAM or boot flash.  */

    /* ??? RAM should repeat to fill physical memory space.  */

    /* SDRAM at address zero*/

    memory_region_add_subregion(address_space_mem, 0, ram);

    /* And again at address 0x80000000 */

    memory_region_init_alias(ram_alias, NULL, "ram.alias", ram, 0, ram_size);

    memory_region_add_subregion(address_space_mem, 0x80000000, ram_alias);

    dev = qdev_create(NULL, TYPE_INTEGRATOR_CM);

    qdev_prop_set_uint32(dev, "memsz", ram_size >> 20);

    qdev_init_nofail(dev);

    sysbus_mmio_map((SysBusDevice *)dev, 0, 0x10000000);

    dev = sysbus_create_varargs(TYPE_INTEGRATOR_PIC, 0x14000000,

                                qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_IRQ),

                                qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_FIQ),

                                NULL);

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

        pic[i] = qdev_get_gpio_in(dev, i);

    }

    sysbus_create_simple(TYPE_INTEGRATOR_PIC, 0xca000000, pic[26]);

    sysbus_create_varargs("integrator_pit", 0x13000000,

                          pic[5], pic[6], pic[7], NULL);

    sysbus_create_simple("pl031", 0x15000000, pic[8]);

    sysbus_create_simple("pl011", 0x16000000, pic[1]);

    sysbus_create_simple("pl011", 0x17000000, pic[2]);

    icp_control_init(0xcb000000);

    sysbus_create_simple("pl050_keyboard", 0x18000000, pic[3]);

    sysbus_create_simple("pl050_mouse", 0x19000000, pic[4]);

    sysbus_create_varargs("pl181", 0x1c000000, pic[23], pic[24], NULL);

    if (nd_table[0].used)

        smc91c111_init(&nd_table[0], 0xc8000000, pic[27]);

    sysbus_create_simple("pl110", 0xc0000000, pic[22]);

    integrator_binfo.ram_size = ram_size;

    integrator_binfo.kernel_filename = kernel_filename;

    integrator_binfo.kernel_cmdline = kernel_cmdline;

    integrator_binfo.initrd_filename = initrd_filename;

    arm_load_kernel(cpu, &integrator_binfo);

}


static void set_vlan(Object *obj, Visitor *v, void *opaque,

                     const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    NICPeers *peers_ptr = qdev_get_prop_ptr(dev, prop);

    NetClientState **ptr = &peers_ptr->ncs[0];

    Error *local_err = NULL;

    int32_t id;

    NetClientState *hubport;

    if (dev->realized) {

        qdev_prop_set_after_realize(dev, name, errp);

    visit_type_int32(v, &id, name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

    if (id == -1) {

        *ptr = NULL;

    hubport = net_hub_port_find(id);

    if (!hubport) {

        error_set(errp, QERR_INVALID_PARAMETER_VALUE,

                  name, prop->info->name);

    *ptr = hubport;


static av_cold int png_dec_end(AVCodecContext *avctx)

{

    PNGDecContext *s = avctx->priv_data;

    ff_thread_release_buffer(avctx, &s->previous_picture);

    av_frame_free(&s->previous_picture.f);

    ff_thread_release_buffer(avctx, &s->last_picture);

    av_frame_free(&s->last_picture.f);

    ff_thread_release_buffer(avctx, &s->picture);

    av_frame_free(&s->picture.f);

    av_freep(&s->buffer);

    s->buffer_size = 0;

    av_freep(&s->last_row);

    s->last_row_size = 0;

    av_freep(&s->tmp_row);

    s->tmp_row_size = 0;

    av_freep(&s->extra_data);

    s->extra_data_size = 0;

    return 0;

}


static void fd_chr_update_read_handler(CharDriverState *chr)

{

    FDCharDriver *s = chr->opaque;

    if (s->fd_in_tag) {

        g_source_remove(s->fd_in_tag);

        s->fd_in_tag = 0;

    }

    if (s->fd_in) {

        s->fd_in_tag = io_add_watch_poll(s->fd_in, fd_chr_read_poll, fd_chr_read, chr);

    }

}


static int probe_file(WriterContext *wctx, const char *filename)

{

    AVFormatContext *fmt_ctx;

    int ret, i;

    int section_id;

    do_read_frames = do_show_frames || do_count_frames;

    do_read_packets = do_show_packets || do_count_packets;

    ret = open_input_file(&fmt_ctx, filename);

    if (ret < 0)

        return ret;

#define CHECK_END if (ret < 0) goto end

    nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));

    nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));

    selected_streams   = av_calloc(fmt_ctx->nb_streams, sizeof(*selected_streams));

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

        if (stream_specifier) {

            ret = avformat_match_stream_specifier(fmt_ctx,

                                                  fmt_ctx->streams[i],

                                                  stream_specifier);

            CHECK_END;

            else

                selected_streams[i] = ret;

            ret = 0;

        } else {

            selected_streams[i] = 1;

        }

    }

    if (do_read_frames || do_read_packets) {

        if (do_show_frames && do_show_packets &&

            wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)

            section_id = SECTION_ID_PACKETS_AND_FRAMES;

        else if (do_show_packets && !do_show_frames)

            section_id = SECTION_ID_PACKETS;

        else // (!do_show_packets && do_show_frames)

            section_id = SECTION_ID_FRAMES;

        if (do_show_frames || do_show_packets)

            writer_print_section_header(wctx, section_id);

        ret = read_packets(wctx, fmt_ctx);

        if (do_show_frames || do_show_packets)

            writer_print_section_footer(wctx);

        CHECK_END;

    }

    if (do_show_programs) {

        ret = show_programs(wctx, fmt_ctx);

        CHECK_END;

    }

    if (do_show_streams) {

        ret = show_streams(wctx, fmt_ctx);

        CHECK_END;

    }

    if (do_show_chapters) {

        ret = show_chapters(wctx, fmt_ctx);

        CHECK_END;

    }

    if (do_show_format) {

        ret = show_format(wctx, fmt_ctx);

        CHECK_END;

    }

end:

    close_input_file(&fmt_ctx);

    av_freep(&nb_streams_frames);

    av_freep(&nb_streams_packets);

    av_freep(&selected_streams);

    return ret;

}


static int kvm_physical_sync_dirty_bitmap(target_phys_addr_t start_addr,

                                          target_phys_addr_t end_addr)

{

    KVMState *s = kvm_state;

    unsigned long size, allocated_size = 0;

    KVMDirtyLog d;

    KVMSlot *mem;

    int ret = 0;

    d.dirty_bitmap = NULL;

    while (start_addr < end_addr) {

        mem = kvm_lookup_overlapping_slot(s, start_addr, end_addr);

        if (mem == NULL) {

            break;

        }

        size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS), HOST_LONG_BITS) / 8;

        if (!d.dirty_bitmap) {

            d.dirty_bitmap = qemu_malloc(size);

        } else if (size > allocated_size) {

            d.dirty_bitmap = qemu_realloc(d.dirty_bitmap, size);

        }

        allocated_size = size;

        memset(d.dirty_bitmap, 0, allocated_size);

        d.slot = mem->slot;

        if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {

            DPRINTF("ioctl failed %d\n", errno);

            ret = -1;

            break;

        }

        kvm_get_dirty_pages_log_range(mem->start_addr, d.dirty_bitmap,

                                      mem->start_addr, mem->memory_size);

        start_addr = mem->start_addr + mem->memory_size;

    }

    qemu_free(d.dirty_bitmap);

    return ret;

}


static void filter(USPPContext *p, uint8_t *dst[3], uint8_t *src[3],

                   int dst_stride[3], int src_stride[3], int width,

                   int height, uint8_t *qp_store, int qp_stride)

{

    int x, y, i, j;

    const int count = 1<<p->log2_count;

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

        int is_chroma = !!i;

        int w = width  >> (is_chroma ? p->hsub : 0);

        int h = height >> (is_chroma ? p->vsub : 0);

        int stride = p->temp_stride[i];

        int block = BLOCK >> (is_chroma ? p->hsub : 0);

        if (!src[i] || !dst[i])

            continue;

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

            int index = block + block * stride + y * stride;

            memcpy(p->src[i] + index, src[i] + y * src_stride[i], w );

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

                p->src[i][index     - x - 1] = p->src[i][index +     x    ];

                p->src[i][index + w + x    ] = p->src[i][index + w - x - 1];

            }

        }

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

            memcpy(p->src[i] + (  block-1-y) * stride, p->src[i] + (  y+block  ) * stride, stride);

            memcpy(p->src[i] + (h+block  +y) * stride, p->src[i] + (h-y+block-1) * stride, stride);

        }

        p->frame->linesize[i] = stride;

        memset(p->temp[i], 0, (h + 2 * block) * stride * sizeof(int16_t));

    }

    if (p->qp)

        p->frame->quality = p->qp * FF_QP2LAMBDA;

    else {

        int qpsum=0;

        int qpcount = (height>>4) * (height>>4);

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

            for (x = 0; x < (width>>4); x++)

                qpsum += qp_store[x + y * qp_stride];

        }

        p->frame->quality = norm_qscale((qpsum + qpcount/2) / qpcount, p->qscale_type) * FF_QP2LAMBDA;

    }

//    init per MB qscale stuff FIXME

    p->frame->height = height;

    p->frame->width  = width;

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

        const int x1 = offset[i+count-1][0];

        const int y1 = offset[i+count-1][1];

        const int x1c = x1 >> p->hsub;

        const int y1c = y1 >> p->vsub;

        const int BLOCKc = BLOCK >> p->hsub;

        int offset;

        AVPacket pkt;

        int got_pkt_ptr;

        av_init_packet(&pkt);

        pkt.data = p->outbuf;

        pkt.size = p->outbuf_size;

        p->frame->data[0] = p->src[0] + x1   + y1   * p->frame->linesize[0];

        p->frame->data[1] = p->src[1] + x1c  + y1c  * p->frame->linesize[1];

        p->frame->data[2] = p->src[2] + x1c  + y1c  * p->frame->linesize[2];

        p->frame->format  = p->avctx_enc[i]->pix_fmt;

        avcodec_encode_video2(p->avctx_enc[i], &pkt, p->frame, &got_pkt_ptr);

        p->frame_dec = p->avctx_enc[i]->coded_frame;

        offset = (BLOCK-x1) + (BLOCK-y1) * p->frame_dec->linesize[0];

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

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

                p->temp[0][x + y * p->temp_stride[0]] += p->frame_dec->data[0][x + y * p->frame_dec->linesize[0] + offset];

        if (!src[2] || !dst[2])

            continue;

        offset = (BLOCKc-x1c) + (BLOCKc-y1c) * p->frame_dec->linesize[1];

        for (y = 0; y < height>>p->vsub; y++) {

            for (x = 0; x < width>>p->hsub; x++) {

                p->temp[1][x + y * p->temp_stride[1]] += p->frame_dec->data[1][x + y * p->frame_dec->linesize[1] + offset];

                p->temp[2][x + y * p->temp_stride[2]] += p->frame_dec->data[2][x + y * p->frame_dec->linesize[2] + offset];

            }

        }

    }

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

        int is_chroma = !!j;

        if (!dst[j])

            continue;

        store_slice_c(dst[j], p->temp[j], dst_stride[j], p->temp_stride[j],

                      width  >> (is_chroma ? p->hsub : 0),

                      height >> (is_chroma ? p->vsub : 0),

                      8-p->log2_count);

    }

}


int main(void)

{

    int nf;

    Suite *s;

    SRunner *sr;

    s = qfloat_suite();

    sr = srunner_create(s);

    srunner_run_all(sr, CK_NORMAL);

    nf = srunner_ntests_failed(sr);

    srunner_free(sr);

    return (nf == 0) ? EXIT_SUCCESS : EXIT_FAILURE;

}


static target_ulong put_tce_emu(sPAPRTCETable *tcet, target_ulong ioba,

                                target_ulong tce)

{

    IOMMUTLBEntry entry;

    hwaddr page_mask = IOMMU_PAGE_MASK(tcet->page_shift);

    unsigned long index = (ioba - tcet->bus_offset) >> tcet->page_shift;

    if (index >= tcet->nb_table) {

        hcall_dprintf("spapr_vio_put_tce on out-of-bounds IOBA 0x"

                      TARGET_FMT_lx "\n", ioba);

        return H_PARAMETER;

    }

    tcet->table[index] = tce;

    entry.target_as = &address_space_memory,

    entry.iova = ioba & page_mask;

    entry.translated_addr = tce & page_mask;

    entry.addr_mask = ~page_mask;

    entry.perm = spapr_tce_iommu_access_flags(tce);

    memory_region_notify_iommu(&tcet->iommu, entry);

    return H_SUCCESS;

}


static target_ulong h_enter(CPUState *env, sPAPREnvironment *spapr,

                            target_ulong opcode, target_ulong *args)

{

    target_ulong flags = args[0];

    target_ulong pte_index = args[1];

    target_ulong pteh = args[2];

    target_ulong ptel = args[3];

    target_ulong i;

    uint8_t *hpte;

    /* only handle 4k and 16M pages for now */

    if (pteh & HPTE_V_LARGE) {

#if 0 /* We don't support 64k pages yet */

        if ((ptel & 0xf000) == 0x1000) {

            /* 64k page */

        } else

#endif

        if ((ptel & 0xff000) == 0) {

            /* 16M page */

            /* lowest AVA bit must be 0 for 16M pages */

            if (pteh & 0x80) {

                return H_PARAMETER;

            }

        } else {

            return H_PARAMETER;

        }

    }

    /* FIXME: bounds check the pa? */

    /* Check WIMG */

    if ((ptel & HPTE_R_WIMG) != HPTE_R_M) {

        return H_PARAMETER;

    }

    pteh &= ~0x60ULL;

    if ((pte_index * HASH_PTE_SIZE_64) & ~env->htab_mask) {

        return H_PARAMETER;

    }

    if (likely((flags & H_EXACT) == 0)) {

        pte_index &= ~7ULL;

        hpte = env->external_htab + (pte_index * HASH_PTE_SIZE_64);

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

            if (i == 8) {

                return H_PTEG_FULL;

            }

            if (((ldq_p(hpte) & HPTE_V_VALID) == 0) &&

                lock_hpte(hpte, HPTE_V_HVLOCK | HPTE_V_VALID)) {

                break;

            }

            hpte += HASH_PTE_SIZE_64;

        }

    } else {

        i = 0;

        hpte = env->external_htab + (pte_index * HASH_PTE_SIZE_64);

        if (!lock_hpte(hpte, HPTE_V_HVLOCK | HPTE_V_VALID)) {

            return H_PTEG_FULL;

        }

    }

    stq_p(hpte + (HASH_PTE_SIZE_64/2), ptel);

    /* eieio();  FIXME: need some sort of barrier for smp? */

    stq_p(hpte, pteh);

    assert(!(ldq_p(hpte) & HPTE_V_HVLOCK));

    args[0] = pte_index + i;

    return H_SUCCESS;

}


static inline void gen_op_arith_add(DisasContext *ctx, TCGv ret, TCGv arg1,

                                    TCGv arg2, int add_ca, int compute_ca,

                                    int compute_ov)

{

    TCGv t0, t1;

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

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

        t0 = ret;

    } else {

        t0 = tcg_temp_local_new();

    }

    if (add_ca) {

        t1 = tcg_temp_local_new();

        tcg_gen_mov_tl(t1, cpu_ca);

    } else {

        TCGV_UNUSED(t1);

    }

    if (compute_ca) {

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

        tcg_gen_movi_tl(cpu_ca, 0);

    }

    if (compute_ov) {

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

        tcg_gen_movi_tl(cpu_ov, 0);

    }

    tcg_gen_add_tl(t0, arg1, arg2);

    if (compute_ca) {

        gen_op_arith_compute_ca(ctx, t0, arg1, 0);

    }

    if (add_ca) {

        tcg_gen_add_tl(t0, t0, t1);

        gen_op_arith_compute_ca(ctx, t0, t1, 0);

        tcg_temp_free(t1);

    }

    if (compute_ov) {

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

    }

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

        gen_set_Rc0(ctx, t0);

    if (!TCGV_EQUAL(t0, ret)) {

        tcg_gen_mov_tl(ret, t0);

        tcg_temp_free(t0);

    }

}


static inline void RENAME(rgb15tobgr24)(const uint8_t *src, uint8_t *dst, int src_size)

{

    const uint16_t *end;

    const uint16_t *mm_end;

    uint8_t *d = dst;

    const uint16_t *s = (const uint16_t*)src;

    end = s + src_size/2;

    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");

    mm_end = end - 7;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

            "movq          %1, %%mm0    \n\t"

            "movq          %1, %%mm1    \n\t"

            "movq          %1, %%mm2    \n\t"

            "pand          %2, %%mm0    \n\t"

            "pand          %3, %%mm1    \n\t"

            "pand          %4, %%mm2    \n\t"

            "psllq         $3, %%mm0    \n\t"

            "psrlq         $2, %%mm1    \n\t"

            "psrlq         $7, %%mm2    \n\t"

            "movq       %%mm0, %%mm3    \n\t"

            "movq       %%mm1, %%mm4    \n\t"

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

            "punpcklwd     %5, %%mm0    \n\t"

            "punpcklwd     %5, %%mm1    \n\t"

            "punpcklwd     %5, %%mm2    \n\t"

            "punpckhwd     %5, %%mm3    \n\t"

            "punpckhwd     %5, %%mm4    \n\t"

            "punpckhwd     %5, %%mm5    \n\t"

            "psllq         $8, %%mm1    \n\t"

            "psllq        $16, %%mm2    \n\t"

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

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

            "psllq         $8, %%mm4    \n\t"

            "psllq        $16, %%mm5    \n\t"

            "por        %%mm4, %%mm3    \n\t"

            "por        %%mm5, %%mm3    \n\t"

            "movq       %%mm0, %%mm6    \n\t"

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

            "movq         8%1, %%mm0    \n\t"

            "movq         8%1, %%mm1    \n\t"

            "movq         8%1, %%mm2    \n\t"

            "pand          %2, %%mm0    \n\t"

            "pand          %3, %%mm1    \n\t"

            "pand          %4, %%mm2    \n\t"

            "psllq         $3, %%mm0    \n\t"

            "psrlq         $2, %%mm1    \n\t"

            "psrlq         $7, %%mm2    \n\t"

            "movq       %%mm0, %%mm3    \n\t"

            "movq       %%mm1, %%mm4    \n\t"

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

            "punpcklwd     %5, %%mm0    \n\t"

            "punpcklwd     %5, %%mm1    \n\t"

            "punpcklwd     %5, %%mm2    \n\t"

            "punpckhwd     %5, %%mm3    \n\t"

            "punpckhwd     %5, %%mm4    \n\t"

            "punpckhwd     %5, %%mm5    \n\t"

            "psllq         $8, %%mm1    \n\t"

            "psllq        $16, %%mm2    \n\t"

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

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

            "psllq         $8, %%mm4    \n\t"

            "psllq        $16, %%mm5    \n\t"

            "por        %%mm4, %%mm3    \n\t"

            "por        %%mm5, %%mm3    \n\t"

            :"=m"(*d)

            :"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r), "m"(mmx_null)

            :"memory");

        /* borrowed 32 to 24 */

        __asm__ volatile(

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

            "movq       %%mm3, %%mm5    \n\t"

            "movq       %%mm6, %%mm0    \n\t"

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

            "movq       %%mm4, %%mm6    \n\t"

            "movq       %%mm5, %%mm7    \n\t"

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

            "movq       %%mm1, %%mm3    \n\t"

            STORE_BGR24_MMX

            :"=m"(*d)

            :"m"(*s)

            :"memory");

        d += 24;

        s += 8;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

    while (s < end) {

        register uint16_t bgr;

        bgr = *s++;

        *d++ = (bgr&0x1F)<<3;

        *d++ = (bgr&0x3E0)>>2;

        *d++ = (bgr&0x7C00)>>7;

    }

}


int inet_dgram_opts(QemuOpts *opts)

{

    struct addrinfo ai, *peer = NULL, *local = NULL;

    const char *addr;

    const char *port;

    char uaddr[INET6_ADDRSTRLEN+1];

    char uport[33];

    int sock = -1, rc;

    /* lookup peer addr */

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

    ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_DGRAM;

    addr = qemu_opt_get(opts, "host");

    port = qemu_opt_get(opts, "port");

    if (addr == NULL || strlen(addr) == 0) {

        addr = "localhost";

    }

    if (port == NULL || strlen(port) == 0) {

        fprintf(stderr, "inet_dgram: port not specified\n");

        return -1;

    }

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

        ai.ai_family = PF_INET;

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

        ai.ai_family = PF_INET6;

    if (0 != (rc = getaddrinfo(addr, port, &ai, &peer))) {

        fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port,

                gai_strerror(rc));

	return -1;

    }

    if (sockets_debug) {

        fprintf(stderr, "%s: peer (%s:%s)\n", __FUNCTION__, addr, port);

        inet_print_addrinfo(__FUNCTION__, peer);

    }

    /* lookup local addr */

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

    ai.ai_flags = AI_PASSIVE;

    ai.ai_family = peer->ai_family;

    ai.ai_socktype = SOCK_DGRAM;

    addr = qemu_opt_get(opts, "localaddr");

    port = qemu_opt_get(opts, "localport");

    if (addr == NULL || strlen(addr) == 0) {

        addr = NULL;

    }

    if (!port || strlen(port) == 0)

        port = "0";

    if (0 != (rc = getaddrinfo(addr, port, &ai, &local))) {

        fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port,

                gai_strerror(rc));

        return -1;

    }

    if (sockets_debug) {

        fprintf(stderr, "%s: local (%s:%s)\n", __FUNCTION__, addr, port);

        inet_print_addrinfo(__FUNCTION__, local);

    }

    /* create socket */

    sock = socket(peer->ai_family, peer->ai_socktype, peer->ai_protocol);

    if (sock < 0) {

        fprintf(stderr,"%s: socket(%s): %s\n", __FUNCTION__,

                inet_strfamily(peer->ai_family), strerror(errno));

        goto err;

    }

    setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));

    /* bind socket */

    if (getnameinfo((struct sockaddr*)local->ai_addr,local->ai_addrlen,

                    uaddr,INET6_ADDRSTRLEN,uport,32,

                    NI_NUMERICHOST | NI_NUMERICSERV) != 0) {

        fprintf(stderr, "%s: getnameinfo: oops\n", __FUNCTION__);

        goto err;

    }

    if (bind(sock, local->ai_addr, local->ai_addrlen) < 0) {

        fprintf(stderr,"%s: bind(%s,%s,%d): OK\n", __FUNCTION__,

                inet_strfamily(local->ai_family), uaddr, inet_getport(local));

        goto err;

    }

    /* connect to peer */

    if (getnameinfo((struct sockaddr*)peer->ai_addr, peer->ai_addrlen,

                    uaddr, INET6_ADDRSTRLEN, uport, 32,

                    NI_NUMERICHOST | NI_NUMERICSERV) != 0) {

        fprintf(stderr, "%s: getnameinfo: oops\n", __FUNCTION__);

        goto err;

    }

    if (connect(sock,peer->ai_addr,peer->ai_addrlen) < 0) {

        fprintf(stderr, "%s: connect(%s,%s,%s,%s): %s\n", __FUNCTION__,

                inet_strfamily(peer->ai_family),

                peer->ai_canonname, uaddr, uport, strerror(errno));

        goto err;

    }

    freeaddrinfo(local);

    freeaddrinfo(peer);

    return sock;

err:

    if (-1 != sock)

        closesocket(sock);

    if (local)

        freeaddrinfo(local);

    if (peer)

        freeaddrinfo(peer);

    return -1;

}


static int ftp_file_size(FTPContext *s)

{

    char command[CONTROL_BUFFER_SIZE];

    char *res = NULL;

    const int size_codes[] = {213, 0};

    snprintf(command, sizeof(command), "SIZE %s\r\n", s->path);

    if (ftp_send_command(s, command, size_codes, &res)) {

        s->filesize = strtoll(&res[4], NULL, 10);

    } else {

        s->filesize = -1;

        av_free(res);

        return AVERROR(EIO);

    }

    av_free(res);

    return 0;

}


static void tcg_out_qemu_ld(TCGContext *s, const TCGArg *args, bool is_64)

{

    TCGReg datalo, datahi, addrlo, rbase;

    TCGReg addrhi __attribute__((unused));

    TCGMemOpIdx oi;

    TCGMemOp opc, s_bits;

#ifdef CONFIG_SOFTMMU

    int mem_index;

    tcg_insn_unit *label_ptr;

#endif

    datalo = *args++;

    datahi = (TCG_TARGET_REG_BITS == 32 && is_64 ? *args++ : 0);

    addrlo = *args++;

    addrhi = (TCG_TARGET_REG_BITS < TARGET_LONG_BITS ? *args++ : 0);

    oi = *args++;

    opc = get_memop(oi);

    s_bits = opc & MO_SIZE;

#ifdef CONFIG_SOFTMMU

    mem_index = get_mmuidx(oi);

    addrlo = tcg_out_tlb_read(s, s_bits, addrlo, addrhi, mem_index, true);

    /* Load a pointer into the current opcode w/conditional branch-link. */

    label_ptr = s->code_ptr;

    tcg_out_bc_noaddr(s, BC | BI(7, CR_EQ) | BO_COND_FALSE | LK);

    rbase = TCG_REG_R3;

#else  /* !CONFIG_SOFTMMU */

    rbase = GUEST_BASE ? TCG_GUEST_BASE_REG : 0;

    if (TCG_TARGET_REG_BITS > TARGET_LONG_BITS) {

        tcg_out_ext32u(s, TCG_REG_TMP1, addrlo);

        addrlo = TCG_REG_TMP1;

    }

#endif

    if (TCG_TARGET_REG_BITS == 32 && s_bits == MO_64) {

        if (opc & MO_BSWAP) {

            tcg_out32(s, ADDI | TAI(TCG_REG_R0, addrlo, 4));

            tcg_out32(s, LWBRX | TAB(datalo, rbase, addrlo));

            tcg_out32(s, LWBRX | TAB(datahi, rbase, TCG_REG_R0));

        } else if (rbase != 0) {

            tcg_out32(s, ADDI | TAI(TCG_REG_R0, addrlo, 4));

            tcg_out32(s, LWZX | TAB(datahi, rbase, addrlo));

            tcg_out32(s, LWZX | TAB(datalo, rbase, TCG_REG_R0));

        } else if (addrlo == datahi) {

            tcg_out32(s, LWZ | TAI(datalo, addrlo, 4));

            tcg_out32(s, LWZ | TAI(datahi, addrlo, 0));

        } else {

            tcg_out32(s, LWZ | TAI(datahi, addrlo, 0));

            tcg_out32(s, LWZ | TAI(datalo, addrlo, 4));

        }

    } else {

        uint32_t insn = qemu_ldx_opc[opc & (MO_BSWAP | MO_SSIZE)];

        if (!HAVE_ISA_2_06 && insn == LDBRX) {

            tcg_out32(s, ADDI | TAI(TCG_REG_R0, addrlo, 4));

            tcg_out32(s, LWBRX | TAB(datalo, rbase, addrlo));

            tcg_out32(s, LWBRX | TAB(TCG_REG_R0, rbase, TCG_REG_R0));

            tcg_out_rld(s, RLDIMI, datalo, TCG_REG_R0, 32, 0);

        } else if (insn) {

            tcg_out32(s, insn | TAB(datalo, rbase, addrlo));

        } else {

            insn = qemu_ldx_opc[opc & (MO_SIZE | MO_BSWAP)];

            tcg_out32(s, insn | TAB(datalo, rbase, addrlo));

            insn = qemu_exts_opc[s_bits];

            tcg_out32(s, insn | RA(datalo) | RS(datalo));

        }

    }

#ifdef CONFIG_SOFTMMU

    add_qemu_ldst_label(s, true, oi, datalo, datahi, addrlo, addrhi,

                        s->code_ptr, label_ptr);

#endif

}


int ff_h264_decode_ref_pic_marking(const H264Context *h, H264SliceContext *sl,

                                   GetBitContext *gb)

{

    int i;

    MMCO *mmco = sl->mmco;

    int nb_mmco = 0;

    if (h->nal_unit_type == NAL_IDR_SLICE) { // FIXME fields

        skip_bits1(gb); // broken_link

        if (get_bits1(gb)) {

            mmco[0].opcode   = MMCO_LONG;

            mmco[0].long_arg = 0;

            nb_mmco          = 1;

        }

        sl->explicit_ref_marking = 1;

    } else {

        sl->explicit_ref_marking = get_bits1(gb);

        if (sl->explicit_ref_marking) {

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

                MMCOOpcode opcode = get_ue_golomb_31(gb);

                mmco[i].opcode = opcode;

                if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG) {

                    mmco[i].short_pic_num =

                        (sl->curr_pic_num - get_ue_golomb(gb) - 1) &

                            (sl->max_pic_num - 1);

#if 0

                    if (mmco[i].short_pic_num >= h->short_ref_count ||

                        !h->short_ref[mmco[i].short_pic_num]) {

                        av_log(s->avctx, AV_LOG_ERROR,

                               "illegal short ref in memory management control "

                               "operation %d\n", mmco);

                        return -1;

                    }

#endif

                }

                if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||

                    opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG) {

                    unsigned int long_arg = get_ue_golomb_31(gb);

                    if (long_arg >= 32 ||

                        (long_arg >= 16 && !(opcode == MMCO_SET_MAX_LONG &&

                                             long_arg == 16) &&

                         !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE(h)))) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "illegal long ref in memory management control "

                               "operation %d\n", opcode);

                        return -1;

                    }

                    mmco[i].long_arg = long_arg;

                }

                if (opcode > (unsigned) MMCO_LONG) {

                    av_log(h->avctx, AV_LOG_ERROR,

                           "illegal memory management control operation %d\n",

                           opcode);

                    return -1;

                }

                if (opcode == MMCO_END)

                    break;

            }

            nb_mmco = i;

        }

    }

    sl->nb_mmco = nb_mmco;

    return 0;

}


 void cpu_sh4_invalidate_tlb(CPUSH4State *s)

{

    int i;

    /* UTLB */

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

        tlb_t * entry = &s->utlb[i];

        entry->v = 0;

    }

    /* ITLB */

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

        tlb_t * entry = &s->utlb[i];

        entry->v = 0;

    }

    tlb_flush(s, 1);

}


uint16_t net_checksum_finish(uint32_t sum)

{

    while (sum>>16)

	sum = (sum & 0xFFFF)+(sum >> 16);

    return ~sum;

}


static void pci_init_mask_bridge(PCIDevice *d)

{

    /* PCI_PRIMARY_BUS, PCI_SECONDARY_BUS, PCI_SUBORDINATE_BUS and

       PCI_SEC_LETENCY_TIMER */

    memset(d->wmask + PCI_PRIMARY_BUS, 0xff, 4);

    /* base and limit */

    d->wmask[PCI_IO_BASE] = PCI_IO_RANGE_MASK & 0xff;

    d->wmask[PCI_IO_LIMIT] = PCI_IO_RANGE_MASK & 0xff;

    pci_set_word(d->wmask + PCI_MEMORY_BASE,

                 PCI_MEMORY_RANGE_MASK & 0xffff);

    pci_set_word(d->wmask + PCI_MEMORY_LIMIT,

                 PCI_MEMORY_RANGE_MASK & 0xffff);

    pci_set_word(d->wmask + PCI_PREF_MEMORY_BASE,

                 PCI_PREF_RANGE_MASK & 0xffff);

    pci_set_word(d->wmask + PCI_PREF_MEMORY_LIMIT,

                 PCI_PREF_RANGE_MASK & 0xffff);

    /* PCI_PREF_BASE_UPPER32 and PCI_PREF_LIMIT_UPPER32 */

    memset(d->wmask + PCI_PREF_BASE_UPPER32, 0xff, 8);

    /* Supported memory and i/o types */

    d->config[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_16;

    d->config[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_16;

    pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_BASE,

                               PCI_PREF_RANGE_TYPE_64);

    pci_word_test_and_set_mask(d->config + PCI_PREF_MEMORY_LIMIT,

                               PCI_PREF_RANGE_TYPE_64);

/* TODO: add this define to pci_regs.h in linux and then in qemu. */

#define  PCI_BRIDGE_CTL_VGA_16BIT	0x10	/* VGA 16-bit decode */

#define  PCI_BRIDGE_CTL_DISCARD		0x100	/* Primary discard timer */

#define  PCI_BRIDGE_CTL_SEC_DISCARD	0x200	/* Secondary discard timer */

#define  PCI_BRIDGE_CTL_DISCARD_STATUS	0x400	/* Discard timer status */

#define  PCI_BRIDGE_CTL_DISCARD_SERR	0x800	/* Discard timer SERR# enable */

/*

 * TODO: Bridges default to 10-bit VGA decoding but we currently only

 * implement 16-bit decoding (no alias support).

 */

    pci_set_word(d->wmask + PCI_BRIDGE_CONTROL,

                 PCI_BRIDGE_CTL_PARITY |

                 PCI_BRIDGE_CTL_SERR |

                 PCI_BRIDGE_CTL_ISA |

                 PCI_BRIDGE_CTL_VGA |

                 PCI_BRIDGE_CTL_VGA_16BIT |

                 PCI_BRIDGE_CTL_MASTER_ABORT |

                 PCI_BRIDGE_CTL_BUS_RESET |

                 PCI_BRIDGE_CTL_FAST_BACK |

                 PCI_BRIDGE_CTL_DISCARD |

                 PCI_BRIDGE_CTL_SEC_DISCARD |

                 PCI_BRIDGE_CTL_DISCARD_SERR);

    /* Below does not do anything as we never set this bit, put here for

     * completeness. */

    pci_set_word(d->w1cmask + PCI_BRIDGE_CONTROL,

                 PCI_BRIDGE_CTL_DISCARD_STATUS);

    d->cmask[PCI_IO_BASE] |= PCI_IO_RANGE_TYPE_MASK;

    d->cmask[PCI_IO_LIMIT] |= PCI_IO_RANGE_TYPE_MASK;

    pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_BASE,

                               PCI_PREF_RANGE_TYPE_MASK);

    pci_word_test_and_set_mask(d->cmask + PCI_PREF_MEMORY_LIMIT,

                               PCI_PREF_RANGE_TYPE_MASK);

}


static TranslationBlock *tb_alloc(target_ulong pc)

{

    TranslationBlock *tb;

    TBContext *ctx;

    assert_tb_locked();

    tb = tcg_tb_alloc(&tcg_ctx);

    if (unlikely(tb == NULL)) {

        return NULL;

    }

    ctx = &tcg_ctx.tb_ctx;

    if (unlikely(ctx->nb_tbs == ctx->tbs_size)) {

        ctx->tbs_size *= 2;

        ctx->tbs = g_renew(TranslationBlock *, ctx->tbs, ctx->tbs_size);

    }

    ctx->tbs[ctx->nb_tbs++] = tb;

    tb->pc = pc;

    tb->cflags = 0;

    tb->invalid = false;

    return tb;

}


static void gpollfds_from_select(void)

{

    int fd;

    for (fd = 0; fd <= nfds; fd++) {

        int events = 0;

        if (FD_ISSET(fd, &rfds)) {

            events |= G_IO_IN | G_IO_HUP | G_IO_ERR;

        }

        if (FD_ISSET(fd, &wfds)) {

            events |= G_IO_OUT | G_IO_ERR;

        }

        if (FD_ISSET(fd, &xfds)) {

            events |= G_IO_PRI;

        }

        if (events) {

            GPollFD pfd = {

                .fd = fd,

                .events = events,

            };

            g_array_append_val(gpollfds, pfd);

        }

    }

}


static int decode_frame(AVCodecContext *avctx,

                        void *data, int *got_frame, AVPacket *avpkt)

{

    TiffContext *const s = avctx->priv_data;

    AVFrame *const p = data;

    ThreadFrame frame = { .f = data };

    unsigned off;

    int le, ret, plane, planes;

    int i, j, entries, stride;

    unsigned soff, ssize;

    uint8_t *dst;

    GetByteContext stripsizes;

    GetByteContext stripdata;

    bytestream2_init(&s->gb, avpkt->data, avpkt->size);

    // parse image header

    if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {

        av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");

        return ret;

    } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {

        av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");

        return AVERROR_INVALIDDATA;

    }

    s->le          = le;

    // TIFF_BPP is not a required tag and defaults to 1

    s->bppcount    = s->bpp = 1;

    s->photometric = TIFF_PHOTOMETRIC_NONE;

    s->compr       = TIFF_RAW;

    s->fill_order  = 0;

    free_geotags(s);

    // Reset these offsets so we can tell if they were set this frame

    s->stripsizesoff = s->strippos = 0;

    /* parse image file directory */

    bytestream2_seek(&s->gb, off, SEEK_SET);

    entries = ff_tget_short(&s->gb, le);

    if (bytestream2_get_bytes_left(&s->gb) < entries * 12)

        return AVERROR_INVALIDDATA;

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

        if ((ret = tiff_decode_tag(s, p)) < 0)

            return ret;

    }

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

        const char *keyname = get_geokey_name(s->geotags[i].key);

        if (!keyname) {

            av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);

            continue;

        }

        if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {

            av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);

            continue;

        }

        ret = av_dict_set(avpriv_frame_get_metadatap(p), keyname, s->geotags[i].val, 0);

        if (ret<0) {

            av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);

            return ret;

        }

    }

    if (!s->strippos && !s->stripoff) {

        av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");

        return AVERROR_INVALIDDATA;

    }

    /* now we have the data and may start decoding */

    if ((ret = init_image(s, &frame)) < 0)

        return ret;

    if (s->strips == 1 && !s->stripsize) {

        av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");

        s->stripsize = avpkt->size - s->stripoff;

    }

    if (s->stripsizesoff) {

        if (s->stripsizesoff >= (unsigned)avpkt->size)

            return AVERROR_INVALIDDATA;

        bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,

                         avpkt->size - s->stripsizesoff);

    }

    if (s->strippos) {

        if (s->strippos >= (unsigned)avpkt->size)

            return AVERROR_INVALIDDATA;

        bytestream2_init(&stripdata, avpkt->data + s->strippos,

                         avpkt->size - s->strippos);

    }

    if (s->rps <= 0) {

        av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps);

        return AVERROR_INVALIDDATA;

    }

    planes = s->planar ? s->bppcount : 1;

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

        stride = p->linesize[plane];

        dst = p->data[plane];

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

            if (s->stripsizesoff)

                ssize = ff_tget(&stripsizes, s->sstype, le);

            else

                ssize = s->stripsize;

            if (s->strippos)

                soff = ff_tget(&stripdata, s->sot, le);

            else

                soff = s->stripoff;

            if (soff > avpkt->size || ssize > avpkt->size - soff) {

                av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");

                return AVERROR_INVALIDDATA;

            }

            if ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,

                                         FFMIN(s->rps, s->height - i))) < 0) {

                if (avctx->err_recognition & AV_EF_EXPLODE)

                    return ret;

                break;

            }

            dst += s->rps * stride;

        }

        if (s->predictor == 2) {

            if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {

                av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");

                return AVERROR_PATCHWELCOME;

            }

            dst   = p->data[plane];

            soff  = s->bpp >> 3;

            if (s->planar)

                soff  = FFMAX(soff / s->bppcount, 1);

            ssize = s->width * soff;

            if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_RGBA64LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_GRAY16LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_YA16LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_GBRP16LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16LE) {

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

                    for (j = soff; j < ssize; j += 2)

                        AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));

                    dst += stride;

                }

            } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_RGBA64BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_YA16BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_GBRP16BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16BE) {

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

                    for (j = soff; j < ssize; j += 2)

                        AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));

                    dst += stride;

                }

            } else {

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

                    for (j = soff; j < ssize; j++)

                        dst[j] += dst[j - soff];

                    dst += stride;

                }

            }

        }

        if (s->photometric == TIFF_PHOTOMETRIC_WHITE_IS_ZERO) {

            dst = p->data[plane];

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

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

                    dst[j] = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];

                dst += stride;

            }

        }

    }

    if (s->planar && s->bppcount > 2) {

        FFSWAP(uint8_t*, p->data[0],     p->data[2]);

        FFSWAP(int,      p->linesize[0], p->linesize[2]);

        FFSWAP(uint8_t*, p->data[0],     p->data[1]);

        FFSWAP(int,      p->linesize[0], p->linesize[1]);

    }

    *got_frame = 1;

    return avpkt->size;

}


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,

                                              int *got_picture_ptr,

                                              AVPacket *avpkt)

{

    int ret;

    *got_picture_ptr = 0;

    if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))

        return -1;

    avctx->pkt = avpkt;

    apply_param_change(avctx, avpkt);

    avcodec_get_frame_defaults(picture);

    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {

        if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)

            ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,

                                         avpkt);

        else {

            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,

                                       avpkt);

            picture->pkt_dts             = avpkt->dts;

            picture->sample_aspect_ratio = avctx->sample_aspect_ratio;

            picture->width               = avctx->width;

            picture->height              = avctx->height;

            picture->format              = avctx->pix_fmt;

        }

        emms_c(); //needed to avoid an emms_c() call before every return;

        if (*got_picture_ptr)

            avctx->frame_number++;

    } else

        ret = 0;

    /* many decoders assign whole AVFrames, thus overwriting extended_data;

     * make sure it's set correctly */

    picture->extended_data = picture->data;

    return ret;

}


static int megasas_pd_get_info_submit(SCSIDevice *sdev, int lun,

                                      MegasasCmd *cmd)

{

    struct mfi_pd_info *info = cmd->iov_buf;

    size_t dcmd_size = sizeof(struct mfi_pd_info);

    uint64_t pd_size;

    uint16_t pd_id = ((sdev->id & 0xFF) << 8) | (lun & 0xFF);

    uint8_t cmdbuf[6];

    SCSIRequest *req;

    size_t len, resid;

    if (!cmd->iov_buf) {

        cmd->iov_buf = g_malloc0(dcmd_size);

        info = cmd->iov_buf;

        info->inquiry_data[0] = 0x7f; /* Force PQual 0x3, PType 0x1f */

        info->vpd_page83[0] = 0x7f;

        megasas_setup_inquiry(cmdbuf, 0, sizeof(info->inquiry_data));

        req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);

        if (!req) {

            trace_megasas_dcmd_req_alloc_failed(cmd->index,

                                                "PD get info std inquiry");

            g_free(cmd->iov_buf);

            cmd->iov_buf = NULL;

            return MFI_STAT_FLASH_ALLOC_FAIL;

        }

        trace_megasas_dcmd_internal_submit(cmd->index,

                                           "PD get info std inquiry", lun);

        len = scsi_req_enqueue(req);

        if (len > 0) {

            cmd->iov_size = len;

            scsi_req_continue(req);

        }

        return MFI_STAT_INVALID_STATUS;

    } else if (info->inquiry_data[0] != 0x7f && info->vpd_page83[0] == 0x7f) {

        megasas_setup_inquiry(cmdbuf, 0x83, sizeof(info->vpd_page83));

        req = scsi_req_new(sdev, cmd->index, lun, cmdbuf, cmd);

        if (!req) {

            trace_megasas_dcmd_req_alloc_failed(cmd->index,

                                                "PD get info vpd inquiry");

            return MFI_STAT_FLASH_ALLOC_FAIL;

        }

        trace_megasas_dcmd_internal_submit(cmd->index,

                                           "PD get info vpd inquiry", lun);

        len = scsi_req_enqueue(req);

        if (len > 0) {

            cmd->iov_size = len;

            scsi_req_continue(req);

        }

        return MFI_STAT_INVALID_STATUS;

    }

    /* Finished, set FW state */

    if ((info->inquiry_data[0] >> 5) == 0) {

        if (megasas_is_jbod(cmd->state)) {

            info->fw_state = cpu_to_le16(MFI_PD_STATE_SYSTEM);

        } else {

            info->fw_state = cpu_to_le16(MFI_PD_STATE_ONLINE);

        }

    } else {

        info->fw_state = cpu_to_le16(MFI_PD_STATE_OFFLINE);

    }

    info->ref.v.device_id = cpu_to_le16(pd_id);

    info->state.ddf.pd_type = cpu_to_le16(MFI_PD_DDF_TYPE_IN_VD|

                                          MFI_PD_DDF_TYPE_INTF_SAS);

    blk_get_geometry(sdev->conf.blk, &pd_size);

    info->raw_size = cpu_to_le64(pd_size);

    info->non_coerced_size = cpu_to_le64(pd_size);

    info->coerced_size = cpu_to_le64(pd_size);

    info->encl_device_id = 0xFFFF;

    info->slot_number = (sdev->id & 0xFF);

    info->path_info.count = 1;

    info->path_info.sas_addr[0] =

        cpu_to_le64(megasas_get_sata_addr(pd_id));

    info->connected_port_bitmap = 0x1;

    info->device_speed = 1;

    info->link_speed = 1;

    resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg);

    g_free(cmd->iov_buf);

    cmd->iov_size = dcmd_size - resid;

    cmd->iov_buf = NULL;

    return MFI_STAT_OK;

}


static void gen_isel(DisasContext *ctx)

{

    int l1, l2;

    uint32_t bi = rC(ctx->opcode);

    uint32_t mask;

    TCGv_i32 t0;

    l1 = gen_new_label();

    l2 = gen_new_label();

    mask = 0x08 >> (bi & 0x03);

    t0 = tcg_temp_new_i32();

    tcg_gen_andi_i32(t0, cpu_crf[bi >> 2], mask);

    tcg_gen_brcondi_i32(TCG_COND_EQ, t0, 0, l1);

    if (rA(ctx->opcode) == 0)

        tcg_gen_movi_tl(cpu_gpr[rD(ctx->opcode)], 0);

    else

        tcg_gen_mov_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_mov_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rB(ctx->opcode)]);

    gen_set_label(l2);

    tcg_temp_free_i32(t0);

}


static void stream_process_mem2s(struct Stream *s,

                                 StreamSlave *tx_dev)

{

    uint32_t prev_d;

    unsigned char txbuf[16 * 1024];

    unsigned int txlen;

    uint32_t app[6];

    if (!stream_running(s) || stream_idle(s)) {

        return;

    }

    while (1) {

        stream_desc_load(s, s->regs[R_CURDESC]);

        if (s->desc.status & SDESC_STATUS_COMPLETE) {

            s->regs[R_DMASR] |= DMASR_HALTED;

            break;

        }

        if (stream_desc_sof(&s->desc)) {

            s->pos = 0;

            memcpy(app, s->desc.app, sizeof app);

        }

        txlen = s->desc.control & SDESC_CTRL_LEN_MASK;

        if ((txlen + s->pos) > sizeof txbuf) {

            hw_error("%s: too small internal txbuf! %d\n", __func__,

                     txlen + s->pos);

        }

        cpu_physical_memory_read(s->desc.buffer_address,

                                 txbuf + s->pos, txlen);

        s->pos += txlen;

        if (stream_desc_eof(&s->desc)) {

            stream_push(tx_dev, txbuf, s->pos, app);

            s->pos = 0;

            stream_complete(s);

        }

        /* Update the descriptor.  */

        s->desc.status = txlen | SDESC_STATUS_COMPLETE;

        stream_desc_store(s, s->regs[R_CURDESC]);

        /* Advance.  */

        prev_d = s->regs[R_CURDESC];

        s->regs[R_CURDESC] = s->desc.nxtdesc;

        if (prev_d == s->regs[R_TAILDESC]) {

            s->regs[R_DMASR] |= DMASR_IDLE;

            break;

        }

    }

}


static int adpcm_decode_init(AVCodecContext * avctx)

{

    ADPCMContext *c = avctx->priv_data;

    if(avctx->channels > 2U){

        return -1;

    }

    c->channel = 0;

    c->status[0].predictor = c->status[1].predictor = 0;

    c->status[0].step_index = c->status[1].step_index = 0;

    c->status[0].step = c->status[1].step = 0;

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_CT:

        c->status[0].step = c->status[1].step = 511;

        break;

    case CODEC_ID_ADPCM_IMA_WS:

        if (avctx->extradata && avctx->extradata_size == 2 * 4) {

            c->status[0].predictor = AV_RL32(avctx->extradata);

            c->status[1].predictor = AV_RL32(avctx->extradata + 4);

        }

        break;

    default:

        break;

    }

    return 0;

}


static inline void bt_hci_event_complete_read_local_name(struct bt_hci_s *hci)

{

    read_local_name_rp params;

    params.status = HCI_SUCCESS;

    memset(params.name, 0, sizeof(params.name));

    if (hci->device.lmp_name)

        strncpy(params.name, hci->device.lmp_name, sizeof(params.name));

    bt_hci_event_complete(hci, &params, READ_LOCAL_NAME_RP_SIZE);

}


static bool vnc_should_update(VncState *vs)

{

    switch (vs->update) {

    case VNC_STATE_UPDATE_NONE:

        break;

    case VNC_STATE_UPDATE_INCREMENTAL:

        /* Only allow incremental updates if the output buffer

         * is empty, or if audio capture is enabled.

         */

        if (!vs->output.offset || vs->audio_cap) {

            return true;

        }

        break;

    case VNC_STATE_UPDATE_FORCE:

        return true;

    }

    return false;

}


static void test_qemu_strtoll_whitespace(void)

{

    const char *str = "  \t  ";

    char f = 'X';

    const char *endptr = &f;

    int64_t res = 999;

    int err;

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

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0);

    g_assert(endptr == str);

}


static void test_migrate(void)

{

    char *uri = g_strdup_printf("unix:%s/migsocket", tmpfs);

    QTestState *global = global_qtest, *from, *to;

    unsigned char dest_byte_a, dest_byte_b, dest_byte_c, dest_byte_d;

    gchar *cmd;

    QDict *rsp;

    char *bootpath = g_strdup_printf("%s/bootsect", tmpfs);

    FILE *bootfile = fopen(bootpath, "wb");

    got_stop = false;

    g_assert_cmpint(fwrite(bootsect, 512, 1, bootfile), ==, 1);

    fclose(bootfile);

    cmd = g_strdup_printf("-machine accel=kvm:tcg -m 150M"

                          " -name pcsource,debug-threads=on"

                          " -serial file:%s/src_serial"

                          " -drive file=%s,format=raw",

                          tmpfs, bootpath);

    from = qtest_start(cmd);

    g_free(cmd);

    cmd = g_strdup_printf("-machine accel=kvm:tcg -m 150M"

                          " -name pcdest,debug-threads=on"

                          " -serial file:%s/dest_serial"

                          " -drive file=%s,format=raw"

                          " -incoming %s",

                          tmpfs, bootpath, uri);

    to = qtest_init(cmd);

    g_free(cmd);

    global_qtest = from;

    rsp = qmp("{ 'execute': 'migrate-set-capabilities',"

                  "'arguments': { "

                      "'capabilities': [ {"

                          "'capability': 'postcopy-ram',"

                          "'state': true } ] } }");

    g_assert(qdict_haskey(rsp, "return"));

    QDECREF(rsp);

    global_qtest = to;

    rsp = qmp("{ 'execute': 'migrate-set-capabilities',"

                  "'arguments': { "

                      "'capabilities': [ {"

                          "'capability': 'postcopy-ram',"

                          "'state': true } ] } }");

    g_assert(qdict_haskey(rsp, "return"));

    QDECREF(rsp);

    /* We want to pick a speed slow enough that the test completes

     * quickly, but that it doesn't complete precopy even on a slow

     * machine, so also set the downtime.

     */

    global_qtest = from;

    rsp = qmp("{ 'execute': 'migrate_set_speed',"

              "'arguments': { 'value': 100000000 } }");

    g_assert(qdict_haskey(rsp, "return"));

    QDECREF(rsp);

    /* 1ms downtime - it should never finish precopy */

    rsp = qmp("{ 'execute': 'migrate_set_downtime',"

              "'arguments': { 'value': 0.001 } }");

    g_assert(qdict_haskey(rsp, "return"));

    QDECREF(rsp);

    /* Wait for the first serial output from the source */

    wait_for_serial("src_serial");

    cmd = g_strdup_printf("{ 'execute': 'migrate',"

                          "'arguments': { 'uri': '%s' } }",

                          uri);

    rsp = qmp(cmd);

    g_free(cmd);

    g_assert(qdict_haskey(rsp, "return"));

    QDECREF(rsp);

    wait_for_migration_pass();

    rsp = return_or_event(qmp("{ 'execute': 'migrate-start-postcopy' }"));

    g_assert(qdict_haskey(rsp, "return"));

    QDECREF(rsp);

    if (!got_stop) {

        qmp_eventwait("STOP");

    }

    global_qtest = to;

    qmp_eventwait("RESUME");

    wait_for_serial("dest_serial");

    global_qtest = from;

    wait_for_migration_complete();

    qtest_quit(from);

    global_qtest = to;

    qtest_memread(to, start_address, &dest_byte_a, 1);

    /* Destination still running, wait for a byte to change */

    do {

        qtest_memread(to, start_address, &dest_byte_b, 1);

        usleep(10 * 1000);

    } while (dest_byte_a == dest_byte_b);

    qmp("{ 'execute' : 'stop'}");

    /* With it stopped, check nothing changes */

    qtest_memread(to, start_address, &dest_byte_c, 1);

    sleep(1);

    qtest_memread(to, start_address, &dest_byte_d, 1);

    g_assert_cmpint(dest_byte_c, ==, dest_byte_d);

    check_guests_ram();

    qtest_quit(to);

    g_free(uri);

    global_qtest = global;

    cleanup("bootsect");

    cleanup("migsocket");

    cleanup("src_serial");

    cleanup("dest_serial");

}


static uint8_t net_tx_pkt_get_gso_type(struct NetTxPkt *pkt,

                                          bool tso_enable)

{

    uint8_t rc = VIRTIO_NET_HDR_GSO_NONE;

    uint16_t l3_proto;

    l3_proto = eth_get_l3_proto(pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base,

        pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len);

    if (!tso_enable) {

        goto func_exit;

    }

    rc = eth_get_gso_type(l3_proto, pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base,

                          pkt->l4proto);

func_exit:

    return rc;

}


static int scsi_req_length(SCSIRequest *req, uint8_t *cmd)

{

    switch (cmd[0] >> 5) {

    case 0:

        req->cmd.xfer = cmd[4];

        req->cmd.len = 6;

        /* length 0 means 256 blocks */

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

            req->cmd.xfer = 256;

        break;

    case 1:

    case 2:

        req->cmd.xfer = cmd[8] | (cmd[7] << 8);

        req->cmd.len = 10;

        break;

    case 4:

        req->cmd.xfer = cmd[13] | (cmd[12] << 8) | (cmd[11] << 16) | (cmd[10] << 24);

        req->cmd.len = 16;

        break;

    case 5:

        req->cmd.xfer = cmd[9] | (cmd[8] << 8) | (cmd[7] << 16) | (cmd[6] << 24);

        req->cmd.len = 12;

        break;

    default:

        trace_scsi_req_parse_bad(req->dev->id, req->lun, req->tag, cmd[0]);

        return -1;

    }

    switch(cmd[0]) {

    case TEST_UNIT_READY:

    case START_STOP:

    case SEEK_6:

    case WRITE_FILEMARKS:

    case SPACE:

    case RESERVE:

    case RELEASE:

    case ERASE:

    case ALLOW_MEDIUM_REMOVAL:

    case VERIFY:

    case SEEK_10:

    case SYNCHRONIZE_CACHE:

    case LOCK_UNLOCK_CACHE:

    case LOAD_UNLOAD:

    case SET_CD_SPEED:

    case SET_LIMITS:

    case WRITE_LONG:

    case MOVE_MEDIUM:

    case UPDATE_BLOCK:

        req->cmd.xfer = 0;

        break;

    case MODE_SENSE:

        break;

    case WRITE_SAME:

        req->cmd.xfer = 1;

        break;

    case READ_CAPACITY:

        req->cmd.xfer = 8;

        break;

    case READ_BLOCK_LIMITS:

        req->cmd.xfer = 6;

        break;

    case READ_POSITION:

        req->cmd.xfer = 20;

        break;

    case SEND_VOLUME_TAG:

        req->cmd.xfer *= 40;

        break;

    case MEDIUM_SCAN:

        req->cmd.xfer *= 8;

        break;

    case WRITE_10:

    case WRITE_VERIFY:

    case WRITE_6:

    case WRITE_12:

    case WRITE_VERIFY_12:

    case WRITE_16:

    case WRITE_VERIFY_16:

        req->cmd.xfer *= req->dev->blocksize;

        break;

    case READ_10:

    case READ_6:

    case READ_REVERSE:

    case RECOVER_BUFFERED_DATA:

    case READ_12:

    case READ_16:

        req->cmd.xfer *= req->dev->blocksize;

        break;

    case INQUIRY:

        req->cmd.xfer = cmd[4] | (cmd[3] << 8);

        break;

    case MAINTENANCE_OUT:

    case MAINTENANCE_IN:

        if (req->dev->type == TYPE_ROM) {

            /* GPCMD_REPORT_KEY and GPCMD_SEND_KEY from multi media commands */

            req->cmd.xfer = cmd[9] | (cmd[8] << 8);

        }

        break;

    }

    return 0;

}


int ff_schro_queue_push_back(FFSchroQueue *queue, void *p_data)

{

    FFSchroQueueElement *p_new = av_mallocz(sizeof(FFSchroQueueElement));

    if (!p_new)

        return -1;

    p_new->data = p_data;

    if (!queue->p_head)

        queue->p_head = p_new;

    else

        queue->p_tail->next = p_new;

    queue->p_tail = p_new;

    ++queue->size;

    return 0;

}


int kvmppc_reset_htab(int shift_hint)

{

    uint32_t shift = shift_hint;

    if (!kvm_enabled()) {

        /* Full emulation, tell caller to allocate htab itself */

        return 0;

    }

    if (kvm_check_extension(kvm_state, KVM_CAP_PPC_ALLOC_HTAB)) {

        int ret;

        ret = kvm_vm_ioctl(kvm_state, KVM_PPC_ALLOCATE_HTAB, &shift);

        if (ret == -ENOTTY) {

            /* At least some versions of PR KVM advertise the

             * capability, but don't implement the ioctl().  Oops.

             * Return 0 so that we allocate the htab in qemu, as is

             * correct for PR. */

            return 0;

        } else if (ret < 0) {

            return ret;

        }

        return shift;

    }

    /* We have a kernel that predates the htab reset calls.  For PR

     * KVM, we need to allocate the htab ourselves, for an HV KVM of

     * this era, it has allocated a 16MB fixed size hash table already. */

    if (kvmppc_is_pr(kvm_state)) {

        /* PR - tell caller to allocate htab */

        return 0;

    } else {

        /* HV - assume 16MB kernel allocated htab */

        return 24;

    }

}


static int ptx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                            AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    PTXContext * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p = &s->picture;

    unsigned int offset, w, h, y, stride, bytes_per_pixel;

    uint8_t *ptr;

    offset          = AV_RL16(buf);

    w               = AV_RL16(buf+8);

    h               = AV_RL16(buf+10);

    bytes_per_pixel = AV_RL16(buf+12) >> 3;

    if (bytes_per_pixel != 2) {

        av_log_ask_for_sample(avctx, "Image format is not RGB15.\n");

        return -1;

    }

    avctx->pix_fmt = PIX_FMT_RGB555;

    if (buf_end - buf < offset)

    if (offset != 0x2c)

        av_log_ask_for_sample(avctx, "offset != 0x2c\n");

    buf += offset;

    if (p->data[0])

        avctx->release_buffer(avctx, p);

    if (av_image_check_size(w, h, 0, avctx))

        return -1;

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

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

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

        return -1;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    ptr    = p->data[0];

    stride = p->linesize[0];

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

        if (buf_end - buf < w * bytes_per_pixel)

            break;

#if HAVE_BIGENDIAN

        unsigned int x;

        for (x=0; x<w*bytes_per_pixel; x+=bytes_per_pixel)

            AV_WN16(ptr+x, AV_RL16(buf+x));

#else

        memcpy(ptr, buf, w*bytes_per_pixel);

#endif

        ptr += stride;

        buf += w*bytes_per_pixel;

    }

    *picture = s->picture;

    *data_size = sizeof(AVPicture);

    return offset + w*h*bytes_per_pixel;

}


static void vpc_close(BlockDriverState *bs)

{

    BDRVVPCState *s = bs->opaque;

    g_free(s->pagetable);

#ifdef CACHE

    g_free(s->pageentry_u8);

#endif

    migrate_del_blocker(s->migration_blocker);

    error_free(s->migration_blocker);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    CPUClass *cc = CPU_CLASS(oc);

    dc->fw_name = "PowerPC,POWER9";

    dc->desc = "POWER9";

    dc->props = powerpc_servercpu_properties;

    pcc->pvr_match = ppc_pvr_match_power9;

    pcc->pcr_mask = PCR_COMPAT_2_05 | PCR_COMPAT_2_06 | PCR_COMPAT_2_07;

    pcc->pcr_supported = PCR_COMPAT_3_00 | PCR_COMPAT_2_07 | PCR_COMPAT_2_06 |

                         PCR_COMPAT_2_05;

    pcc->init_proc = init_proc_POWER9;

    pcc->check_pow = check_pow_nocheck;

    cc->has_work = cpu_has_work_POWER9;

    pcc->insns_flags = PPC_INSNS_BASE | PPC_ISEL | PPC_STRING | PPC_MFTB |

                       PPC_FLOAT | PPC_FLOAT_FSEL | PPC_FLOAT_FRES |

                       PPC_FLOAT_FSQRT | PPC_FLOAT_FRSQRTE |

                       PPC_FLOAT_FRSQRTES |

                       PPC_FLOAT_STFIWX |

                       PPC_FLOAT_EXT |

                       PPC_CACHE | PPC_CACHE_ICBI | PPC_CACHE_DCBZ |

                       PPC_MEM_SYNC | PPC_MEM_EIEIO |

                       PPC_MEM_TLBIE | PPC_MEM_TLBSYNC |

                       PPC_64B | PPC_64BX | PPC_ALTIVEC |

                       PPC_SEGMENT_64B | PPC_SLBI |

                       PPC_POPCNTB | PPC_POPCNTWD |

                       PPC_CILDST;

    pcc->insns_flags2 = PPC2_VSX | PPC2_VSX207 | PPC2_DFP | PPC2_DBRX |

                        PPC2_PERM_ISA206 | PPC2_DIVE_ISA206 |

                        PPC2_ATOMIC_ISA206 | PPC2_FP_CVT_ISA206 |

                        PPC2_FP_TST_ISA206 | PPC2_BCTAR_ISA207 |

                        PPC2_LSQ_ISA207 | PPC2_ALTIVEC_207 |

                        PPC2_ISA205 | PPC2_ISA207S | PPC2_FP_CVT_S64 |

                        PPC2_TM | PPC2_PM_ISA206 | PPC2_ISA300;

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

                    (1ull << MSR_TM) |

                    (1ull << MSR_VR) |

                    (1ull << MSR_VSX) |

                    (1ull << MSR_EE) |

                    (1ull << MSR_PR) |

                    (1ull << MSR_FP) |

                    (1ull << MSR_ME) |

                    (1ull << MSR_FE0) |

                    (1ull << MSR_SE) |

                    (1ull << MSR_DE) |

                    (1ull << MSR_FE1) |

                    (1ull << MSR_IR) |

                    (1ull << MSR_DR) |

                    (1ull << MSR_PMM) |

                    (1ull << MSR_RI) |

                    (1ull << MSR_LE);

    pcc->mmu_model = POWERPC_MMU_3_00;

#if defined(CONFIG_SOFTMMU)

    pcc->handle_mmu_fault = ppc64_v3_handle_mmu_fault;

    /* segment page size remain the same */

    pcc->sps = &POWER7_POWER8_sps;

    pcc->radix_page_info = &POWER9_radix_page_info;

#endif

    pcc->excp_model = POWERPC_EXCP_POWER8;

    pcc->bus_model = PPC_FLAGS_INPUT_POWER7;

    pcc->bfd_mach = bfd_mach_ppc64;

    pcc->flags = POWERPC_FLAG_VRE | POWERPC_FLAG_SE |

                 POWERPC_FLAG_BE | POWERPC_FLAG_PMM |

                 POWERPC_FLAG_BUS_CLK | POWERPC_FLAG_CFAR |

                 POWERPC_FLAG_VSX | POWERPC_FLAG_TM;

    pcc->l1_dcache_size = 0x8000;

    pcc->l1_icache_size = 0x8000;

    pcc->interrupts_big_endian = ppc_cpu_interrupts_big_endian_lpcr;

}


static int mxf_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    MXFContext *mxf = s->priv_data;

    KLVPacket klv;

    int64_t essence_offset = 0;

    mxf->last_forward_tell = INT64_MAX;

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

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

        return AVERROR_INVALIDDATA;

    }

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

    mxf->fc = s;

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

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

        const MXFMetadataReadTableEntry *metadata;

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

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

            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)

                break;

            else

                continue;

        }

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

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

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

            IS_KLV_KEY(klv.key, mxf_essence_element_key) ||

            IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) ||

            IS_KLV_KEY(klv.key, mxf_system_item_key)) {

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

                compute_partition_essence_offset(s, mxf, &klv);

            }

            if (!essence_offset)

                essence_offset = klv.offset;

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

            if (mxf_parse_handle_essence(mxf) <= 0)

                break;

            continue;

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

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

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

            if(mxf_parse_handle_partition_or_eof(mxf) <= 0)

                break;

        }

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

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

                int res;

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

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

                } else {

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

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

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

                }

                if (res < 0) {

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

                    return res;

                }

                break;

            }

        }

        if (!metadata->read)

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

    }

    /* FIXME avoid seek */

    if (!essence_offset)  {

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

        return AVERROR_INVALIDDATA;

    }

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

    mxf_compute_essence_containers(mxf);

    return mxf_parse_structural_metadata(mxf);

}


static opj_image_t *mj2_create_image(AVCodecContext *avctx, opj_cparameters_t *parameters)
{
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
    opj_image_cmptparm_t cmptparm[4] = {{0}};
    opj_image_t *img;
    int i;
    int sub_dx[4];
    int sub_dy[4];
    int numcomps;
    OPJ_COLOR_SPACE color_space = CLRSPC_UNKNOWN;
    sub_dx[0] = sub_dx[3] = 1;
    sub_dy[0] = sub_dy[3] = 1;
    sub_dx[1] = sub_dx[2] = 1 << desc->log2_chroma_w;
    sub_dy[1] = sub_dy[2] = 1 << desc->log2_chroma_h;
    numcomps = desc->nb_components;
    switch (avctx->pix_fmt) {
    case AV_PIX_FMT_GRAY8:
    case AV_PIX_FMT_YA8:
    case AV_PIX_FMT_GRAY16:
    case AV_PIX_FMT_YA16:
        color_space = CLRSPC_GRAY;
        break;
    case AV_PIX_FMT_RGB24:
    case AV_PIX_FMT_RGBA:
    case AV_PIX_FMT_RGB48:
    case AV_PIX_FMT_RGBA64:
    case AV_PIX_FMT_GBR24P:
    case AV_PIX_FMT_GBRP9:
    case AV_PIX_FMT_GBRP10:
    case AV_PIX_FMT_GBRP12:
    case AV_PIX_FMT_GBRP14:
    case AV_PIX_FMT_GBRP16:
    case AV_PIX_FMT_XYZ12:
        color_space = CLRSPC_SRGB;
        break;
    case AV_PIX_FMT_YUV410P:
    case AV_PIX_FMT_YUV411P:
    case AV_PIX_FMT_YUV420P:
    case AV_PIX_FMT_YUV422P:
    case AV_PIX_FMT_YUV440P:
    case AV_PIX_FMT_YUV444P:
    case AV_PIX_FMT_YUVA420P:
    case AV_PIX_FMT_YUVA422P:
    case AV_PIX_FMT_YUVA444P:
    case AV_PIX_FMT_YUV420P9:
    case AV_PIX_FMT_YUV422P9:
    case AV_PIX_FMT_YUV444P9:
    case AV_PIX_FMT_YUVA420P9:
    case AV_PIX_FMT_YUVA422P9:
    case AV_PIX_FMT_YUVA444P9:
    case AV_PIX_FMT_YUV420P10:
    case AV_PIX_FMT_YUV422P10:
    case AV_PIX_FMT_YUV444P10:
    case AV_PIX_FMT_YUVA420P10:
    case AV_PIX_FMT_YUVA422P10:
    case AV_PIX_FMT_YUVA444P10:
    case AV_PIX_FMT_YUV420P12:
    case AV_PIX_FMT_YUV422P12:
    case AV_PIX_FMT_YUV444P12:
    case AV_PIX_FMT_YUV420P14:
    case AV_PIX_FMT_YUV422P14:
    case AV_PIX_FMT_YUV444P14:
    case AV_PIX_FMT_YUV420P16:
    case AV_PIX_FMT_YUV422P16:
    case AV_PIX_FMT_YUV444P16:
    case AV_PIX_FMT_YUVA420P16:
    case AV_PIX_FMT_YUVA422P16:
    case AV_PIX_FMT_YUVA444P16:
        color_space = CLRSPC_SYCC;
        break;
    default:
        av_log(avctx, AV_LOG_ERROR,
               "The requested pixel format '%s' is not supported\n",
               av_get_pix_fmt_name(avctx->pix_fmt));
    }
    for (i = 0; i < numcomps; i++) {
        cmptparm[i].prec = desc->comp[i].depth_minus1 + 1;
        cmptparm[i].bpp  = desc->comp[i].depth_minus1 + 1;
        cmptparm[i].sgnd = 0;
        cmptparm[i].dx = sub_dx[i];
        cmptparm[i].dy = sub_dy[i];
        cmptparm[i].w = (avctx->width + sub_dx[i] - 1) / sub_dx[i];
        cmptparm[i].h = (avctx->height + sub_dy[i] - 1) / sub_dy[i];
    }
    img = opj_image_create(numcomps, cmptparm, color_space);
    // x0, y0 is the top left corner of the image
    // x1, y1 is the width, height of the reference grid
    img->x0 = 0;
    img->y0 = 0;
    img->x1 = (avctx->width  - 1) * parameters->subsampling_dx + 1;
    img->y1 = (avctx->height - 1) * parameters->subsampling_dy + 1;
    return img;
}


static int xen_platform_initfn(PCIDevice *dev)

{

    PCIXenPlatformState *d = DO_UPCAST(PCIXenPlatformState, pci_dev, dev);

    uint8_t *pci_conf;

    pci_conf = d->pci_dev.config;

    pci_set_word(pci_conf + PCI_COMMAND, PCI_COMMAND_IO | PCI_COMMAND_MEMORY);

    pci_config_set_prog_interface(pci_conf, 0);

    pci_conf[PCI_INTERRUPT_PIN] = 1;

    pci_register_bar(&d->pci_dev, 0, 0x100,

            PCI_BASE_ADDRESS_SPACE_IO, platform_ioport_map);

    /* reserve 16MB mmio address for share memory*/

    pci_register_bar(&d->pci_dev, 1, 0x1000000,

            PCI_BASE_ADDRESS_MEM_PREFETCH, platform_mmio_map);

    platform_fixed_ioport_init(d);

    return 0;

}


static int proxy_symlink(FsContext *fs_ctx, const char *oldpath,

                         V9fsPath *dir_path, const char *name, FsCred *credp)

{

    int retval;

    V9fsString fullname, target;

    v9fs_string_init(&fullname);

    v9fs_string_init(&target);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    v9fs_string_sprintf(&target, "%s", oldpath);

    retval = v9fs_request(fs_ctx->private, T_SYMLINK, NULL, "ssdd",

                          &target, &fullname, credp->fc_uid, credp->fc_gid);

    v9fs_string_free(&fullname);

    v9fs_string_free(&target);

    if (retval < 0) {

        errno = -retval;

        retval = -1;

    }

    return retval;

}


static int vfio_enable_intx(VFIODevice *vdev)

{

    VFIOIRQSetFD irq_set_fd = {

        .irq_set = {

            .argsz = sizeof(irq_set_fd),

            .flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER,

            .index = VFIO_PCI_INTX_IRQ_INDEX,

            .start = 0,

            .count = 1,

        },

    };

    uint8_t pin = vfio_pci_read_config(&vdev->pdev, PCI_INTERRUPT_PIN, 1);

    int ret;

    if (vdev->intx.disabled || !pin) {

        return 0;

    }

    vfio_disable_interrupts(vdev);

    vdev->intx.pin = pin - 1; /* Pin A (1) -> irq[0] */

    ret = event_notifier_init(&vdev->intx.interrupt, 0);

    if (ret) {

        error_report("vfio: Error: event_notifier_init failed\n");

        return ret;

    }

    irq_set_fd.fd = event_notifier_get_fd(&vdev->intx.interrupt);

    qemu_set_fd_handler(irq_set_fd.fd, vfio_intx_interrupt, NULL, vdev);

    if (ioctl(vdev->fd, VFIO_DEVICE_SET_IRQS, &irq_set_fd)) {

        error_report("vfio: Error: Failed to setup INTx fd: %m\n");

        return -errno;

    }

    /*

     * Disable mmaps so we can trap on BAR accesses.  We interpret any

     * access as a response to an interrupt and unmask the physical

     * device.  The device will re-assert if the interrupt is still

     * pending.  We'll likely retrigger on the host multiple times per

     * guest interrupt, but without EOI notification it's better than

     * nothing.  Acceleration paths through KVM will avoid this.

     */

    vfio_mmap_set_enabled(vdev, false);

    vdev->interrupt = VFIO_INT_INTx;

    DPRINTF("%s(%04x:%02x:%02x.%x)\n", __func__, vdev->host.domain,

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

    return 0;

}


void HELPER(mvc)(CPUS390XState *env, uint32_t l, uint64_t dest, uint64_t src)

{

    int i = 0;

    int x = 0;

    uint32_t l_64 = (l + 1) / 8;

    HELPER_LOG("%s l %d dest %" PRIx64 " src %" PRIx64 "\n",

               __func__, l, dest, src);

#ifndef CONFIG_USER_ONLY

    if ((l > 32) &&

        (src & TARGET_PAGE_MASK) == ((src + l) & TARGET_PAGE_MASK) &&

        (dest & TARGET_PAGE_MASK) == ((dest + l) & TARGET_PAGE_MASK)) {

        if (dest == (src + 1)) {

            mvc_fast_memset(env, l + 1, dest, cpu_ldub_data(env, src));

            return;

        } else if ((src & TARGET_PAGE_MASK) != (dest & TARGET_PAGE_MASK)) {

            mvc_fast_memmove(env, l + 1, dest, src);

            return;

        }

    }

#else

    if (dest == (src + 1)) {

        memset(g2h(dest), cpu_ldub_data(env, src), l + 1);

        return;

    /* mvc and memmove do not behave the same when areas overlap! */

    } else if ((dest < src) || (src + l < dest)) {

        memmove(g2h(dest), g2h(src), l + 1);

        return;

    }

#endif

    /* handle the parts that fit into 8-byte loads/stores */

    if ((dest + 8 <= src) || (src + 8 <= dest)) {

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

            cpu_stq_data(env, dest + x, cpu_ldq_data(env, src + x));

            x += 8;

        }

    }

    /* slow version with byte accesses which always work */

    for (i = x; i <= l; i++) {

        cpu_stb_data(env, dest + i, cpu_ldub_data(env, src + i));

    }

}