static av_cold int mpc7_decode_init(AVCodecContext * avctx)

{

    int i, j;

    MPCContext *c = avctx->priv_data;

    GetBitContext gb;

    LOCAL_ALIGNED_16(uint8_t, buf, [16]);

    static int vlc_initialized = 0;

    static VLC_TYPE scfi_table[1 << MPC7_SCFI_BITS][2];

    static VLC_TYPE dscf_table[1 << MPC7_DSCF_BITS][2];

    static VLC_TYPE hdr_table[1 << MPC7_HDR_BITS][2];

    static VLC_TYPE quant_tables[7224][2];

    /* Musepack SV7 is always stereo */

    if (avctx->channels != 2) {

        av_log_ask_for_sample(avctx, "Unsupported number of channels: %d\n",

                              avctx->channels);

        return AVERROR_PATCHWELCOME;

    }

    if(avctx->extradata_size < 16){

        av_log(avctx, AV_LOG_ERROR, "Too small extradata size (%i)!\n", avctx->extradata_size);

        return -1;

    }

    memset(c->oldDSCF, 0, sizeof(c->oldDSCF));

    av_lfg_init(&c->rnd, 0xDEADBEEF);

    ff_dsputil_init(&c->dsp, avctx);

    ff_mpadsp_init(&c->mpadsp);

    c->dsp.bswap_buf((uint32_t*)buf, (const uint32_t*)avctx->extradata, 4);

    ff_mpc_init();

    init_get_bits(&gb, buf, 128);

    c->IS = get_bits1(&gb);

    c->MSS = get_bits1(&gb);

    c->maxbands = get_bits(&gb, 6);

    if(c->maxbands >= BANDS){

        av_log(avctx, AV_LOG_ERROR, "Too many bands: %i\n", c->maxbands);

        return -1;

    }

    skip_bits_long(&gb, 88);

    c->gapless = get_bits1(&gb);

    c->lastframelen = get_bits(&gb, 11);

    av_log(avctx, AV_LOG_DEBUG, "IS: %d, MSS: %d, TG: %d, LFL: %d, bands: %d\n",

            c->IS, c->MSS, c->gapless, c->lastframelen, c->maxbands);

    c->frames_to_skip = 0;

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    avctx->channel_layout = AV_CH_LAYOUT_STEREO;

    if(vlc_initialized) return 0;

    av_log(avctx, AV_LOG_DEBUG, "Initing VLC\n");

    scfi_vlc.table = scfi_table;

    scfi_vlc.table_allocated = 1 << MPC7_SCFI_BITS;

    if(init_vlc(&scfi_vlc, MPC7_SCFI_BITS, MPC7_SCFI_SIZE,

                &mpc7_scfi[1], 2, 1,

                &mpc7_scfi[0], 2, 1, INIT_VLC_USE_NEW_STATIC)){

        av_log(avctx, AV_LOG_ERROR, "Cannot init SCFI VLC\n");

        return -1;

    }

    dscf_vlc.table = dscf_table;

    dscf_vlc.table_allocated = 1 << MPC7_DSCF_BITS;

    if(init_vlc(&dscf_vlc, MPC7_DSCF_BITS, MPC7_DSCF_SIZE,

                &mpc7_dscf[1], 2, 1,

                &mpc7_dscf[0], 2, 1, INIT_VLC_USE_NEW_STATIC)){

        av_log(avctx, AV_LOG_ERROR, "Cannot init DSCF VLC\n");

        return -1;

    }

    hdr_vlc.table = hdr_table;

    hdr_vlc.table_allocated = 1 << MPC7_HDR_BITS;

    if(init_vlc(&hdr_vlc, MPC7_HDR_BITS, MPC7_HDR_SIZE,

                &mpc7_hdr[1], 2, 1,

                &mpc7_hdr[0], 2, 1, INIT_VLC_USE_NEW_STATIC)){

        av_log(avctx, AV_LOG_ERROR, "Cannot init HDR VLC\n");

        return -1;

    }

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

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

            quant_vlc[i][j].table = &quant_tables[quant_offsets[i*2 + j]];

            quant_vlc[i][j].table_allocated = quant_offsets[i*2 + j + 1] - quant_offsets[i*2 + j];

            if(init_vlc(&quant_vlc[i][j], 9, mpc7_quant_vlc_sizes[i],

                        &mpc7_quant_vlc[i][j][1], 4, 2,

                        &mpc7_quant_vlc[i][j][0], 4, 2, INIT_VLC_USE_NEW_STATIC)){

                av_log(avctx, AV_LOG_ERROR, "Cannot init QUANT VLC %i,%i\n",i,j);

                return -1;

            }

        }

    }

    vlc_initialized = 1;

    avcodec_get_frame_defaults(&c->frame);

    avctx->coded_frame = &c->frame;

    return 0;

}


static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)

{

    struct video_data *s = s1->priv_data;

    struct v4l2_input input;

    struct v4l2_standard standard;

    struct v4l2_streamparm streamparm = { 0 };

    struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;

    int i;

    streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

#if FF_API_FORMAT_PARAMETERS

    if (ap->channel > 0)

        s->channel = ap->channel;

#endif

    /* set tv video input */

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

    input.index = s->channel;

    if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {

        av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");

        return AVERROR(EIO);

    }

    av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",

            s->channel, input.name);

    if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {

        av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",

                s->channel);

        return AVERROR(EIO);

    }

#if FF_API_FORMAT_PARAMETERS

    if (ap->standard) {

        av_freep(&s->standard);

        s->standard = av_strdup(ap->standard);

    }

#endif

    if (s->standard) {

        av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",

               s->standard);

        /* set tv standard */

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

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

            standard.index = i;

            if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {

                av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",

                       s->standard);

                return AVERROR(EIO);

            }

            if (!strcasecmp(standard.name, s->standard)) {

                break;

            }

        }

        av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",

               s->standard, (uint64_t)standard.id);

        if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {

            av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",

                   s->standard);

            return AVERROR(EIO);

        }

    }

    av_freep(&s->standard);

    if (ap->time_base.num && ap->time_base.den) {

        av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",

               ap->time_base.num, ap->time_base.den);

        tpf->numerator = ap->time_base.num;

        tpf->denominator = ap->time_base.den;

        if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {

            av_log(s1, AV_LOG_ERROR,

                   "ioctl set time per frame(%d/%d) failed\n",

                   ap->time_base.num, ap->time_base.den);

            return AVERROR(EIO);

        }

        if (ap->time_base.den != tpf->denominator ||

            ap->time_base.num != tpf->numerator) {

            av_log(s1, AV_LOG_INFO,

                   "The driver changed the time per frame from %d/%d to %d/%d\n",

                   ap->time_base.num, ap->time_base.den,

                   tpf->numerator, tpf->denominator);

        }

    } else {

        /* if timebase value is not set in ap, read the timebase value from the driver */

        if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {

            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));

            return AVERROR(errno);

        }

    }

    ap->time_base.num = tpf->numerator;

    ap->time_base.den = tpf->denominator;

    return 0;

}


void vnc_tight_clear(VncState *vs)

{

    int i;

    for (i=0; i<ARRAY_SIZE(vs->tight.stream); i++) {

        if (vs->tight.stream[i].opaque) {

            deflateEnd(&vs->tight.stream[i]);

        }

    }

    buffer_free(&vs->tight.tight);

    buffer_free(&vs->tight.zlib);

    buffer_free(&vs->tight.gradient);

#ifdef CONFIG_VNC_JPEG

    buffer_free(&vs->tight.jpeg);

}


vcard_emul_replay_insertion_events(void)
{
    VReaderListEntry *current_entry;
    VReaderListEntry *next_entry = NULL;
    VReaderList *list = vreader_get_reader_list();
    for (current_entry = vreader_list_get_first(list); current_entry;
            current_entry = next_entry) {
        VReader *vreader = vreader_list_get_reader(current_entry);
        next_entry = vreader_list_get_next(current_entry);
        vreader_queue_card_event(vreader);
    }
}


static int cmp_intervals(const void *a, const void *b)

{

    const Interval *i1 = a;

    const Interval *i2 = b;

    int64_t ts_diff = i1->start_ts - i2->start_ts;

    int ret;

    ret = ts_diff > 0 ? 1 : ts_diff < 0 ? -1 : 0;

    return ret == 0 ? i1->index - i2->index : ret;

}


static char *getstr8(const uint8_t **pp, const uint8_t *p_end)

{

    int len;

    const uint8_t *p;

    char *str;

    p   = *pp;

    len = get8(&p, p_end);

    if (len < 0)

        return NULL;

    if ((p + len) > p_end)

        return NULL;

    str = av_malloc(len + 1);

    if (!str)

        return NULL;

    memcpy(str, p, len);

    str[len] = '\0';

    p  += len;

    *pp = p;

    return str;

}


int monitor_fdset_dup_fd_remove(int dupfd)

{

    return -1;

}


int av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)

{

    BufferSourceContext *s = ctx->priv;

    AVFrame *copy;

    int ret;

    if (!frame) {

        s->eof = 1;

        return 0;

    } else if (s->eof)

        return AVERROR(EINVAL);

    switch (ctx->outputs[0]->type) {

    case AVMEDIA_TYPE_VIDEO:

        CHECK_VIDEO_PARAM_CHANGE(ctx, s, frame->width, frame->height,

                                 frame->format);

        break;

    case AVMEDIA_TYPE_AUDIO:

        CHECK_AUDIO_PARAM_CHANGE(ctx, s, frame->sample_rate, frame->channel_layout,

                                 frame->format);

        break;

    default:

        return AVERROR(EINVAL);

    }

    if (!av_fifo_space(s->fifo) &&

        (ret = av_fifo_realloc2(s->fifo, av_fifo_size(s->fifo) +

                                         sizeof(copy))) < 0)

        return ret;

    if (!(copy = av_frame_alloc()))

        return AVERROR(ENOMEM);

    av_frame_move_ref(copy, frame);

    if ((ret = av_fifo_generic_write(s->fifo, &copy, sizeof(copy), NULL)) < 0) {

        av_frame_move_ref(frame, copy);

        av_frame_free(&copy);

        return ret;

    }

    return 0;

}


static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)

{

    VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);

    VirtIODevice *vdev = vq->vdev;

    hwaddr pa = offsetof(VRingUsed, flags);

    uint16_t flags = virtio_lduw_phys_cached(vq->vdev, &caches->used, pa);

    virtio_stw_phys_cached(vdev, &caches->used, pa, flags & ~mask);

    address_space_cache_invalidate(&caches->used, pa, sizeof(flags));

}


static int wmavoice_decode_packet(AVCodecContext *ctx, void *data,

                                  int *data_size, AVPacket *avpkt)

{

    WMAVoiceContext *s = ctx->priv_data;

    GetBitContext *gb = &s->gb;

    int size, res, pos;

    if (*data_size < 480 * sizeof(float)) {

        av_log(ctx, AV_LOG_ERROR,

               "Output buffer too small (%d given - %zu needed)\n",

               *data_size, 480 * sizeof(float));

        return -1;

    }

    /* Packets are sometimes a multiple of ctx->block_align, with a packet

     * header at each ctx->block_align bytes. However, Libav's ASF demuxer

     * feeds us ASF packets, which may concatenate multiple "codec" packets

     * in a single "muxer" packet, so we artificially emulate that by

     * capping the packet size at ctx->block_align. */

    for (size = avpkt->size; size > ctx->block_align; size -= ctx->block_align);

    if (!size) {

        *data_size = 0;

        return 0;

    }

    init_get_bits(&s->gb, avpkt->data, size << 3);

    /* size == ctx->block_align is used to indicate whether we are dealing with

     * a new packet or a packet of which we already read the packet header

     * previously. */

    if (size == ctx->block_align) { // new packet header

        if ((res = parse_packet_header(s)) < 0)

            return res;

        /* If the packet header specifies a s->spillover_nbits, then we want

         * to push out all data of the previous packet (+ spillover) before

         * continuing to parse new superframes in the current packet. */

        if (s->spillover_nbits > 0) {

            if (s->sframe_cache_size > 0) {

                int cnt = get_bits_count(gb);

                copy_bits(&s->pb, avpkt->data, size, gb, s->spillover_nbits);

                flush_put_bits(&s->pb);

                s->sframe_cache_size += s->spillover_nbits;

                if ((res = synth_superframe(ctx, data, data_size)) == 0 &&

                    *data_size > 0) {

                    cnt += s->spillover_nbits;

                    s->skip_bits_next = cnt & 7;

                    return cnt >> 3;

                } else

                    skip_bits_long (gb, s->spillover_nbits - cnt +

                                    get_bits_count(gb)); // resync

            } else

                skip_bits_long(gb, s->spillover_nbits);  // resync

        }

    } else if (s->skip_bits_next)

        skip_bits(gb, s->skip_bits_next);

    /* Try parsing superframes in current packet */

    s->sframe_cache_size = 0;

    s->skip_bits_next = 0;

    pos = get_bits_left(gb);

    if ((res = synth_superframe(ctx, data, data_size)) < 0) {

        return res;

    } else if (*data_size > 0) {

        int cnt = get_bits_count(gb);

        s->skip_bits_next = cnt & 7;

        return cnt >> 3;

    } else if ((s->sframe_cache_size = pos) > 0) {

        /* rewind bit reader to start of last (incomplete) superframe... */

        init_get_bits(gb, avpkt->data, size << 3);

        skip_bits_long(gb, (size << 3) - pos);

        assert(get_bits_left(gb) == pos);

        /* ...and cache it for spillover in next packet */

        init_put_bits(&s->pb, s->sframe_cache, SFRAME_CACHE_MAXSIZE);

        copy_bits(&s->pb, avpkt->data, size, gb, s->sframe_cache_size);

        // FIXME bad - just copy bytes as whole and add use the

        // skip_bits_next field

    }

    return size;

}


static av_cold int flashsv_encode_end(AVCodecContext *avctx)

{

    FlashSVContext *s = avctx->priv_data;

    deflateEnd(&s->zstream);

    av_free(s->encbuffer);

    av_free(s->previous_frame);

    av_free(s->tmpblock);

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static int pcx_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                            AVPacket *avpkt)

{

    PCXContext * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p = &s->picture;

    GetByteContext gb;

    int compressed, xmin, ymin, xmax, ymax, ret;

    unsigned int w, h, bits_per_pixel, bytes_per_line, nplanes, stride, y, x,

                 bytes_per_scanline;

    uint8_t *ptr, *scanline;

    if (avpkt->size < 128)

        return AVERROR_INVALIDDATA;

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

    if (bytestream2_get_byteu(&gb) != 0x0a || bytestream2_get_byteu(&gb) > 5) {

        av_log(avctx, AV_LOG_ERROR, "this is not PCX encoded data\n");

        return AVERROR_INVALIDDATA;

    }

    compressed = bytestream2_get_byteu(&gb);

    bits_per_pixel = bytestream2_get_byteu(&gb);

    xmin = bytestream2_get_le16u(&gb);

    ymin = bytestream2_get_le16u(&gb);

    xmax = bytestream2_get_le16u(&gb);

    ymax = bytestream2_get_le16u(&gb);

    avctx->sample_aspect_ratio.num = bytestream2_get_le16u(&gb);

    avctx->sample_aspect_ratio.den = bytestream2_get_le16u(&gb);

    if (xmax < xmin || ymax < ymin) {

        av_log(avctx, AV_LOG_ERROR, "invalid image dimensions\n");

        return AVERROR_INVALIDDATA;

    }

    w = xmax - xmin + 1;

    h = ymax - ymin + 1;

    bytestream2_skipu(&gb, 49);

    nplanes            = bytestream2_get_byteu(&gb);

    bytes_per_line     = bytestream2_get_le16u(&gb);

    bytes_per_scanline = nplanes * bytes_per_line;

    if (bytes_per_scanline < (w * bits_per_pixel * nplanes + 7) / 8) {

        av_log(avctx, AV_LOG_ERROR, "PCX data is corrupted\n");

        return AVERROR_INVALIDDATA;

    }

    switch ((nplanes<<8) + bits_per_pixel) {

        case 0x0308:

            avctx->pix_fmt = AV_PIX_FMT_RGB24;

            break;

        case 0x0108:

        case 0x0104:

        case 0x0102:

        case 0x0101:

        case 0x0401:

        case 0x0301:

        case 0x0201:

            avctx->pix_fmt = AV_PIX_FMT_PAL8;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "invalid PCX file\n");

            return AVERROR_INVALIDDATA;

    }

    bytestream2_skipu(&gb, 60);

    if (p->data[0])

        avctx->release_buffer(avctx, p);

    if ((ret = av_image_check_size(w, h, 0, avctx)) < 0)

        return ret;

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

        avcodec_set_dimensions(avctx, w, h);

    if ((ret = ff_get_buffer(avctx, p)) < 0) {

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

        return ret;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    ptr    = p->data[0];

    stride = p->linesize[0];

    scanline = av_malloc(bytes_per_scanline);

    if (!scanline)

        return AVERROR(ENOMEM);

    if (nplanes == 3 && bits_per_pixel == 8) {

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

            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);

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

                ptr[3*x  ] = scanline[x                    ];

                ptr[3*x+1] = scanline[x+ bytes_per_line    ];

                ptr[3*x+2] = scanline[x+(bytes_per_line<<1)];

            }

            ptr += stride;

        }

    } else if (nplanes == 1 && bits_per_pixel == 8) {

        int palstart = avpkt->size - 769;

        for (y=0; y<h; y++, ptr+=stride) {

            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);

            memcpy(ptr, scanline, w);

        }

        if (bytestream2_tell(&gb) != palstart) {

            av_log(avctx, AV_LOG_WARNING, "image data possibly corrupted\n");

            bytestream2_seek(&gb, palstart, SEEK_SET);

        }

        if (bytestream2_get_byte(&gb) != 12) {

            av_log(avctx, AV_LOG_ERROR, "expected palette after image data\n");

            ret = AVERROR_INVALIDDATA;

            goto end;

        }

    } else if (nplanes == 1) {   /* all packed formats, max. 16 colors */

        GetBitContext s;

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

            init_get_bits8(&s, scanline, bytes_per_scanline);

            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);

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

                ptr[x] = get_bits(&s, bits_per_pixel);

            ptr += stride;

        }

    } else {    /* planar, 4, 8 or 16 colors */

        int i;

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

            pcx_rle_decode(&gb, scanline, bytes_per_scanline, compressed);

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

                int m = 0x80 >> (x&7), v = 0;

                for (i=nplanes - 1; i>=0; i--) {

                    v <<= 1;

                    v  += !!(scanline[i*bytes_per_line + (x>>3)] & m);

                }

                ptr[x] = v;

            }

            ptr += stride;

        }

    }

    ret = bytestream2_tell(&gb);

    if (nplanes == 1 && bits_per_pixel == 8) {

        pcx_palette(&gb, (uint32_t *) p->data[1], 256);

        ret += 256 * 3;

    } else if (bits_per_pixel * nplanes == 1) {

        AV_WN32A(p->data[1]  , 0xFF000000);

        AV_WN32A(p->data[1]+4, 0xFFFFFFFF);

    } else if (bits_per_pixel < 8) {

        bytestream2_seek(&gb, 16, SEEK_SET);

        pcx_palette(&gb, (uint32_t *) p->data[1], 16);

    }

    *picture = s->picture;

    *got_frame = 1;

end:

    av_free(scanline);

    return ret;

}


static void av_always_inline filter_mb_edgev( uint8_t *pix, int stride, int16_t bS[4], unsigned int qp, H264Context *h) {

    const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    const unsigned int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[qp - qp_bd_offset + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]];

        tc[1] = tc0_table[index_a][bS[1]];

        tc[2] = tc0_table[index_a][bS[2]];

        tc[3] = tc0_table[index_a][bS[3]];

        h->h264dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_h_loop_filter_luma_intra(pix, stride, alpha, beta);

    }

}


int rom_add_file(const char *file, const char *fw_dir,

                 target_phys_addr_t addr, int32_t bootindex)

{

    Rom *rom;

    int rc, fd = -1;

    char devpath[100];

    rom = g_malloc0(sizeof(*rom));

    rom->name = g_strdup(file);

    rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);

    if (rom->path == NULL) {

        rom->path = g_strdup(file);

    }

    fd = open(rom->path, O_RDONLY | O_BINARY);

    if (fd == -1) {

        fprintf(stderr, "Could not open option rom '%s': %s\n",

                rom->path, strerror(errno));

        goto err;

    }

    if (fw_dir) {

        rom->fw_dir  = g_strdup(fw_dir);

        rom->fw_file = g_strdup(file);

    }

    rom->addr    = addr;

    rom->romsize = lseek(fd, 0, SEEK_END);

    rom->data    = g_malloc0(rom->romsize);

    lseek(fd, 0, SEEK_SET);

    rc = read(fd, rom->data, rom->romsize);

    if (rc != rom->romsize) {

        fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",

                rom->name, rc, rom->romsize);

        goto err;

    }

    close(fd);

    rom_insert(rom);

    if (rom->fw_file && fw_cfg) {

        const char *basename;

        char fw_file_name[56];

        basename = strrchr(rom->fw_file, '/');

        if (basename) {

            basename++;

        } else {

            basename = rom->fw_file;

        }

        snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,

                 basename);

        fw_cfg_add_file(fw_cfg, fw_file_name, rom->data, rom->romsize);

        snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);

    } else {

        snprintf(devpath, sizeof(devpath), "/rom@" TARGET_FMT_plx, addr);

    }

    add_boot_device_path(bootindex, NULL, devpath);

    return 0;

err:

    if (fd != -1)

        close(fd);

    g_free(rom->data);

    g_free(rom->path);

    g_free(rom->name);

    g_free(rom);

    return -1;

}


static int hls_write_header(AVFormatContext *s)

{

    HLSContext *hls = s->priv_data;

    int ret, i;

    char *p;

    const char *pattern = "%d.ts";

    const char *pattern_localtime_fmt = "-%s.ts";

    const char *vtt_pattern = "%d.vtt";

    AVDictionary *options = NULL;

    int basename_size;

    int vtt_basename_size;

    hls->sequence       = hls->start_sequence;

    hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;

    hls->start_pts      = AV_NOPTS_VALUE;

    if (hls->flags & HLS_PROGRAM_DATE_TIME) {

        time_t now0;

        time(&now0);

        hls->initial_prog_date_time = now0;

    }

    if (hls->format_options_str) {

        ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);

        if (ret < 0) {

            av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);

            goto fail;

        }

    }

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

        hls->has_video +=

            s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;

        hls->has_subtitle +=

            s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;

    }

    if (hls->has_video > 1)

        av_log(s, AV_LOG_WARNING,

               "More than a single video stream present, "

               "expect issues decoding it.\n");

    hls->oformat = av_guess_format("mpegts", NULL, NULL);

    if (!hls->oformat) {

        ret = AVERROR_MUXER_NOT_FOUND;

        goto fail;

    }

    if(hls->has_subtitle) {

        hls->vtt_oformat = av_guess_format("webvtt", NULL, NULL);

        if (!hls->oformat) {

            ret = AVERROR_MUXER_NOT_FOUND;

            goto fail;

        }

    }

    if (hls->segment_filename) {

        hls->basename = av_strdup(hls->segment_filename);

        if (!hls->basename) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

    } else {

        if (hls->flags & HLS_SINGLE_FILE)

            pattern = ".ts";

        if (hls->use_localtime) {

            basename_size = strlen(s->filename) + strlen(pattern_localtime_fmt) + 1;

        } else {

            basename_size = strlen(s->filename) + strlen(pattern) + 1;

        }

        hls->basename = av_malloc(basename_size);

        if (!hls->basename) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        av_strlcpy(hls->basename, s->filename, basename_size);

        p = strrchr(hls->basename, '.');

        if (p)

            *p = '\0';

        if (hls->use_localtime) {

            av_strlcat(hls->basename, pattern_localtime_fmt, basename_size);

        } else {

            av_strlcat(hls->basename, pattern, basename_size);

        }

    }

    if (!hls->use_localtime && (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX)) {

        av_log(hls, AV_LOG_ERROR, "second_level_segment_index hls_flag requires use_localtime to be true\n");

        ret = AVERROR(EINVAL);

        goto fail;

    }

    if(hls->has_subtitle) {

        if (hls->flags & HLS_SINGLE_FILE)

            vtt_pattern = ".vtt";

        vtt_basename_size = strlen(s->filename) + strlen(vtt_pattern) + 1;

        hls->vtt_basename = av_malloc(vtt_basename_size);

        if (!hls->vtt_basename) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        hls->vtt_m3u8_name = av_malloc(vtt_basename_size);

        if (!hls->vtt_m3u8_name ) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        av_strlcpy(hls->vtt_basename, s->filename, vtt_basename_size);

        p = strrchr(hls->vtt_basename, '.');

        if (p)

            *p = '\0';

        if( hls->subtitle_filename ) {

            strcpy(hls->vtt_m3u8_name, hls->subtitle_filename);

        } else {

            strcpy(hls->vtt_m3u8_name, hls->vtt_basename);

            av_strlcat(hls->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);

        }

        av_strlcat(hls->vtt_basename, vtt_pattern, vtt_basename_size);

    }

    if ((ret = hls_mux_init(s)) < 0)

        goto fail;

    if (hls->flags & HLS_APPEND_LIST) {

        parse_playlist(s, s->filename);

        hls->discontinuity = 1;

        if (hls->init_time > 0) {

            av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"

                   " hls_init_time value will have no effect\n");

            hls->init_time = 0;

            hls->recording_time = hls->time * AV_TIME_BASE;

        }

    }

    if ((ret = hls_start(s)) < 0)

        goto fail;

    av_dict_copy(&options, hls->format_options, 0);

    ret = avformat_write_header(hls->avf, &options);

    if (av_dict_count(options)) {

        av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);

        ret = AVERROR(EINVAL);

        goto fail;

    }

    //av_assert0(s->nb_streams == hls->avf->nb_streams);

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

        AVStream *inner_st;

        AVStream *outer_st = s->streams[i];

        if (hls->max_seg_size > 0) {

            if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&

                (outer_st->codecpar->bit_rate > hls->max_seg_size)) {

                av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "

                       "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",

                       outer_st->codecpar->bit_rate, hls->max_seg_size);

            }

        }

        if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)

            inner_st = hls->avf->streams[i];

        else if (hls->vtt_avf)

            inner_st = hls->vtt_avf->streams[0];

        else {

            /* We have a subtitle stream, when the user does not want one */

            inner_st = NULL;

            continue;

        }

        avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);

    }

fail:

    av_dict_free(&options);

    if (ret < 0) {

        av_freep(&hls->basename);

        av_freep(&hls->vtt_basename);

        if (hls->avf)

            avformat_free_context(hls->avf);

        if (hls->vtt_avf)

            avformat_free_context(hls->vtt_avf);

    }

    return ret;

}


static int tta_get_unary(GetBitContext *gb)

{

    int ret = 0;

    // count ones

    while(get_bits1(gb))

        ret++;

    return ret;

}


void helper_set_alt_mode (void)

{

    env->saved_mode = env->ps & 0xC;

    env->ps = (env->ps & ~0xC) | (env->ipr[IPR_ALT_MODE] & 0xC);

}


setup_sigcontext(struct target_sigcontext *sc, CPUM68KState *env,

                 abi_ulong mask)

{

    int err = 0;

    __put_user(mask, &sc->sc_mask);

    __put_user(env->aregs[7], &sc->sc_usp);

    __put_user(env->dregs[0], &sc->sc_d0);

    __put_user(env->dregs[1], &sc->sc_d1);

    __put_user(env->aregs[0], &sc->sc_a0);

    __put_user(env->aregs[1], &sc->sc_a1);

    __put_user(env->sr, &sc->sc_sr);

    __put_user(env->pc, &sc->sc_pc);

    return err;

}


static void icount_adjust_rt(void * opaque)

{

    qemu_mod_timer(icount_rt_timer,

                   qemu_get_clock(rt_clock) + 1000);

    icount_adjust();

}


static void virtio_blk_migration_state_changed(Notifier *notifier, void *data)

{

    VirtIOBlock *s = container_of(notifier, VirtIOBlock,

                                  migration_state_notifier);

    MigrationState *mig = data;

    Error *err = NULL;

    if (migration_in_setup(mig)) {

        if (!s->dataplane) {

            return;

        }

        virtio_blk_data_plane_destroy(s->dataplane);

        s->dataplane = NULL;

    } else if (migration_has_finished(mig) ||

               migration_has_failed(mig)) {

        if (s->dataplane) {

            return;

        }

        bdrv_drain_all(); /* complete in-flight non-dataplane requests */

        virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->conf,

                                     &s->dataplane, &err);

        if (err != NULL) {

            error_report("%s", error_get_pretty(err));

            error_free(err);

        }

    }

}


CaptureVoiceOut *AUD_add_capture (

    struct audsettings *as,

    struct audio_capture_ops *ops,

    void *cb_opaque

    )

{

    AudioState *s = &glob_audio_state;

    CaptureVoiceOut *cap;

    struct capture_callback *cb;

    if (audio_validate_settings (as)) {

        dolog ("Invalid settings were passed when trying to add capture\n");

        audio_print_settings (as);

        goto err0;

    }

    cb = audio_calloc (AUDIO_FUNC, 1, sizeof (*cb));

    if (!cb) {

        dolog ("Could not allocate capture callback information, size %zu\n",

               sizeof (*cb));

        goto err0;

    }

    cb->ops = *ops;

    cb->opaque = cb_opaque;

    cap = audio_pcm_capture_find_specific (as);

    if (cap) {

        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);

        return cap;

    }

    else {

        HWVoiceOut *hw;

        CaptureVoiceOut *cap;

        cap = audio_calloc (AUDIO_FUNC, 1, sizeof (*cap));

        if (!cap) {

            dolog ("Could not allocate capture voice, size %zu\n",

                   sizeof (*cap));

            goto err1;

        }

        hw = &cap->hw;

        LIST_INIT (&hw->sw_head);

        LIST_INIT (&cap->cb_head);

        /* XXX find a more elegant way */

        hw->samples = 4096 * 4;

        hw->mix_buf = audio_calloc (AUDIO_FUNC, hw->samples,

                                    sizeof (struct st_sample));

        if (!hw->mix_buf) {

            dolog ("Could not allocate capture mix buffer (%d samples)\n",

                   hw->samples);

            goto err2;

        }

        audio_pcm_init_info (&hw->info, as);

        cap->buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

        if (!cap->buf) {

            dolog ("Could not allocate capture buffer "

                   "(%d samples, each %d bytes)\n",

                   hw->samples, 1 << hw->info.shift);

            goto err3;

        }

        hw->clip = mixeng_clip

            [hw->info.nchannels == 2]

            [hw->info.sign]

            [hw->info.swap_endianness]

            [audio_bits_to_index (hw->info.bits)];

        LIST_INSERT_HEAD (&s->cap_head, cap, entries);

        LIST_INSERT_HEAD (&cap->cb_head, cb, entries);

        hw = NULL;

        while ((hw = audio_pcm_hw_find_any_out (hw))) {

            audio_attach_capture (hw);

        }

        return cap;

    err3:

        qemu_free (cap->hw.mix_buf);

    err2:

        qemu_free (cap);

    err1:

        qemu_free (cb);

    err0:

        return NULL;

    }

}


const char *bdrv_get_encrypted_filename(BlockDriverState *bs)

{

    if (bs->backing_hd && bs->backing_hd->encrypted)

        return bs->backing_file;

    else if (bs->encrypted)

        return bs->filename;

    else

        return NULL;

}


static inline void tcg_out_goto(TCGContext *s, tcg_insn_unit *target)

{

    ptrdiff_t offset = target - s->code_ptr;

    assert(offset == sextract64(offset, 0, 26));

    tcg_out_insn(s, 3206, B, offset);

}


void qapi_copy_SocketAddress(SocketAddress **p_dest,

                             SocketAddress *src)

{

    QmpOutputVisitor *qov;

    Visitor *ov, *iv;

    QObject *obj;

    *p_dest = NULL;

    qov = qmp_output_visitor_new();

    ov = qmp_output_get_visitor(qov);

    visit_type_SocketAddress(ov, NULL, &src, &error_abort);

    obj = qmp_output_get_qobject(qov);

    visit_free(ov);

    if (!obj) {

        return;

    }

    iv = qmp_input_visitor_new(obj, true);

    visit_type_SocketAddress(iv, NULL, p_dest, &error_abort);

    visit_free(iv);

    qobject_decref(obj);

}


static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)

{

    AVFormatContext *is = ifile->ctx;

    AVFormatContext *os = ofile->ctx;

    AVChapter **tmp;

    int i;

    tmp = av_realloc(os->chapters, sizeof(*os->chapters) * (is->nb_chapters + os->nb_chapters));

    if (!tmp)

        return AVERROR(ENOMEM);

    os->chapters = tmp;

    for (i = 0; i < is->nb_chapters; i++) {

        AVChapter *in_ch = is->chapters[i], *out_ch;

        int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,

                                       AV_TIME_BASE_Q, in_ch->time_base);

        int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :

                           av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);

        if (in_ch->end < ts_off)

            continue;

        if (rt != INT64_MAX && in_ch->start > rt + ts_off)

            break;

        out_ch = av_mallocz(sizeof(AVChapter));

        if (!out_ch)

            return AVERROR(ENOMEM);

        out_ch->id        = in_ch->id;

        out_ch->time_base = in_ch->time_base;

        out_ch->start     = FFMAX(0,  in_ch->start - ts_off);

        out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);

        if (copy_metadata)

            av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);

        os->chapters[os->nb_chapters++] = out_ch;

    }

    return 0;

}


gen_intermediate_code_internal(CPUState * env, TranslationBlock * tb,

                               int search_pc)

{

    DisasContext ctx;

    target_ulong pc_start;

    static uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int i, ii;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    ctx.pc = pc_start;

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

    ctx.bstate = BS_NONE;

    ctx.sr = env->sr;

    ctx.fpscr = env->fpscr;

    ctx.memidx = (env->sr & SR_MD) ? 1 : 0;

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

       so assume it is a dynamic branch.  */

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

    ctx.tb = tb;

    ctx.singlestep_enabled = env->singlestep_enabled;

    ctx.features = env->features;

    ctx.has_movcal = (tb->flags & TB_FLAG_PENDING_MOVCA);

#ifdef DEBUG_DISAS

    qemu_log_mask(CPU_LOG_TB_CPU,

                 "------------------------------------------------\n");

    log_cpu_state_mask(CPU_LOG_TB_CPU, env, 0);

#endif

    ii = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_icount_start();

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

        if (unlikely(!TAILQ_EMPTY(&env->breakpoints))) {

            TAILQ_FOREACH(bp, &env->breakpoints, entry) {

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

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

		    tcg_gen_movi_i32(cpu_pc, ctx.pc);

		    gen_helper_debug();

		    ctx.bstate = BS_EXCP;

		    break;

		}

	    }

	}

        if (search_pc) {

            i = gen_opc_ptr - gen_opc_buf;

            if (ii < i) {

                ii++;

                while (ii < i)

                    gen_opc_instr_start[ii++] = 0;

            }

            gen_opc_pc[ii] = ctx.pc;

            gen_opc_hflags[ii] = ctx.flags;

            gen_opc_instr_start[ii] = 1;

            gen_opc_icount[ii] = num_insns;

        }

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

            gen_io_start();

#if 0

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

	fflush(stderr);

#endif

	ctx.opcode = lduw_code(ctx.pc);

	decode_opc(&ctx);

        num_insns++;

	ctx.pc += 2;

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

	    break;

	if (env->singlestep_enabled)

	    break;

        if (num_insns >= max_insns)

            break;

        if (singlestep)

            break;

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    if (env->singlestep_enabled) {

        tcg_gen_movi_i32(cpu_pc, ctx.pc);

        gen_helper_debug();

    } else {

	switch (ctx.bstate) {

        case BS_STOP:

            /* gen_op_interrupt_restart(); */

            /* fall through */

        case BS_NONE:

            if (ctx.flags) {

                gen_store_flags(ctx.flags | DELAY_SLOT_CLEARME);

	    }

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

            break;

        case BS_EXCP:

            /* gen_op_interrupt_restart(); */

            tcg_gen_exit_tb(0);

            break;

        case BS_BRANCH:

        default:

            break;

	}

    }

    gen_icount_end(tb, num_insns);

    *gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        i = gen_opc_ptr - gen_opc_buf;

        ii++;

        while (ii <= i)

            gen_opc_instr_start[ii++] = 0;

    } else {

        tb->size = ctx.pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

#ifdef SH4_DEBUG_DISAS

    qemu_log_mask(CPU_LOG_TB_IN_ASM, "\n");

#endif

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

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

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

	qemu_log("\n");

    }

#endif

}


int cpu_x86_register(X86CPU *cpu, const char *cpu_model)

{

    CPUX86State *env = &cpu->env;

    x86_def_t def1, *def = &def1;

    Error *error = NULL;

    memset(def, 0, sizeof(*def));

    if (cpu_x86_find_by_name(def, cpu_model) < 0)

        return -1;

    if (def->vendor1) {

        env->cpuid_vendor1 = def->vendor1;

        env->cpuid_vendor2 = def->vendor2;

        env->cpuid_vendor3 = def->vendor3;

    } else {

        env->cpuid_vendor1 = CPUID_VENDOR_INTEL_1;

        env->cpuid_vendor2 = CPUID_VENDOR_INTEL_2;

        env->cpuid_vendor3 = CPUID_VENDOR_INTEL_3;

    }

    env->cpuid_vendor_override = def->vendor_override;

    object_property_set_int(OBJECT(cpu), def->level, "level", &error);

    object_property_set_int(OBJECT(cpu), def->family, "family", &error);

    object_property_set_int(OBJECT(cpu), def->model, "model", &error);

    object_property_set_int(OBJECT(cpu), def->stepping, "stepping", &error);

    env->cpuid_features = def->features;

    env->cpuid_ext_features = def->ext_features;

    env->cpuid_ext2_features = def->ext2_features;

    env->cpuid_ext3_features = def->ext3_features;

    object_property_set_int(OBJECT(cpu), def->xlevel, "xlevel", &error);

    env->cpuid_kvm_features = def->kvm_features;

    env->cpuid_svm_features = def->svm_features;

    env->cpuid_ext4_features = def->ext4_features;

    env->cpuid_7_0_ebx = def->cpuid_7_0_ebx_features;

    env->cpuid_xlevel2 = def->xlevel2;

    object_property_set_int(OBJECT(cpu), (int64_t)def->tsc_khz * 1000,

                            "tsc-frequency", &error);

    /* On AMD CPUs, some CPUID[8000_0001].EDX bits must match the bits on

     * CPUID[1].EDX.

     */

    if (env->cpuid_vendor1 == CPUID_VENDOR_AMD_1 &&

            env->cpuid_vendor2 == CPUID_VENDOR_AMD_2 &&

            env->cpuid_vendor3 == CPUID_VENDOR_AMD_3) {

        env->cpuid_ext2_features &= ~CPUID_EXT2_AMD_ALIASES;

        env->cpuid_ext2_features |= (def->features & CPUID_EXT2_AMD_ALIASES);

    }

    if (!kvm_enabled()) {

        env->cpuid_features &= TCG_FEATURES;

        env->cpuid_ext_features &= TCG_EXT_FEATURES;

        env->cpuid_ext2_features &= (TCG_EXT2_FEATURES

#ifdef TARGET_X86_64

            | CPUID_EXT2_SYSCALL | CPUID_EXT2_LM

#endif

            );

        env->cpuid_ext3_features &= TCG_EXT3_FEATURES;

        env->cpuid_svm_features &= TCG_SVM_FEATURES;

    }

    object_property_set_str(OBJECT(cpu), def->model_id, "model-id", &error);

    if (error_is_set(&error)) {

        error_free(error);

        return -1;

    }

    return 0;

}


static void init_proc_e500 (CPUPPCState *env, int version)

{

    uint32_t tlbncfg[2];

    uint64_t ivor_mask = 0x0000000F0000FFFFULL;

    uint32_t l1cfg0 = 0x3800  /* 8 ways */

                    | 0x0020; /* 32 kb */

#if !defined(CONFIG_USER_ONLY)

    int i;

#endif

    /* Time base */

    gen_tbl(env);

    /*

     * XXX The e500 doesn't implement IVOR7 and IVOR9, but doesn't

     *     complain when accessing them.

     * gen_spr_BookE(env, 0x0000000F0000FD7FULL);

     */

    if (version == fsl_e500mc) {

        ivor_mask = 0x000003FE0000FFFFULL;

    }

    gen_spr_BookE(env, ivor_mask);

    /* Processor identification */

    spr_register(env, SPR_BOOKE_PIR, "PIR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_pir,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_SPEFSCR, "SPEFSCR",

                 &spr_read_spefscr, &spr_write_spefscr,

                 &spr_read_spefscr, &spr_write_spefscr,

                 0x00000000);

    /* Memory management */

#if defined(CONFIG_USER_ONLY)

    env->dcache_line_size = 32;

    env->icache_line_size = 32;

#else /* !defined(CONFIG_USER_ONLY) */

    env->nb_pids = 3;

    env->nb_ways = 2;

    env->id_tlbs = 0;

    switch (version) {

    case fsl_e500v1:

        /* e500v1 */

        tlbncfg[0] = gen_tlbncfg(2, 1, 1, 0, 256);

        tlbncfg[1] = gen_tlbncfg(16, 1, 9, TLBnCFG_AVAIL | TLBnCFG_IPROT, 16);

        env->dcache_line_size = 32;

        env->icache_line_size = 32;

        break;

    case fsl_e500v2:

        /* e500v2 */

        tlbncfg[0] = gen_tlbncfg(4, 1, 1, 0, 512);

        tlbncfg[1] = gen_tlbncfg(16, 1, 12, TLBnCFG_AVAIL | TLBnCFG_IPROT, 16);

        env->dcache_line_size = 32;

        env->icache_line_size = 32;

        break;

    case fsl_e500mc:

        /* e500mc */

        tlbncfg[0] = gen_tlbncfg(4, 1, 1, 0, 512);

        tlbncfg[1] = gen_tlbncfg(64, 1, 12, TLBnCFG_AVAIL | TLBnCFG_IPROT, 64);

        env->dcache_line_size = 64;

        env->icache_line_size = 64;

        l1cfg0 |= 0x1000000; /* 64 byte cache block size */

        break;

    default:

        cpu_abort(env, "Unknown CPU: " TARGET_FMT_lx "\n", env->spr[SPR_PVR]);

    }

#endif

    gen_spr_BookE206(env, 0x000000DF, tlbncfg);

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_BBEAR, "BBEAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_BBTAR, "BBTAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_MCAR, "MCAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_MCSR, "MCSR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_NPIDR, "NPIDR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_BUCSR, "BUCSR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_L1CFG0, "L1CFG0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 l1cfg0);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_L1CSR0, "L1CSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_e500_l1csr0,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_L1CSR1, "L1CSR1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_BOOKE_MCSRR0, "MCSRR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_BOOKE_MCSRR1, "MCSRR1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_MMUCSR0, "MMUCSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_booke206_mmucsr0,

                 0x00000000);

#if !defined(CONFIG_USER_ONLY)

    env->nb_tlb = 0;

    env->tlb_type = TLB_MAS;

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

        env->nb_tlb += booke206_tlb_size(env, i);

    }

#endif

    init_excp_e200(env);

    /* Allocate hardware IRQ controller */

    ppce500_irq_init(env);

}


int rom_copy(uint8_t *dest, target_phys_addr_t addr, size_t size)

{

    target_phys_addr_t end = addr + size;

    uint8_t *s, *d = dest;

    size_t l = 0;

    Rom *rom;

    QTAILQ_FOREACH(rom, &roms, next) {

        if (rom->fw_file) {

            continue;

        }

        if (rom->addr + rom->romsize < addr)

            continue;

        if (rom->addr > end)

            break;

        if (!rom->data)

            continue;

        d = dest + (rom->addr - addr);

        s = rom->data;

        l = rom->romsize;

        if (rom->addr < addr) {

            d = dest;

            s += (addr - rom->addr);

            l -= (addr - rom->addr);

        }

        if ((d + l) > (dest + size)) {

            l = dest - d;

        }

        memcpy(d, s, l);

    }

    return (d + l) - dest;

}


static int default_qemu_set_fd_handler2(int fd,

                                        IOCanReadHandler *fd_read_poll,

                                        IOHandler *fd_read,

                                        IOHandler *fd_write,

                                        void *opaque)

{

    abort();

}


struct omap_eac_s *omap_eac_init(struct omap_target_agent_s *ta,

                qemu_irq irq, qemu_irq *drq, omap_clk fclk, omap_clk iclk)

{

    int iomemtype;

    struct omap_eac_s *s = (struct omap_eac_s *)

            qemu_mallocz(sizeof(struct omap_eac_s));

    s->irq = irq;

    s->codec.rxdrq = *drq ++;

    s->codec.txdrq = *drq;

    omap_eac_reset(s);

#ifdef HAS_AUDIO

    AUD_register_card("OMAP EAC", &s->codec.card);

    iomemtype = cpu_register_io_memory(omap_eac_readfn,

                    omap_eac_writefn, s);

    omap_l4_attach(ta, 0, iomemtype);

#endif

    return s;

}


static void intel_hda_response(HDACodecDevice *dev, bool solicited, uint32_t response)

{

    HDACodecBus *bus = HDA_BUS(dev->qdev.parent_bus);

    IntelHDAState *d = container_of(bus, IntelHDAState, codecs);

    hwaddr addr;

    uint32_t wp, ex;

    if (d->ics & ICH6_IRS_BUSY) {

        dprint(d, 2, "%s: [irr] response 0x%x, cad 0x%x\n",

               __FUNCTION__, response, dev->cad);

        d->irr = response;

        d->ics &= ~(ICH6_IRS_BUSY | 0xf0);

        d->ics |= (ICH6_IRS_VALID | (dev->cad << 4));

        return;

    }

    if (!(d->rirb_ctl & ICH6_RBCTL_DMA_EN)) {

        dprint(d, 1, "%s: rirb dma disabled, drop codec response\n", __FUNCTION__);

        return;

    }

    ex = (solicited ? 0 : (1 << 4)) | dev->cad;

    wp = (d->rirb_wp + 1) & 0xff;

    addr = intel_hda_addr(d->rirb_lbase, d->rirb_ubase);

    stl_le_pci_dma(&d->pci, addr + 8*wp, response);

    stl_le_pci_dma(&d->pci, addr + 8*wp + 4, ex);

    d->rirb_wp = wp;

    dprint(d, 2, "%s: [wp 0x%x] response 0x%x, extra 0x%x\n",

           __FUNCTION__, wp, response, ex);

    d->rirb_count++;

    if (d->rirb_count == d->rirb_cnt) {

        dprint(d, 2, "%s: rirb count reached (%d)\n", __FUNCTION__, d->rirb_count);

        if (d->rirb_ctl & ICH6_RBCTL_IRQ_EN) {

            d->rirb_sts |= ICH6_RBSTS_IRQ;

            intel_hda_update_irq(d);

        }

    } else if ((d->corb_rp & 0xff) == d->corb_wp) {

        dprint(d, 2, "%s: corb ring empty (%d/%d)\n", __FUNCTION__,

               d->rirb_count, d->rirb_cnt);

        if (d->rirb_ctl & ICH6_RBCTL_IRQ_EN) {

            d->rirb_sts |= ICH6_RBSTS_IRQ;

            intel_hda_update_irq(d);

        }

    }

}


static void as_memory_range_add(AddressSpace *as, FlatRange *fr)

{

    ram_addr_t phys_offset, region_offset;

    memory_region_prepare_ram_addr(fr->mr);

    phys_offset = fr->mr->ram_addr;

    region_offset = fr->offset_in_region;

    /* cpu_register_physical_memory_log() wants region_offset for

     * mmio, but prefers offseting phys_offset for RAM.  Humour it.

     */

    if ((phys_offset & ~TARGET_PAGE_MASK) <= IO_MEM_ROM) {

        phys_offset += region_offset;

        region_offset = 0;

    }

    if (!fr->readable) {

        phys_offset &= ~TARGET_PAGE_MASK & ~IO_MEM_ROMD;

    }

    if (fr->readonly) {

        phys_offset |= IO_MEM_ROM;

    }

    cpu_register_physical_memory_log(int128_get64(fr->addr.start),

                                     int128_get64(fr->addr.size),

                                     phys_offset,

                                     region_offset,

                                     fr->dirty_log_mask);

}


static int flashsv_decode_frame(AVCodecContext *avctx, void *data,

                                int *got_frame, AVPacket *avpkt)

{

    int buf_size = avpkt->size;

    FlashSVContext *s = avctx->priv_data;

    int h_blocks, v_blocks, h_part, v_part, i, j, ret;

    GetBitContext gb;

    /* no supplementary picture */

    if (buf_size == 0)

        return 0;

    if (buf_size < 4)

        return -1;

    init_get_bits(&gb, avpkt->data, buf_size * 8);

    /* start to parse the bitstream */

    s->block_width  = 16 * (get_bits(&gb, 4) + 1);

    s->image_width  = get_bits(&gb, 12);

    s->block_height = 16 * (get_bits(&gb, 4) + 1);

    s->image_height = get_bits(&gb, 12);

    if (s->ver == 2) {

        skip_bits(&gb, 6);

        if (get_bits1(&gb)) {

            avpriv_request_sample(avctx, "iframe");

            return AVERROR_PATCHWELCOME;

        }

        if (get_bits1(&gb)) {

            avpriv_request_sample(avctx, "Custom palette");

            return AVERROR_PATCHWELCOME;

        }

    }

    /* calculate number of blocks and size of border (partial) blocks */

    h_blocks = s->image_width  / s->block_width;

    h_part   = s->image_width  % s->block_width;

    v_blocks = s->image_height / s->block_height;

    v_part   = s->image_height % s->block_height;

    /* the block size could change between frames, make sure the buffer

     * is large enough, if not, get a larger one */

    if (s->block_size < s->block_width * s->block_height) {

        int tmpblock_size = 3 * s->block_width * s->block_height, err;

        if ((err = av_reallocp(&s->tmpblock, tmpblock_size)) < 0) {

            s->block_size = 0;

            av_log(avctx, AV_LOG_ERROR,

                   "Cannot allocate decompression buffer.\n");

            return err;

        }

        if (s->ver == 2) {

            s->deflate_block_size = calc_deflate_block_size(tmpblock_size);

            if (s->deflate_block_size <= 0) {

                av_log(avctx, AV_LOG_ERROR,

                       "Cannot determine deflate buffer size.\n");

                return -1;

            }

            if ((err = av_reallocp(&s->deflate_block, s->deflate_block_size)) < 0) {

                s->block_size = 0;

                av_log(avctx, AV_LOG_ERROR, "Cannot allocate deflate buffer.\n");

                return err;

            }

        }

    }

    s->block_size = s->block_width * s->block_height;

    /* initialize the image size once */

    if (avctx->width == 0 && avctx->height == 0) {

        avctx->width  = s->image_width;

        avctx->height = s->image_height;

    }

    /* check for changes of image width and image height */

    if (avctx->width != s->image_width || avctx->height != s->image_height) {

        av_log(avctx, AV_LOG_ERROR,

               "Frame width or height differs from first frame!\n");

        av_log(avctx, AV_LOG_ERROR, "fh = %d, fv %d  vs  ch = %d, cv = %d\n",

               avctx->height, avctx->width, s->image_height, s->image_width);

        return AVERROR_INVALIDDATA;

    }

    /* we care for keyframes only in Screen Video v2 */

    s->is_keyframe = (avpkt->flags & AV_PKT_FLAG_KEY) && (s->ver == 2);

    if (s->is_keyframe) {

        int err;

        if ((err = av_reallocp(&s->keyframedata, avpkt->size)) < 0)

            return err;

        memcpy(s->keyframedata, avpkt->data, avpkt->size);

        if ((err = av_reallocp(&s->blocks, (v_blocks + !!v_part) *

                               (h_blocks + !!h_part) * sizeof(s->blocks[0]))) < 0)

            return err;

    }

    ff_dlog(avctx, "image: %dx%d block: %dx%d num: %dx%d part: %dx%d\n",

            s->image_width, s->image_height, s->block_width, s->block_height,

            h_blocks, v_blocks, h_part, v_part);

    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) {

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

        return ret;

    }

    /* loop over all block columns */

    for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {

        int y_pos  = j * s->block_height; // vertical position in frame

        int cur_blk_height = (j < v_blocks) ? s->block_height : v_part;

        /* loop over all block rows */

        for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {

            int x_pos = i * s->block_width; // horizontal position in frame

            int cur_blk_width = (i < h_blocks) ? s->block_width : h_part;

            int has_diff = 0;

            /* get the size of the compressed zlib chunk */

            int size = get_bits(&gb, 16);

            s->color_depth    = 0;

            s->zlibprime_curr = 0;

            s->zlibprime_prev = 0;

            s->diff_start     = 0;

            s->diff_height    = cur_blk_height;

            if (8 * size > get_bits_left(&gb)) {

                av_frame_unref(s->frame);

                return AVERROR_INVALIDDATA;

            }

            if (s->ver == 2 && size) {

                skip_bits(&gb, 3);

                s->color_depth    = get_bits(&gb, 2);

                has_diff          = get_bits1(&gb);

                s->zlibprime_curr = get_bits1(&gb);

                s->zlibprime_prev = get_bits1(&gb);

                if (s->color_depth != 0 && s->color_depth != 2) {

                    av_log(avctx, AV_LOG_ERROR,

                           "%dx%d invalid color depth %d\n",

                           i, j, s->color_depth);

                    return AVERROR_INVALIDDATA;

                }

                if (has_diff) {

                    if (!s->keyframe) {

                        av_log(avctx, AV_LOG_ERROR,

                               "Inter frame without keyframe\n");

                        return AVERROR_INVALIDDATA;

                    }

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

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

                    if (s->diff_start + s->diff_height > cur_blk_height) {

                        av_log(avctx, AV_LOG_ERROR,

                               "Block parameters invalid: %d + %d > %d\n",

                               s->diff_start, s->diff_height, cur_blk_height);

                        return AVERROR_INVALIDDATA;

                    }

                    av_log(avctx, AV_LOG_DEBUG,

                           "%dx%d diff start %d height %d\n",

                           i, j, s->diff_start, s->diff_height);

                    size -= 2;

                }

                if (s->zlibprime_prev)

                    av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_prev\n", i, j);

                if (s->zlibprime_curr) {

                    int col = get_bits(&gb, 8);

                    int row = get_bits(&gb, 8);

                    av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_curr %dx%d\n",

                           i, j, col, row);

                    size -= 2;

                    avpriv_request_sample(avctx, "zlibprime_curr");

                    return AVERROR_PATCHWELCOME;

                }

                if (!s->blocks && (s->zlibprime_curr || s->zlibprime_prev)) {

                    av_log(avctx, AV_LOG_ERROR,

                           "no data available for zlib priming\n");

                    return AVERROR_INVALIDDATA;

                }

                size--; // account for flags byte

            }

            if (has_diff) {

                int k;

                int off = (s->image_height - y_pos - 1) * s->frame->linesize[0];

                for (k = 0; k < cur_blk_height; k++) {

                    int x = off - k * s->frame->linesize[0] + x_pos * 3;

                    memcpy(s->frame->data[0] + x, s->keyframe + x,

                           cur_blk_width * 3);

                }

            }

            /* skip unchanged blocks, which have size 0 */

            if (size) {

                if (flashsv_decode_block(avctx, avpkt, &gb, size,

                                         cur_blk_width, cur_blk_height,

                                         x_pos, y_pos,

                                         i + j * (h_blocks + !!h_part)))

                    av_log(avctx, AV_LOG_ERROR,

                           "error in decompression of block %dx%d\n", i, j);

            }

        }

    }

    if (s->is_keyframe && s->ver == 2) {

        if (!s->keyframe) {

            s->keyframe = av_malloc(s->frame->linesize[0] * avctx->height);

            if (!s->keyframe) {

                av_log(avctx, AV_LOG_ERROR, "Cannot allocate image data\n");

                return AVERROR(ENOMEM);

            }

        }

        memcpy(s->keyframe, s->frame->data[0],

               s->frame->linesize[0] * avctx->height);

    }

    if ((ret = av_frame_ref(data, s->frame)) < 0)

        return ret;

    *got_frame = 1;

    if ((get_bits_count(&gb) / 8) != buf_size)

        av_log(avctx, AV_LOG_ERROR, "buffer not fully consumed (%d != %d)\n",

               buf_size, (get_bits_count(&gb) / 8));

    /* report that the buffer was completely consumed */

    return buf_size;

}


static void t_gen_mulu(TCGv d, TCGv d2, TCGv a, TCGv b)

{

	TCGv t0, t1;

	t0 = tcg_temp_new(TCG_TYPE_I64);

	t1 = tcg_temp_new(TCG_TYPE_I64);

	tcg_gen_extu_i32_i64(t0, a);

	tcg_gen_extu_i32_i64(t1, b);

	tcg_gen_mul_i64(t0, t0, t1);

	tcg_gen_trunc_i64_i32(d, t0);

	tcg_gen_shri_i64(t0, t0, 32);

	tcg_gen_trunc_i64_i32(d2, t0);

	tcg_temp_free(t0);

	tcg_temp_free(t1);

}


static int pte64_check(struct mmu_ctx_hash64 *ctx, target_ulong pte0,

                       target_ulong pte1, int h, int rw, int type)

{

    target_ulong mmask;

    int access, ret, pp;

    ret = -1;

    /* Check validity and table match */

    if ((pte0 & HPTE64_V_VALID) && (h == !!(pte0 & HPTE64_V_SECONDARY))) {

        /* Check vsid & api */

        mmask = PTE64_CHECK_MASK;

        pp = (pte1 & HPTE64_R_PP) | ((pte1 & HPTE64_R_PP0) >> 61);

        /* No execute if either noexec or guarded bits set */

        ctx->nx = (pte1 & HPTE64_R_N) || (pte1 & HPTE64_R_G);

        if (HPTE64_V_COMPARE(pte0, ctx->ptem)) {

            if (ctx->raddr != (hwaddr)-1ULL) {

                /* all matches should have equal RPN, WIMG & PP */

                if ((ctx->raddr & mmask) != (pte1 & mmask)) {

                    qemu_log("Bad RPN/WIMG/PP\n");

                    return -3;

                }

            }

            /* Compute access rights */

            access = ppc_hash64_pp_check(ctx->key, pp, ctx->nx);

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            ret = ppc_hash64_check_prot(ctx->prot, rw, type);

            if (ret == 0) {

                /* Access granted */

                LOG_MMU("PTE access granted !\n");

            } else {

                /* Access right violation */

                LOG_MMU("PTE access rejected\n");

            }

        }

    }

    return ret;

}


static void coroutine_fn nest(void *opaque)

{

    NestData *nd = opaque;

    nd->n_enter++;

    if (nd->n_enter < nd->max) {

        Coroutine *child;

        child = qemu_coroutine_create(nest);

        qemu_coroutine_enter(child, nd);

    }

    nd->n_return++;

}


static int vp8_lossless_decode_frame(AVCodecContext *avctx, AVFrame *p,

                                     int *got_frame, uint8_t *data_start,

                                     unsigned int data_size, int is_alpha_chunk)

{

    WebPContext *s = avctx->priv_data;

    int w, h, ret, i;

    if (!is_alpha_chunk) {

        s->lossless = 1;

        avctx->pix_fmt = AV_PIX_FMT_ARGB;

    }

    ret = init_get_bits8(&s->gb, data_start, data_size);

    if (ret < 0)

        return ret;

    if (!is_alpha_chunk) {

        if (get_bits(&s->gb, 8) != 0x2F) {

            av_log(avctx, AV_LOG_ERROR, "Invalid WebP Lossless signature\n");

            return AVERROR_INVALIDDATA;

        }

        w = get_bits(&s->gb, 14) + 1;

        h = get_bits(&s->gb, 14) + 1;

        if (s->width && s->width != w) {

            av_log(avctx, AV_LOG_WARNING, "Width mismatch. %d != %d\n",

                   s->width, w);

        }

        s->width = w;

        if (s->height && s->height != h) {

            av_log(avctx, AV_LOG_WARNING, "Height mismatch. %d != %d\n",

                   s->width, w);

        }

        s->height = h;

        ret = ff_set_dimensions(avctx, s->width, s->height);

        if (ret < 0)

            return ret;

        s->has_alpha = get_bits1(&s->gb);

        if (get_bits(&s->gb, 3) != 0x0) {

            av_log(avctx, AV_LOG_ERROR, "Invalid WebP Lossless version\n");

            return AVERROR_INVALIDDATA;

        }

    } else {

        if (!s->width || !s->height)

            return AVERROR_BUG;

        w = s->width;

        h = s->height;

    }

    /* parse transformations */

    s->nb_transforms = 0;

    s->reduced_width = 0;

    while (get_bits1(&s->gb)) {

        enum TransformType transform = get_bits(&s->gb, 2);

        s->transforms[s->nb_transforms++] = transform;

        switch (transform) {

        case PREDICTOR_TRANSFORM:

            ret = parse_transform_predictor(s);

            break;

        case COLOR_TRANSFORM:

            ret = parse_transform_color(s);

            break;

        case COLOR_INDEXING_TRANSFORM:

            ret = parse_transform_color_indexing(s);

            break;

        }

        if (ret < 0)

            goto free_and_return;

    }

    /* decode primary image */

    s->image[IMAGE_ROLE_ARGB].frame = p;

    if (is_alpha_chunk)

        s->image[IMAGE_ROLE_ARGB].is_alpha_primary = 1;

    ret = decode_entropy_coded_image(s, IMAGE_ROLE_ARGB, w, h);

    if (ret < 0)

        goto free_and_return;

    /* apply transformations */

    for (i = s->nb_transforms - 1; i >= 0; i--) {

        switch (s->transforms[i]) {

        case PREDICTOR_TRANSFORM:

            ret = apply_predictor_transform(s);

            break;

        case COLOR_TRANSFORM:

            ret = apply_color_transform(s);

            break;

        case SUBTRACT_GREEN:

            ret = apply_subtract_green_transform(s);

            break;

        case COLOR_INDEXING_TRANSFORM:

            ret = apply_color_indexing_transform(s);

            break;

        }

        if (ret < 0)

            goto free_and_return;

    }

    *got_frame   = 1;

    p->pict_type = AV_PICTURE_TYPE_I;

    p->key_frame = 1;

    ret          = data_size;

free_and_return:

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

        image_ctx_free(&s->image[i]);

    return ret;

}


static int check_bd(VIOsPAPRVLANDevice *dev, vlan_bd_t bd,

                    target_ulong alignment)

{

    if ((VLAN_BD_ADDR(bd) % alignment)

        || (VLAN_BD_LEN(bd) % alignment)) {

        return -1;

    }

    if (spapr_vio_check_tces(&dev->sdev, VLAN_BD_ADDR(bd),

                             VLAN_BD_LEN(bd), SPAPR_TCE_RW) != 0) {

        return -1;

    }

    return 0;

}


int kvm_arm_sync_mpstate_to_qemu(ARMCPU *cpu)

{

    if (cap_has_mp_state) {

        struct kvm_mp_state mp_state;

        int ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MP_STATE, &mp_state);

        if (ret) {

            fprintf(stderr, "%s: failed to get MP_STATE %d/%s\n",

                    __func__, ret, strerror(-ret));

            abort();

        }

        cpu->powered_off = (mp_state.mp_state == KVM_MP_STATE_STOPPED);

    }

    return 0;

}


static int a64_write_packet(struct AVFormatContext *s, AVPacket *pkt)

{

    AVCodecContext *avctx = s->streams[0]->codec;

    A64MuxerContext *c = s->priv_data;

    int i, j;

    int ch_chunksize;

    int lifetime;

    int frame_count;

    int charset_size;

    int frame_size;

    int num_frames;

    /* fetch values from extradata */

    switch (avctx->codec->id) {

    case CODEC_ID_A64_MULTI:

    case CODEC_ID_A64_MULTI5:

        if(c->interleaved) {

            /* Write interleaved, means we insert chunks of the future charset before each current frame.

             * Reason: if we load 1 charset + corresponding frames in one block on c64, we need to store

             * them first and then display frame by frame to keep in sync. Thus we would read and write

             * the data for colram from/to ram first and waste too much time. If we interleave and send the

             * charset beforehand, we assemble a new charset chunk by chunk, write current screen data to

             * screen-ram to be displayed and decode the colram directly to colram-location $d800 during

             * the overscan, while reading directly from source

             * This is the only way so far, to achieve 25fps on c64 */

            if(avctx->extradata) {

                /* fetch values from extradata */

                lifetime     = AV_RB32(avctx->extradata + 0);

                frame_count  = AV_RB32(avctx->extradata + 4);

                charset_size = AV_RB32(avctx->extradata + 8);

                frame_size   = AV_RB32(avctx->extradata + 12);

                /* TODO: sanity checks? */

            }

            else {

                av_log(avctx, AV_LOG_ERROR, "extradata not set\n");

                return AVERROR(EINVAL);

            }

            ch_chunksize=charset_size/lifetime;

            /* TODO: check if charset/size is % lifetime, but maybe check in codec */

            if(pkt->data) num_frames = lifetime;

            else num_frames = c->prev_frame_count;

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

                if(pkt->data) {

                    /* if available, put newest charset chunk into buffer */

                    put_buffer(s->pb, pkt->data + ch_chunksize * i, ch_chunksize);

                }

                else {

                    /* a bit ugly, but is there an alternative to put many zeros? */

                    for(j = 0; j < ch_chunksize; j++) put_byte(s->pb, 0);

                }

                if(c->prev_pkt.data) {

                    /* put frame (screen + colram) from last packet into buffer */

                    put_buffer(s->pb, c->prev_pkt.data + charset_size + frame_size * i, frame_size);

                }

                else {

                    /* a bit ugly, but is there an alternative to put many zeros? */

                    for(j = 0; j < frame_size; j++) put_byte(s->pb, 0);

                }

            }

            /* backup current packet for next turn */

            if(pkt->data) {

                av_new_packet(&c->prev_pkt, pkt->size);

                memcpy(c->prev_pkt.data, pkt->data, pkt->size);

            }

            c->prev_frame_count = frame_count;

            break;

        }

        default:

            /* Write things as is. Nice for self-contained frames from non-multicolor modes or if played

             * directly from ram and not from a streaming device (rrnet/mmc) */

            if(pkt) put_buffer(s->pb, pkt->data, pkt->size);

        break;

    }

    put_flush_packet(s->pb);

    return 0;

}


static int decode_pce(AACContext * ac, enum ChannelPosition new_che_pos[4][MAX_ELEM_ID],

        GetBitContext * gb) {

    int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc;

    skip_bits(gb, 2);  // object_type

    ac->m4ac.sampling_index = get_bits(gb, 4);

    if(ac->m4ac.sampling_index > 11) {

        av_log(ac->avccontext, AV_LOG_ERROR, "invalid sampling rate index %d\n", ac->m4ac.sampling_index);

        return -1;

    }

    ac->m4ac.sample_rate = ff_mpeg4audio_sample_rates[ac->m4ac.sampling_index];

    num_front       = get_bits(gb, 4);

    num_side        = get_bits(gb, 4);

    num_back        = get_bits(gb, 4);

    num_lfe         = get_bits(gb, 2);

    num_assoc_data  = get_bits(gb, 3);

    num_cc          = get_bits(gb, 4);

    if (get_bits1(gb))

        skip_bits(gb, 4); // mono_mixdown_tag

    if (get_bits1(gb))

        skip_bits(gb, 4); // stereo_mixdown_tag

    if (get_bits1(gb))

        skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround

    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_FRONT, gb, num_front);

    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_SIDE,  gb, num_side );

    decode_channel_map(new_che_pos[TYPE_CPE], new_che_pos[TYPE_SCE], AAC_CHANNEL_BACK,  gb, num_back );

    decode_channel_map(NULL,                  new_che_pos[TYPE_LFE], AAC_CHANNEL_LFE,   gb, num_lfe  );

    skip_bits_long(gb, 4 * num_assoc_data);

    decode_channel_map(new_che_pos[TYPE_CCE], new_che_pos[TYPE_CCE], AAC_CHANNEL_CC,    gb, num_cc   );

    align_get_bits(gb);

    /* comment field, first byte is length */

    skip_bits_long(gb, 8 * get_bits(gb, 8));

    return 0;

}


void start_ahci_device(AHCIQState *ahci)

{

    /* Map AHCI's ABAR (BAR5) */

    ahci->hba_base = qpci_iomap(ahci->dev, 5, &ahci->barsize);

    g_assert(ahci->hba_base);

    /* turns on pci.cmd.iose, pci.cmd.mse and pci.cmd.bme */

    qpci_device_enable(ahci->dev);

}


void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)

{

    balloon_event_fn = func;

    balloon_opaque = opaque;

}


void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd)

{

    qemu_mutex_init(&ssd->lock);

    QTAILQ_INIT(&ssd->updates);

    ssd->mouse_x = -1;

    ssd->mouse_y = -1;

    if (ssd->num_surfaces == 0) {

        ssd->num_surfaces = 1024;

    }

    ssd->bufsize = (16 * 1024 * 1024);

    ssd->buf = g_malloc(ssd->bufsize);

}


static av_cold int sonic_decode_init(AVCodecContext *avctx)

{

    SonicContext *s = avctx->priv_data;

    GetBitContext gb;

    int i;

    s->channels = avctx->channels;

    s->samplerate = avctx->sample_rate;

    if (!avctx->extradata)

    {

        av_log(avctx, AV_LOG_ERROR, "No mandatory headers present\n");

        return AVERROR_INVALIDDATA;

    }

    init_get_bits8(&gb, avctx->extradata, avctx->extradata_size);

    s->version = get_bits(&gb, 2);

    if (s->version >= 2) {

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

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

    }

    if (s->version != 2)

    {

        av_log(avctx, AV_LOG_ERROR, "Unsupported Sonic version, please report\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->version >= 1)

    {

        int sample_rate_index;

        s->channels = get_bits(&gb, 2);

        sample_rate_index = get_bits(&gb, 4);

        if (sample_rate_index >= FF_ARRAY_ELEMS(samplerate_table)) {

            av_log(avctx, AV_LOG_ERROR, "Invalid sample_rate_index %d\n", sample_rate_index);

            return AVERROR_INVALIDDATA;

        }

        s->samplerate = samplerate_table[sample_rate_index];

        av_log(avctx, AV_LOG_INFO, "Sonicv2 chans: %d samprate: %d\n",

            s->channels, s->samplerate);

    }

    if (s->channels > MAX_CHANNELS || s->channels < 1)

    {

        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");

        return AVERROR_INVALIDDATA;

    }

    s->lossless = get_bits1(&gb);

    if (!s->lossless)

        skip_bits(&gb, 3); // XXX FIXME

    s->decorrelation = get_bits(&gb, 2);

    if (s->decorrelation != 3 && s->channels != 2) {

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

        return AVERROR_INVALIDDATA;

    }

    s->downsampling = get_bits(&gb, 2);

    if (!s->downsampling) {

        av_log(avctx, AV_LOG_ERROR, "invalid downsampling value\n");

        return AVERROR_INVALIDDATA;

    }

    s->num_taps = (get_bits(&gb, 5)+1)<<5;

    if (get_bits1(&gb)) // XXX FIXME

        av_log(avctx, AV_LOG_INFO, "Custom quant table\n");

    s->block_align = 2048LL*s->samplerate/(44100*s->downsampling);

    s->frame_size = s->channels*s->block_align*s->downsampling;

//    avctx->frame_size = s->block_align;

    av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d.%d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",

        s->version, s->minor_version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);

    // generate taps

    s->tap_quant = av_calloc(s->num_taps, sizeof(*s->tap_quant));

    if (!s->tap_quant)

        return AVERROR(ENOMEM);

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

        s->tap_quant[i] = ff_sqrt(i+1);

    s->predictor_k = av_calloc(s->num_taps, sizeof(*s->predictor_k));

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

    {

        s->predictor_state[i] = av_calloc(s->num_taps, sizeof(**s->predictor_state));

        if (!s->predictor_state[i])

            return AVERROR(ENOMEM);

    }

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

    {

        s->coded_samples[i] = av_calloc(s->block_align, sizeof(**s->coded_samples));

        if (!s->coded_samples[i])

            return AVERROR(ENOMEM);

    }

    s->int_samples = av_calloc(s->frame_size, sizeof(*s->int_samples));

    if (!s->int_samples)

        return AVERROR(ENOMEM);

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    return 0;

}


static void init_vlcs(FourXContext *f){

    static int done = 0;

    int i;

    if (!done) {

        done = 1;

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

            init_vlc(&block_type_vlc[i], BLOCK_TYPE_VLC_BITS, 7,

                     &block_type_tab[i][0][1], 2, 1,

                     &block_type_tab[i][0][0], 2, 1);

        }

    }

}


static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,

                                 unsigned int y, unsigned int width, unsigned int height,

                                 const uint8_t yuva_color[4], int hsub, int vsub)

{

    int r, c, alpha;

    unsigned int luma_pos, chroma_pos1, chroma_pos2;

    uint8_t src_val;

    for (r = 0; r < bitmap->rows && r+y < height; r++) {

        for (c = 0; c < bitmap->width && c+x < width; c++) {

            /* get intensity value in the glyph bitmap (source) */

            src_val = GET_BITMAP_VAL(r, c);

            if (!src_val)

                continue;

            SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);

        }

    }

    return 0;

}


static void remote_block_to_network(RDMARemoteBlock *rb)

{

    rb->remote_host_addr = htonll(rb->remote_host_addr);

    rb->offset = htonll(rb->offset);

    rb->length = htonll(rb->length);

    rb->remote_rkey = htonl(rb->remote_rkey);

}


int clp_service_call(S390CPU *cpu, uint8_t r2)

{

    ClpReqHdr *reqh;

    ClpRspHdr *resh;

    S390PCIBusDevice *pbdev;

    uint32_t req_len;

    uint32_t res_len;

    uint8_t buffer[4096 * 2];

    uint8_t cc = 0;

    CPUS390XState *env = &cpu->env;

    int i;

    cpu_synchronize_state(CPU(cpu));

    if (env->psw.mask & PSW_MASK_PSTATE) {

        program_interrupt(env, PGM_PRIVILEGED, 4);

        return 0;

    }

    if (s390_cpu_virt_mem_read(cpu, env->regs[r2], r2, buffer, sizeof(*reqh))) {

        return 0;

    }

    reqh = (ClpReqHdr *)buffer;

    req_len = lduw_p(&reqh->len);

    if (req_len < 16 || req_len > 8184 || (req_len % 8 != 0)) {

        program_interrupt(env, PGM_OPERAND, 4);

        return 0;

    }

    if (s390_cpu_virt_mem_read(cpu, env->regs[r2], r2, buffer,

                               req_len + sizeof(*resh))) {

        return 0;

    }

    resh = (ClpRspHdr *)(buffer + req_len);

    res_len = lduw_p(&resh->len);

    if (res_len < 8 || res_len > 8176 || (res_len % 8 != 0)) {

        program_interrupt(env, PGM_OPERAND, 4);

        return 0;

    }

    if ((req_len + res_len) > 8192) {

        program_interrupt(env, PGM_OPERAND, 4);

        return 0;

    }

    if (s390_cpu_virt_mem_read(cpu, env->regs[r2], r2, buffer,

                               req_len + res_len)) {

        return 0;

    }

    if (req_len != 32) {

        stw_p(&resh->rsp, CLP_RC_LEN);

        goto out;

    }

    switch (lduw_p(&reqh->cmd)) {

    case CLP_LIST_PCI: {

        ClpReqRspListPci *rrb = (ClpReqRspListPci *)buffer;

        list_pci(rrb, &cc);

        break;

    }

    case CLP_SET_PCI_FN: {

        ClpReqSetPci *reqsetpci = (ClpReqSetPci *)reqh;

        ClpRspSetPci *ressetpci = (ClpRspSetPci *)resh;

        pbdev = s390_pci_find_dev_by_fh(ldl_p(&reqsetpci->fh));

        if (!pbdev) {

                stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FH);

                goto out;

        }

        switch (reqsetpci->oc) {

        case CLP_SET_ENABLE_PCI_FN:

            pbdev->fh |= FH_MASK_ENABLE;

            pbdev->state = ZPCI_FS_ENABLED;

            stl_p(&ressetpci->fh, pbdev->fh);

            stw_p(&ressetpci->hdr.rsp, CLP_RC_OK);

            break;

        case CLP_SET_DISABLE_PCI_FN:

            pbdev->fh &= ~FH_MASK_ENABLE;

            pbdev->state = ZPCI_FS_DISABLED;

            stl_p(&ressetpci->fh, pbdev->fh);

            stw_p(&ressetpci->hdr.rsp, CLP_RC_OK);

            break;

        default:

            DPRINTF("unknown set pci command\n");

            stw_p(&ressetpci->hdr.rsp, CLP_RC_SETPCIFN_FHOP);

            break;

        }

        break;

    }

    case CLP_QUERY_PCI_FN: {

        ClpReqQueryPci *reqquery = (ClpReqQueryPci *)reqh;

        ClpRspQueryPci *resquery = (ClpRspQueryPci *)resh;

        pbdev = s390_pci_find_dev_by_fh(ldl_p(&reqquery->fh));

        if (!pbdev) {

            DPRINTF("query pci no pci dev\n");

            stw_p(&resquery->hdr.rsp, CLP_RC_SETPCIFN_FH);

            goto out;

        }

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

            uint32_t data = pci_get_long(pbdev->pdev->config +

                PCI_BASE_ADDRESS_0 + (i * 4));

            stl_p(&resquery->bar[i], data);

            resquery->bar_size[i] = pbdev->pdev->io_regions[i].size ?

                                    ctz64(pbdev->pdev->io_regions[i].size) : 0;

            DPRINTF("bar %d addr 0x%x size 0x%" PRIx64 "barsize 0x%x\n", i,

                    ldl_p(&resquery->bar[i]),

                    pbdev->pdev->io_regions[i].size,

                    resquery->bar_size[i]);

        }

        stq_p(&resquery->sdma, ZPCI_SDMA_ADDR);

        stq_p(&resquery->edma, ZPCI_EDMA_ADDR);

        stl_p(&resquery->fid, pbdev->fid);

        stw_p(&resquery->pchid, 0);

        stw_p(&resquery->ug, 1);

        stl_p(&resquery->uid, pbdev->fid);

        stw_p(&resquery->hdr.rsp, CLP_RC_OK);

        break;

    }

    case CLP_QUERY_PCI_FNGRP: {

        ClpRspQueryPciGrp *resgrp = (ClpRspQueryPciGrp *)resh;

        resgrp->fr = 1;

        stq_p(&resgrp->dasm, 0);

        stq_p(&resgrp->msia, ZPCI_MSI_ADDR);

        stw_p(&resgrp->mui, 0);

        stw_p(&resgrp->i, 128);

        resgrp->version = 0;

        stw_p(&resgrp->hdr.rsp, CLP_RC_OK);

        break;

    }

    default:

        DPRINTF("unknown clp command\n");

        stw_p(&resh->rsp, CLP_RC_CMD);

        break;

    }

out:

    if (s390_cpu_virt_mem_write(cpu, env->regs[r2], r2, buffer,

                                req_len + res_len)) {

        return 0;

    }

    setcc(cpu, cc);

    return 0;

}