target_ulong do_load_msr (CPUPPCState *env)

{

    return

#if defined (TARGET_PPC64)

        ((target_ulong)msr_sf   << MSR_SF)   |

        ((target_ulong)msr_isf  << MSR_ISF)  |

        ((target_ulong)msr_hv   << MSR_HV)   |

#endif

        ((target_ulong)msr_ucle << MSR_UCLE) |

        ((target_ulong)msr_vr   << MSR_VR)   | /* VR / SPE */

        ((target_ulong)msr_ap   << MSR_AP)   |

        ((target_ulong)msr_sa   << MSR_SA)   |

        ((target_ulong)msr_key  << MSR_KEY)  |

        ((target_ulong)msr_pow  << MSR_POW)  | /* POW / WE */

        ((target_ulong)msr_tgpr << MSR_TGPR) | /* TGPR / CE */

        ((target_ulong)msr_ile  << MSR_ILE)  |

        ((target_ulong)msr_ee   << MSR_EE)   |

        ((target_ulong)msr_pr   << MSR_PR)   |

        ((target_ulong)msr_fp   << MSR_FP)   |

        ((target_ulong)msr_me   << MSR_ME)   |

        ((target_ulong)msr_fe0  << MSR_FE0)  |

        ((target_ulong)msr_se   << MSR_SE)   | /* SE / DWE / UBLE */

        ((target_ulong)msr_be   << MSR_BE)   | /* BE / DE */

        ((target_ulong)msr_fe1  << MSR_FE1)  |

        ((target_ulong)msr_al   << MSR_AL)   |

        ((target_ulong)msr_ip   << MSR_IP)   |

        ((target_ulong)msr_ir   << MSR_IR)   | /* IR / IS */

        ((target_ulong)msr_dr   << MSR_DR)   | /* DR / DS */

        ((target_ulong)msr_pe   << MSR_PE)   | /* PE / EP */

        ((target_ulong)msr_px   << MSR_PX)   | /* PX / PMM */

        ((target_ulong)msr_ri   << MSR_RI)   |

        ((target_ulong)msr_le   << MSR_LE);

}


static void unpack_alpha(GetBitContext *gb, uint16_t *dst, int num_coeffs,

                         const int num_bits)

{

    const int mask = (1 << num_bits) - 1;

    int i, idx, val, alpha_val;

    idx       = 0;

    alpha_val = mask;

    do {

        do {

            if (get_bits1(gb))

                val = get_bits(gb, num_bits);

            else {

                int sign;

                val  = get_bits(gb, num_bits == 16 ? 7 : 4);

                sign = val & 1;

                val  = (val + 2) >> 1;

                if (sign)

                    val = -val;

            }

            alpha_val = (alpha_val + val) & mask;

            if (num_bits == 16)

                dst[idx++] = alpha_val >> 6;

            else

                dst[idx++] = (alpha_val << 2) | (alpha_val >> 6);

            if (idx == num_coeffs - 1)

                break;

        } while (get_bits1(gb));

        val = get_bits(gb, 4);

        if (!val)

            val = get_bits(gb, 11);

        if (idx + val > num_coeffs)

            val = num_coeffs - idx;

        if (num_bits == 16)

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

                dst[idx++] = alpha_val >> 6;

        else

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

                dst[idx++] = (alpha_val << 2) | (alpha_val >> 6);

    } while (idx < num_coeffs);

}


bool desc_ring_set_size(DescRing *ring, uint32_t size)

{

    int i;

    if (size < 2 || size > 0x10000 || (size & (size - 1))) {

        DPRINTF("ERROR: ring[%d] size (%d) not a power of 2 "

                "or in range [2, 64K]\n", ring->index, size);

        return false;

    }

    for (i = 0; i < ring->size; i++) {

        g_free(ring->info[i].buf);

    }

    ring->size = size;

    ring->head = ring->tail = 0;

    ring->info = g_realloc(ring->info, size * sizeof(DescInfo));

    if (!ring->info) {

        return false;

    }

    memset(ring->info, 0, size * sizeof(DescInfo));

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

        ring->info[i].ring = ring;

    }

    return true;

}


static void gen_wsr_windowstart(DisasContext *dc, uint32_t sr, TCGv_i32 v)

{

    tcg_gen_andi_i32(cpu_SR[sr], v, (1 << dc->config->nareg / 4) - 1);

    reset_used_window(dc);

}


static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)

{

    int ret;

    ret = laiocb->ret;

    if (ret != -ECANCELED) {

        if (ret == laiocb->nbytes) {

            ret = 0;

        } else if (ret >= 0) {

            /* Short reads mean EOF, pad with zeros. */

            if (laiocb->is_read) {

                qemu_iovec_memset(laiocb->qiov, ret, 0,

                    laiocb->qiov->size - ret);

            } else {

                ret = -ENOSPC;

            }

        }

    }

    laiocb->ret = ret;

    if (laiocb->co) {

        /* Jump and continue completion for foreign requests, don't do

         * anything for current request, it will be completed shortly. */

        if (laiocb->co != qemu_coroutine_self()) {

            qemu_coroutine_enter(laiocb->co);

        }

    } else {

        laiocb->common.cb(laiocb->common.opaque, ret);

        qemu_aio_unref(laiocb);

    }

}


static uint32_t msix_mmio_readl(void *opaque, target_phys_addr_t addr)

{

    PCIDevice *dev = opaque;

    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1);

    void *page = dev->msix_table_page;

    uint32_t val = 0;

    memcpy(&val, (void *)((char *)page + offset), 4);

    return val;

}


int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)

{

    int ret;

    if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))

        return AVERROR(EINVAL);

    if (avctx->internal->draining)

        return AVERROR_EOF;

    if (!avpkt || !avpkt->size) {

        avctx->internal->draining = 1;

        avpkt = NULL;

        if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))

            return 0;

    }

    if (avctx->codec->send_packet) {

        if (avpkt) {

            ret = apply_param_change(avctx, (AVPacket *)avpkt);

            if (ret < 0)

                return ret;

        }

        return avctx->codec->send_packet(avctx, avpkt);

    }

    // Emulation via old API. Assume avpkt is likely not refcounted, while

    // decoder output is always refcounted, and avoid copying.

    if (avctx->internal->buffer_pkt->size || avctx->internal->buffer_frame->buf[0])

        return AVERROR(EAGAIN);

    // The goal is decoding the first frame of the packet without using memcpy,

    // because the common case is having only 1 frame per packet (especially

    // with video, but audio too). In other cases, it can't be avoided, unless

    // the user is feeding refcounted packets.

    return do_decode(avctx, (AVPacket *)avpkt);

}


static int asf_read_stream_properties(AVFormatContext *s, const GUIDParseTable *g)

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    uint64_t size;

    uint32_t err_data_len, ts_data_len; // type specific data length

    uint16_t flags;

    ff_asf_guid stream_type;

    enum AVMediaType type;

    int i, ret;

    uint8_t stream_index;

    AVStream *st;

    ASFStream *asf_st;

    // ASF file must not contain more than 128 streams according to the specification

    if (asf->nb_streams >= ASF_MAX_STREAMS)

        return AVERROR_INVALIDDATA;

    size = avio_rl64(pb);

    ff_get_guid(pb, &stream_type);

    if (!ff_guidcmp(&stream_type, &ff_asf_audio_stream))

        type = AVMEDIA_TYPE_AUDIO;

    else if (!ff_guidcmp(&stream_type, &ff_asf_video_stream))

        type = AVMEDIA_TYPE_VIDEO;

    else if (!ff_guidcmp(&stream_type, &ff_asf_jfif_media))

        type = AVMEDIA_TYPE_VIDEO;

    else if (!ff_guidcmp(&stream_type, &ff_asf_command_stream))

        type = AVMEDIA_TYPE_DATA;

    else if (!ff_guidcmp(&stream_type,

                         &ff_asf_ext_stream_embed_stream_header))

        type = AVMEDIA_TYPE_UNKNOWN;

    else

        return AVERROR_INVALIDDATA;

    ff_get_guid(pb, &stream_type); // error correction type

    avio_skip(pb, 8); // skip the time offset

    ts_data_len      = avio_rl32(pb);

    err_data_len     = avio_rl32(pb);

    flags            = avio_rl16(pb); // bit 15 - Encrypted Content

    stream_index = flags & ASF_STREAM_NUM;

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

        if (stream_index == asf->asf_st[i]->stream_index) {

            av_log(s, AV_LOG_WARNING,

                   "Duplicate stream found, this stream will be ignored.\n");

            align_position(pb, asf->offset, size);

            return 0;

        }

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 32, 1, 1000); // pts should be dword, in milliseconds

    st->codec->codec_type = type;

    asf->asf_st[asf->nb_streams] = av_mallocz(sizeof(*asf_st));

    if (!asf->asf_st[asf->nb_streams])

        return AVERROR(ENOMEM);

    asf_st                       = asf->asf_st[asf->nb_streams];

    asf_st->stream_index         = stream_index;

    asf_st->index                = st->index;

    asf_st->indexed              = 0;

    st->id                       = flags & ASF_STREAM_NUM;

    av_init_packet(&asf_st->pkt.avpkt);

    asf_st->pkt.data_size        = 0;

    avio_skip(pb, 4); // skip reserved field

    switch (type) {

    case AVMEDIA_TYPE_AUDIO:

        asf_st->type = AVMEDIA_TYPE_AUDIO;

        if ((ret = ff_get_wav_header(s, pb, st->codec, ts_data_len)) < 0)

            return ret;

        break;

    case AVMEDIA_TYPE_VIDEO:

        asf_st->type = AVMEDIA_TYPE_VIDEO;

        if ((ret = parse_video_info(pb, st)) < 0)

            return ret;

        break;

    default:

        avio_skip(pb, ts_data_len);

        break;

    }

    if (err_data_len) {

        if (type == AVMEDIA_TYPE_AUDIO) {

            uint8_t span = avio_r8(pb);

            if (span > 1) {

                asf_st->span              = span;

                asf_st->virtual_pkt_len   = avio_rl16(pb);

                asf_st->virtual_chunk_len = avio_rl16(pb);

                if (!asf_st->virtual_chunk_len || !asf_st->virtual_pkt_len)

                    return AVERROR_INVALIDDATA;

                avio_skip(pb, err_data_len - 5);

            } else

                avio_skip(pb, err_data_len - 1);

        } else

            avio_skip(pb, err_data_len);

    }

    asf->nb_streams++;

    align_position(pb, asf->offset, size);

    return 0;

}


static ssize_t gunzip(void *dst, size_t dstlen, uint8_t *src,

                      size_t srclen)

{

    z_stream s;

    ssize_t dstbytes;

    int r, i, flags;

    /* skip header */

    i = 10;

    flags = src[3];

    if (src[2] != DEFLATED || (flags & RESERVED) != 0) {

        puts ("Error: Bad gzipped data\n");

        return -1;

    }

    if ((flags & EXTRA_FIELD) != 0)

        i = 12 + src[10] + (src[11] << 8);

    if ((flags & ORIG_NAME) != 0)

        while (src[i++] != 0)

            ;

    if ((flags & COMMENT) != 0)

        while (src[i++] != 0)

            ;

    if ((flags & HEAD_CRC) != 0)

        i += 2;

    if (i >= srclen) {

        puts ("Error: gunzip out of data in header\n");

        return -1;

    }

    s.zalloc = zalloc;

    s.zfree = zfree;

    r = inflateInit2(&s, -MAX_WBITS);

    if (r != Z_OK) {

        printf ("Error: inflateInit2() returned %d\n", r);

        return (-1);

    }

    s.next_in = src + i;

    s.avail_in = srclen - i;

    s.next_out = dst;

    s.avail_out = dstlen;

    r = inflate(&s, Z_FINISH);

    if (r != Z_OK && r != Z_STREAM_END) {

        printf ("Error: inflate() returned %d\n", r);

        return -1;

    }

    dstbytes = s.next_out - (unsigned char *) dst;

    inflateEnd(&s);

    return dstbytes;

}


int check_tm_pred8x8_mode(int mode, int mb_x, int mb_y)

{

    if (!mb_x)

        return mb_y ? VERT_PRED8x8 : DC_129_PRED8x8;

    else

        return mb_y ? mode : HOR_PRED8x8;

}


static void omap_i2c_recv(I2CAdapter *i2c, uint8_t addr,

                          uint8_t *buf, uint16_t len)

{

    OMAPI2C *s = (OMAPI2C *)i2c;

    uint16_t data, stat;

    omap_i2c_set_slave_addr(s, addr);

    data = len;

    memwrite(s->addr + OMAP_I2C_CNT, &data, 2);

    data = OMAP_I2C_CON_I2C_EN |

           OMAP_I2C_CON_MST |

           OMAP_I2C_CON_STT |

           OMAP_I2C_CON_STP;

    memwrite(s->addr + OMAP_I2C_CON, &data, 2);

    memread(s->addr + OMAP_I2C_CON, &data, 2);

    g_assert((data & OMAP_I2C_CON_STP) == 0);

    memread(s->addr + OMAP_I2C_STAT, &data, 2);

    g_assert((data & OMAP_I2C_STAT_NACK) == 0);

    memread(s->addr + OMAP_I2C_CNT, &data, 2);

    g_assert_cmpuint(data, ==, len);

    while (len > 0) {

        memread(s->addr + OMAP_I2C_STAT, &data, 2);

        g_assert((data & OMAP_I2C_STAT_RRDY) != 0);

        g_assert((data & OMAP_I2C_STAT_ROVR) == 0);

        memread(s->addr + OMAP_I2C_DATA, &data, 2);

        memread(s->addr + OMAP_I2C_STAT, &stat, 2);

        if (unlikely(len == 1)) {

            *buf = data & 0xf;

            buf++;

            len--;

        } else {

            memcpy(buf, &data, 2);

            buf += 2;

            len -= 2;

        }

    }

    memread(s->addr + OMAP_I2C_CON, &data, 2);

    g_assert((data & OMAP_I2C_CON_STP) == 0);

}


double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max)

{

    char *tail;

    const char *error;

    double d = av_strtod(numstr, &tail);

    if (*tail)

        error= "Expected number for %s but found: %s\n";

    else if (d < min || d > max)

        error= "The value for %s was %s which is not within %f - %f\n";

    else if(type == OPT_INT64 && (int64_t)d != d)

        error= "Expected int64 for %s but found %s\n";

    else

        return d;

    fprintf(stderr, error, context, numstr, min, max);

    exit(1);

}


static void do_video_out(AVFormatContext *s,

                         AVOutputStream *ost,

                         AVInputStream *ist,

                         AVFrame *in_picture,

                         int *frame_size)

{

    int nb_frames, i, ret;

    int64_t topBand, bottomBand, leftBand, rightBand;

    AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;

    AVFrame picture_crop_temp, picture_pad_temp;

    AVCodecContext *enc, *dec;

    avcodec_get_frame_defaults(&picture_crop_temp);

    avcodec_get_frame_defaults(&picture_pad_temp);

    enc = ost->st->codec;

    dec = ist->st->codec;

    /* by default, we output a single frame */

    nb_frames = 1;

    *frame_size = 0;

    if(video_sync_method){

        double vdelta;

        vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;

        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c

        if (vdelta < -1.1)

            nb_frames = 0;

        else if (video_sync_method == 2 || (video_sync_method<0 && (s->oformat->flags & AVFMT_VARIABLE_FPS))){

            if(vdelta<=-0.6){

                nb_frames=0;

            }else if(vdelta>0.6)

            ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));

        }else if (vdelta > 1.1)

            nb_frames = lrintf(vdelta);

//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);

        if (nb_frames == 0){

            ++nb_frames_drop;

            if (verbose>2)

                fprintf(stderr, "*** drop!\n");

        }else if (nb_frames > 1) {

            nb_frames_dup += nb_frames;

            if (verbose>2)

                fprintf(stderr, "*** %d dup!\n", nb_frames-1);

        }

    }else

        ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));

    nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);

    if (nb_frames <= 0)

        return;

    if (ost->video_crop) {

        if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {

            fprintf(stderr, "error cropping picture\n");

            if (exit_on_error)

                av_exit(1);

            return;

        }

        formatted_picture = &picture_crop_temp;

    } else {

        formatted_picture = in_picture;

    }

    final_picture = formatted_picture;

    padding_src = formatted_picture;

    resampling_dst = &ost->pict_tmp;

    if (ost->video_pad) {

        final_picture = &ost->pict_tmp;

        if (ost->video_resample) {

            if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {

                fprintf(stderr, "error padding picture\n");

                if (exit_on_error)

                    av_exit(1);

                return;

            }

            resampling_dst = &picture_pad_temp;

        }

    }

    if (ost->video_resample) {

        padding_src = NULL;

        final_picture = &ost->pict_tmp;

        if(  (ost->resample_height != (ist->st->codec->height - (ost->topBand  + ost->bottomBand)))

          || (ost->resample_width  != (ist->st->codec->width  - (ost->leftBand + ost->rightBand)))

          || (ost->resample_pix_fmt!= ist->st->codec->pix_fmt) ) {

            fprintf(stderr,"Input Stream #%d.%d frame size changed to %dx%d, %s\n", ist->file_index, ist->index, ist->st->codec->width, ist->st->codec->height,avcodec_get_pix_fmt_name(ist->st->codec->pix_fmt));

            /* keep bands proportional to the frame size */

            topBand    = ((int64_t)ist->st->codec->height * ost->original_topBand    / ost->original_height) & ~1;

            bottomBand = ((int64_t)ist->st->codec->height * ost->original_bottomBand / ost->original_height) & ~1;

            leftBand   = ((int64_t)ist->st->codec->width  * ost->original_leftBand   / ost->original_width)  & ~1;

            rightBand  = ((int64_t)ist->st->codec->width  * ost->original_rightBand  / ost->original_width)  & ~1;

            /* sanity check to ensure no bad band sizes sneak in */

            assert(topBand    <= INT_MAX && topBand    >= 0);

            assert(bottomBand <= INT_MAX && bottomBand >= 0);

            assert(leftBand   <= INT_MAX && leftBand   >= 0);

            assert(rightBand  <= INT_MAX && rightBand  >= 0);

            ost->topBand    = topBand;

            ost->bottomBand = bottomBand;

            ost->leftBand   = leftBand;

            ost->rightBand  = rightBand;

            ost->resample_height = ist->st->codec->height - (ost->topBand  + ost->bottomBand);

            ost->resample_width  = ist->st->codec->width  - (ost->leftBand + ost->rightBand);

            ost->resample_pix_fmt= ist->st->codec->pix_fmt;

            /* initialize a new scaler context */

            sws_freeContext(ost->img_resample_ctx);

            sws_flags = av_get_int(sws_opts, "sws_flags", NULL);

            ost->img_resample_ctx = sws_getContext(

                ist->st->codec->width  - (ost->leftBand + ost->rightBand),

                ist->st->codec->height - (ost->topBand  + ost->bottomBand),

                ist->st->codec->pix_fmt,

                ost->st->codec->width  - (ost->padleft  + ost->padright),

                ost->st->codec->height - (ost->padtop   + ost->padbottom),

                ost->st->codec->pix_fmt,

                sws_flags, NULL, NULL, NULL);

            if (ost->img_resample_ctx == NULL) {

                fprintf(stderr, "Cannot get resampling context\n");

                av_exit(1);

            }

        }

        sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,

              0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);

    }

    if (ost->video_pad) {

        av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,

                enc->height, enc->width, enc->pix_fmt,

                ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);

    }

    /* duplicates frame if needed */

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

        AVPacket pkt;

        av_init_packet(&pkt);

        pkt.stream_index= ost->index;

        if (s->oformat->flags & AVFMT_RAWPICTURE) {

            /* raw pictures are written as AVPicture structure to

               avoid any copies. We support temorarily the older

               method. */

            AVFrame* old_frame = enc->coded_frame;

            enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack

            pkt.data= (uint8_t *)final_picture;

            pkt.size=  sizeof(AVPicture);

            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);

            pkt.flags |= PKT_FLAG_KEY;

            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);

            enc->coded_frame = old_frame;

        } else {

            AVFrame big_picture;

            big_picture= *final_picture;

            /* better than nothing: use input picture interlaced

               settings */

            big_picture.interlaced_frame = in_picture->interlaced_frame;

            if(avcodec_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){

                if(top_field_first == -1)

                    big_picture.top_field_first = in_picture->top_field_first;

                else

                    big_picture.top_field_first = top_field_first;

            }

            /* handles sameq here. This is not correct because it may

               not be a global option */

            if (same_quality) {

                big_picture.quality = ist->st->quality;

            }else

                big_picture.quality = ost->st->quality;

            if(!me_threshold)

                big_picture.pict_type = 0;

//            big_picture.pts = AV_NOPTS_VALUE;

            big_picture.pts= ost->sync_opts;

//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);

//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);

            ret = avcodec_encode_video(enc,

                                       bit_buffer, bit_buffer_size,

                                       &big_picture);

            if (ret < 0) {

                fprintf(stderr, "Video encoding failed\n");

                av_exit(1);

            }

            if(ret>0){

                pkt.data= bit_buffer;

                pkt.size= ret;

                if(enc->coded_frame->pts != AV_NOPTS_VALUE)

                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);

/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",

   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,

   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/

                if(enc->coded_frame->key_frame)

                    pkt.flags |= PKT_FLAG_KEY;

                write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);

                *frame_size = ret;

                video_size += ret;

                //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",

                //        enc->frame_number-1, ret, enc->pict_type);

                /* if two pass, output log */

                if (ost->logfile && enc->stats_out) {

                    fprintf(ost->logfile, "%s", enc->stats_out);

                }

            }

        }

        ost->sync_opts++;

        ost->frame_number++;

    }

}


static void gen_ld(DisasContext *ctx, uint32_t opc,

                   int rt, int base, int16_t offset)

{

    TCGv t0, t1, t2;

    int mem_idx = ctx->mem_idx;

    if (rt == 0 && ctx->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F)) {

        /* Loongson CPU uses a load to zero register for prefetch.

           We emulate it as a NOP. On other CPU we must perform the

           actual memory access. */

        return;

    }

    t0 = tcg_temp_new();

    gen_base_offset_addr(ctx, t0, base, offset);

    switch (opc) {

#if defined(TARGET_MIPS64)

    case OPC_LWU:

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEUL |

                           ctx->default_tcg_memop_mask);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LD:

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEQ |

                           ctx->default_tcg_memop_mask);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LLD:

    case R6_OPC_LLD:

        op_ld_lld(t0, t0, mem_idx, ctx);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LDL:

        t1 = tcg_temp_new();

        /* Do a byte access to possibly trigger a page

           fault with the unaligned address.  */

        tcg_gen_qemu_ld_tl(t1, t0, mem_idx, MO_UB);

        tcg_gen_andi_tl(t1, t0, 7);

#ifndef TARGET_WORDS_BIGENDIAN

        tcg_gen_xori_tl(t1, t1, 7);

#endif

        tcg_gen_shli_tl(t1, t1, 3);

        tcg_gen_andi_tl(t0, t0, ~7);

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEQ);

        tcg_gen_shl_tl(t0, t0, t1);

        t2 = tcg_const_tl(-1);

        tcg_gen_shl_tl(t2, t2, t1);

        gen_load_gpr(t1, rt);

        tcg_gen_andc_tl(t1, t1, t2);

        tcg_temp_free(t2);

        tcg_gen_or_tl(t0, t0, t1);

        tcg_temp_free(t1);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LDR:

        t1 = tcg_temp_new();

        /* Do a byte access to possibly trigger a page

           fault with the unaligned address.  */

        tcg_gen_qemu_ld_tl(t1, t0, mem_idx, MO_UB);

        tcg_gen_andi_tl(t1, t0, 7);

#ifdef TARGET_WORDS_BIGENDIAN

        tcg_gen_xori_tl(t1, t1, 7);

#endif

        tcg_gen_shli_tl(t1, t1, 3);

        tcg_gen_andi_tl(t0, t0, ~7);

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEQ);

        tcg_gen_shr_tl(t0, t0, t1);

        tcg_gen_xori_tl(t1, t1, 63);

        t2 = tcg_const_tl(0xfffffffffffffffeull);

        tcg_gen_shl_tl(t2, t2, t1);

        gen_load_gpr(t1, rt);

        tcg_gen_and_tl(t1, t1, t2);

        tcg_temp_free(t2);

        tcg_gen_or_tl(t0, t0, t1);

        tcg_temp_free(t1);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LDPC:

        t1 = tcg_const_tl(pc_relative_pc(ctx));

        gen_op_addr_add(ctx, t0, t0, t1);

        tcg_temp_free(t1);

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEQ);

        gen_store_gpr(t0, rt);

        break;

#endif

    case OPC_LWPC:

        t1 = tcg_const_tl(pc_relative_pc(ctx));

        gen_op_addr_add(ctx, t0, t0, t1);

        tcg_temp_free(t1);

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TESL);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LWE:

    case OPC_LW:

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TESL |

                           ctx->default_tcg_memop_mask);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LHE:

    case OPC_LH:

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TESW |

                           ctx->default_tcg_memop_mask);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LHUE:

    case OPC_LHU:

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEUW |

                           ctx->default_tcg_memop_mask);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LBE:

    case OPC_LB:

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_SB);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LBUE:

    case OPC_LBU:

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_UB);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LWLE:

    case OPC_LWL:

        t1 = tcg_temp_new();

        /* Do a byte access to possibly trigger a page

           fault with the unaligned address.  */

        tcg_gen_qemu_ld_tl(t1, t0, mem_idx, MO_UB);

        tcg_gen_andi_tl(t1, t0, 3);

#ifndef TARGET_WORDS_BIGENDIAN

        tcg_gen_xori_tl(t1, t1, 3);

#endif

        tcg_gen_shli_tl(t1, t1, 3);

        tcg_gen_andi_tl(t0, t0, ~3);

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEUL);

        tcg_gen_shl_tl(t0, t0, t1);

        t2 = tcg_const_tl(-1);

        tcg_gen_shl_tl(t2, t2, t1);

        gen_load_gpr(t1, rt);

        tcg_gen_andc_tl(t1, t1, t2);

        tcg_temp_free(t2);

        tcg_gen_or_tl(t0, t0, t1);

        tcg_temp_free(t1);

        tcg_gen_ext32s_tl(t0, t0);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LWR:

        t1 = tcg_temp_new();

        /* Do a byte access to possibly trigger a page

           fault with the unaligned address.  */

        tcg_gen_qemu_ld_tl(t1, t0, mem_idx, MO_UB);

        tcg_gen_andi_tl(t1, t0, 3);

#ifdef TARGET_WORDS_BIGENDIAN

        tcg_gen_xori_tl(t1, t1, 3);

#endif

        tcg_gen_shli_tl(t1, t1, 3);

        tcg_gen_andi_tl(t0, t0, ~3);

        tcg_gen_qemu_ld_tl(t0, t0, mem_idx, MO_TEUL);

        tcg_gen_shr_tl(t0, t0, t1);

        tcg_gen_xori_tl(t1, t1, 31);

        t2 = tcg_const_tl(0xfffffffeull);

        tcg_gen_shl_tl(t2, t2, t1);

        gen_load_gpr(t1, rt);

        tcg_gen_and_tl(t1, t1, t2);

        tcg_temp_free(t2);

        tcg_gen_or_tl(t0, t0, t1);

        tcg_temp_free(t1);

        tcg_gen_ext32s_tl(t0, t0);

        gen_store_gpr(t0, rt);

        break;

    case OPC_LLE:

    case OPC_LL:

    case R6_OPC_LL:

        op_ld_ll(t0, t0, mem_idx, ctx);

        gen_store_gpr(t0, rt);

        break;

    }

    tcg_temp_free(t0);

}


static void libschroedinger_decode_frame_free(void *frame)

{

    schro_frame_unref(frame);

}


static void network_to_caps(RDMACapabilities *cap)

{

    cap->version = ntohl(cap->version);

    cap->flags = ntohl(cap->flags);

}


static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)

{

    OutputStream *ost;

    AVStream *st = avformat_new_stream(oc, NULL);

    int idx      = oc->nb_streams - 1, ret = 0;

    char *bsf = NULL, *next, *codec_tag = NULL;

    AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;

    double qscale = -1;

    int i;

    if (!st) {

        av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");

        exit_program(1);

    }

    if (oc->nb_streams - 1 < o->nb_streamid_map)

        st->id = o->streamid_map[oc->nb_streams - 1];

    GROW_ARRAY(output_streams, nb_output_streams);

    if (!(ost = av_mallocz(sizeof(*ost))))

        exit_program(1);

    output_streams[nb_output_streams - 1] = ost;

    ost->file_index = nb_output_files - 1;

    ost->index      = idx;

    ost->st         = st;

    st->codecpar->codec_type = type;

    ret = choose_encoder(o, oc, ost);

    if (ret < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error selecting an encoder for stream "

               "%d:%d\n", ost->file_index, ost->index);

        exit_program(1);

    }

    ost->enc_ctx = avcodec_alloc_context3(ost->enc);

    if (!ost->enc_ctx) {

        av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding context.\n");

        exit_program(1);

    }

    ost->enc_ctx->codec_type = type;

    ost->ref_par = avcodec_parameters_alloc();

    if (!ost->ref_par) {

        av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding parameters.\n");

        exit_program(1);

    }

    if (ost->enc) {

        AVIOContext *s = NULL;

        char *buf = NULL, *arg = NULL, *preset = NULL;

        ost->encoder_opts  = filter_codec_opts(o->g->codec_opts, ost->enc->id, oc, st, ost->enc);

        MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);

        if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {

            do  {

                buf = get_line(s);

                if (!buf[0] || buf[0] == '#') {

                    av_free(buf);

                    continue;

                }

                if (!(arg = strchr(buf, '='))) {

                    av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");

                    exit_program(1);

                }

                *arg++ = 0;

                av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);

                av_free(buf);

            } while (!s->eof_reached);

            avio_closep(&s);

        }

        if (ret) {

            av_log(NULL, AV_LOG_FATAL,

                   "Preset %s specified for stream %d:%d, but could not be opened.\n",

                   preset, ost->file_index, ost->index);

            exit_program(1);

        }

    } else {

        ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);

    }

    ost->max_frames = INT64_MAX;

    MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);

    for (i = 0; i<o->nb_max_frames; i++) {

        char *p = o->max_frames[i].specifier;

        if (!*p && type != AVMEDIA_TYPE_VIDEO) {

            av_log(NULL, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");

            break;

        }

    }

    ost->copy_prior_start = -1;

    MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);

    MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);

    while (bsf) {

        char *arg = NULL;

        if (next = strchr(bsf, ','))

            *next++ = 0;

        if (arg = strchr(bsf, '='))

            *arg++ = 0;

        if (!(bsfc = av_bitstream_filter_init(bsf))) {

            av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);

            exit_program(1);

        }

        if (bsfc_prev)

            bsfc_prev->next = bsfc;

        else

            ost->bitstream_filters = bsfc;

        if (arg)

            if (!(bsfc->args = av_strdup(arg))) {

                av_log(NULL, AV_LOG_FATAL, "Bitstream filter memory allocation failed\n");

                exit_program(1);

            }

        bsfc_prev = bsfc;

        bsf       = next;

    }

    MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);

    if (codec_tag) {

        uint32_t tag = strtol(codec_tag, &next, 0);

        if (*next)

            tag = AV_RL32(codec_tag);

        ost->st->codecpar->codec_tag =

        ost->enc_ctx->codec_tag = tag;

    }

    MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);

    if (qscale >= 0) {

        ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;

        ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;

    }

    MATCH_PER_STREAM_OPT(disposition, str, ost->disposition, oc, st);

    ost->disposition = av_strdup(ost->disposition);

    if (oc->oformat->flags & AVFMT_GLOBALHEADER)

        ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);

    av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);

    if (ost->enc && av_get_exact_bits_per_sample(ost->enc->id) == 24)

        av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);

    av_dict_copy(&ost->resample_opts, o->g->resample_opts, 0);

    ost->source_index = source_index;

    if (source_index >= 0) {

        ost->sync_ist = input_streams[source_index];

        input_streams[source_index]->discard = 0;

        input_streams[source_index]->st->discard = input_streams[source_index]->user_set_discard;

    }

    ost->last_mux_dts = AV_NOPTS_VALUE;

    return ost;

}


static void pcnet_common_init(PCNetState *d, NICInfo *nd)

{

    d->poll_timer = qemu_new_timer(vm_clock, pcnet_poll_timer, d);

    d->nd = nd;

    if (nd && nd->vlan) {

        d->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

                                     pcnet_receive, pcnet_can_receive, d);

        qemu_format_nic_info_str(d->vc, d->nd->macaddr);

    } else {

        d->vc = NULL;

    }

    pcnet_h_reset(d);

    register_savevm("pcnet", -1, 2, pcnet_save, pcnet_load, d);

}


static int get_transform_coeffs(AC3DecodeContext * ctx)

{

    int i;

    ac3_audio_block *ab = &ctx->audio_block;

    float *samples = ctx->samples;

    int got_cplchan = 0;

    int dithflag = 0;

    samples += (ctx->bsi.flags & AC3_BSI_LFEON) ? 256 : 0;

    for (i = 0; i < ctx->bsi.nfchans; i++) {

        if ((ab->flags & AC3_AB_CPLINU) && (ab->chincpl & (1 << i)))

            dithflag = 0; /* don't generate dither until channels are decoupled */

        else

            dithflag = ab->dithflag & (1 << i);

        /* transform coefficients for individual channel */

        if (_get_transform_coeffs(ab->dexps[i], ab->bap[i], ab->chcoeffs[i], samples + (i * 256),

                    0, ab->endmant[i], dithflag, &ctx->gb, &ctx->state))

            return -1;

        /* tranform coefficients for coupling channels */

        if ((ab->flags & AC3_AB_CPLINU) && (ab->chincpl & (1 << i)) && !got_cplchan) {

            if (_get_transform_coeffs(ab->dcplexps, ab->cplbap, 1.0f, ab->cplcoeffs,

                        ab->cplstrtmant, ab->cplendmant, 0, &ctx->gb, &ctx->state))

                return -1;

            got_cplchan = 1;

        }

    }

    if (ctx->bsi.flags & AC3_BSI_LFEON)

        if (_get_transform_coeffs(ab->lfeexps, ab->lfebap, 1.0f, samples - 256, 0, 7, 0, &ctx->gb, &ctx->state))

                return -1;

    /* uncouple the channels from the coupling channel */

    if (ab->flags & AC3_AB_CPLINU)

        if (uncouple_channels(ctx))

            return -1;

    return 0;

}


static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set)

{

    int err;

    if (mxf->metadata_sets_count+1 >= UINT_MAX / sizeof(*mxf->metadata_sets))

        return AVERROR(ENOMEM);

    if ((err = av_reallocp_array(&mxf->metadata_sets, mxf->metadata_sets_count + 1,

                                 sizeof(*mxf->metadata_sets))) < 0) {

        mxf->metadata_sets_count = 0;

        return err;

    }

    mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set;

    mxf->metadata_sets_count++;

    return 0;

}


static int dvvideo_encode_frame(AVCodecContext *c, AVPacket *pkt,

                                const AVFrame *frame, int *got_packet)

{

    DVVideoContext *s = c->priv_data;

    int ret;

    s->sys = avpriv_dv_codec_profile(c);

    if (!s->sys || ff_dv_init_dynamic_tables(s->sys))

        return -1;

    if ((ret = ff_alloc_packet(pkt, s->sys->frame_size)) < 0) {

        av_log(c, AV_LOG_ERROR, "Error getting output packet.\n");

        return ret;

    }

    c->pix_fmt                = s->sys->pix_fmt;

    s->frame                  = frame;

    c->coded_frame->key_frame = 1;

    c->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    s->buf = pkt->data;

    c->execute(c, dv_encode_video_segment, s->sys->work_chunks, NULL,

               dv_work_pool_size(s->sys), sizeof(DVwork_chunk));

    emms_c();

    dv_format_frame(s, pkt->data);

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static void mxf_write_partition(AVFormatContext *s, int bodysid,

                                int indexsid,

                                const uint8_t *key, int write_metadata)

{

    MXFContext *mxf = s->priv_data;

    ByteIOContext *pb = s->pb;

    int64_t header_byte_count_offset;

    unsigned index_byte_count = 0;

    uint64_t partition_offset = url_ftell(pb);

    if (mxf->edit_units_count) {

        index_byte_count = 109 + (s->nb_streams+1)*6 +

            mxf->edit_units_count*(11+mxf->slice_count*4);

        // add encoded ber length

        index_byte_count += 16 + klv_ber_length(index_byte_count);

        index_byte_count += klv_fill_size(index_byte_count);

    }

    if (!memcmp(key, body_partition_key, 16)) {

        mxf->body_partition_offset =

            av_realloc(mxf->body_partition_offset,

                       (mxf->body_partitions_count+1)*

                       sizeof(*mxf->body_partition_offset));

        mxf->body_partition_offset[mxf->body_partitions_count++] = partition_offset;

    }

    // write klv

    put_buffer(pb, key, 16);

    klv_encode_ber_length(pb, 88 + 16 * mxf->essence_container_count);

    // write partition value

    put_be16(pb, 1); // majorVersion

    put_be16(pb, 2); // minorVersion

    put_be32(pb, KAG_SIZE); // KAGSize

    put_be64(pb, partition_offset); // ThisPartition

    if (!memcmp(key, body_partition_key, 16) && mxf->body_partitions_count > 1)

        put_be64(pb, mxf->body_partition_offset[mxf->body_partitions_count-2]); // PreviousPartition

    else if (!memcmp(key, footer_partition_key, 16))

        put_be64(pb, mxf->body_partition_offset[mxf->body_partitions_count-1]); // PreviousPartition

    else

        put_be64(pb, 0);

    put_be64(pb, mxf->footer_partition_offset); // footerPartition

    // set offset

    header_byte_count_offset = url_ftell(pb);

    put_be64(pb, 0); // headerByteCount, update later

    // indexTable

    put_be64(pb, index_byte_count); // indexByteCount

    put_be32(pb, index_byte_count ? indexsid : 0); // indexSID

    // BodyOffset

    if (bodysid && mxf->edit_units_count) {

        uint64_t partition_end = url_ftell(pb) + 8 + 4 + 16 + 8 +

            16*mxf->essence_container_count;

        put_be64(pb, partition_end + klv_fill_size(partition_end) +

                 index_byte_count - mxf->first_edit_unit_offset);

    } else

        put_be64(pb, 0);

    put_be32(pb, bodysid); // bodySID

    // operational pattern

    if (s->nb_streams > 1) {

        put_buffer(pb, op1a_ul, 14);

        put_be16(pb, 0x0900); // multi track

    } else {

        put_buffer(pb, op1a_ul, 16);

    }

    // essence container

    mxf_write_essence_container_refs(s);

    if (write_metadata) {

        // mark the start of the headermetadata and calculate metadata size

        int64_t pos, start;

        unsigned header_byte_count;

        mxf_write_klv_fill(s);

        start = url_ftell(s->pb);

        mxf_write_primer_pack(s);

        mxf_write_header_metadata_sets(s);

        pos = url_ftell(s->pb);

        header_byte_count = pos - start + klv_fill_size(pos);

        // update header_byte_count

        url_fseek(pb, header_byte_count_offset, SEEK_SET);

        put_be64(pb, header_byte_count);

        url_fseek(pb, pos, SEEK_SET);

    }

    put_flush_packet(pb);

}


static void *spapr_create_fdt_skel(const char *cpu_model,

                                   target_phys_addr_t rma_size,

                                   target_phys_addr_t initrd_base,

                                   target_phys_addr_t initrd_size,

                                   target_phys_addr_t kernel_size,

                                   const char *boot_device,

                                   const char *kernel_cmdline,

                                   long hash_shift)

{

    void *fdt;

    CPUPPCState *env;

    uint64_t mem_reg_property[2];

    uint32_t start_prop = cpu_to_be32(initrd_base);

    uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);

    uint32_t pft_size_prop[] = {0, cpu_to_be32(hash_shift)};

    char hypertas_prop[] = "hcall-pft\0hcall-term\0hcall-dabr\0hcall-interrupt"

        "\0hcall-tce\0hcall-vio\0hcall-splpar\0hcall-bulk";

    char qemu_hypertas_prop[] = "hcall-memop1";

    uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};

    int i;

    char *modelname;

    int smt = kvmppc_smt_threads();

    unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80};

    uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)};

    uint32_t associativity[] = {cpu_to_be32(0x4), cpu_to_be32(0x0),

                                cpu_to_be32(0x0), cpu_to_be32(0x0),

                                cpu_to_be32(0x0)};

    char mem_name[32];

    target_phys_addr_t node0_size, mem_start;

#define _FDT(exp) \

    do { \

        int ret = (exp);                                           \

        if (ret < 0) {                                             \

            fprintf(stderr, "qemu: error creating device tree: %s: %s\n", \

                    #exp, fdt_strerror(ret));                      \

            exit(1);                                               \

        }                                                          \

    } while (0)

    fdt = g_malloc0(FDT_MAX_SIZE);

    _FDT((fdt_create(fdt, FDT_MAX_SIZE)));

    if (kernel_size) {

        _FDT((fdt_add_reservemap_entry(fdt, KERNEL_LOAD_ADDR, kernel_size)));

    }

    if (initrd_size) {

        _FDT((fdt_add_reservemap_entry(fdt, initrd_base, initrd_size)));

    }

    _FDT((fdt_finish_reservemap(fdt)));

    /* Root node */

    _FDT((fdt_begin_node(fdt, "")));

    _FDT((fdt_property_string(fdt, "device_type", "chrp")));

    _FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));

    /* /chosen */

    _FDT((fdt_begin_node(fdt, "chosen")));

    /* Set Form1_affinity */

    _FDT((fdt_property(fdt, "ibm,architecture-vec-5", vec5, sizeof(vec5))));

    _FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));

    _FDT((fdt_property(fdt, "linux,initrd-start",

                       &start_prop, sizeof(start_prop))));

    _FDT((fdt_property(fdt, "linux,initrd-end",

                       &end_prop, sizeof(end_prop))));

    if (kernel_size) {

        uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),

                              cpu_to_be64(kernel_size) };

        _FDT((fdt_property(fdt, "qemu,boot-kernel", &kprop, sizeof(kprop))));

    }

    _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));

    _FDT((fdt_property_cell(fdt, "qemu,graphic-width", graphic_width)));

    _FDT((fdt_property_cell(fdt, "qemu,graphic-height", graphic_height)));

    _FDT((fdt_property_cell(fdt, "qemu,graphic-depth", graphic_depth)));

    _FDT((fdt_end_node(fdt)));

    /* memory node(s) */

    node0_size = (nb_numa_nodes > 1) ? node_mem[0] : ram_size;

    if (rma_size > node0_size) {

        rma_size = node0_size;

    }

    /* RMA */

    mem_reg_property[0] = 0;

    mem_reg_property[1] = cpu_to_be64(rma_size);

    _FDT((fdt_begin_node(fdt, "memory@0")));

    _FDT((fdt_property_string(fdt, "device_type", "memory")));

    _FDT((fdt_property(fdt, "reg", mem_reg_property,

        sizeof(mem_reg_property))));

    _FDT((fdt_property(fdt, "ibm,associativity", associativity,

        sizeof(associativity))));

    _FDT((fdt_end_node(fdt)));

    /* RAM: Node 0 */

    if (node0_size > rma_size) {

        mem_reg_property[0] = cpu_to_be64(rma_size);

        mem_reg_property[1] = cpu_to_be64(node0_size - rma_size);

        sprintf(mem_name, "memory@" TARGET_FMT_lx, rma_size);

        _FDT((fdt_begin_node(fdt, mem_name)));

        _FDT((fdt_property_string(fdt, "device_type", "memory")));

        _FDT((fdt_property(fdt, "reg", mem_reg_property,

                           sizeof(mem_reg_property))));

        _FDT((fdt_property(fdt, "ibm,associativity", associativity,

                           sizeof(associativity))));

        _FDT((fdt_end_node(fdt)));

    }

    /* RAM: Node 1 and beyond */

    mem_start = node0_size;

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

        mem_reg_property[0] = cpu_to_be64(mem_start);

        mem_reg_property[1] = cpu_to_be64(node_mem[i]);

        associativity[3] = associativity[4] = cpu_to_be32(i);

        sprintf(mem_name, "memory@" TARGET_FMT_lx, mem_start);

        _FDT((fdt_begin_node(fdt, mem_name)));

        _FDT((fdt_property_string(fdt, "device_type", "memory")));

        _FDT((fdt_property(fdt, "reg", mem_reg_property,

            sizeof(mem_reg_property))));

        _FDT((fdt_property(fdt, "ibm,associativity", associativity,

            sizeof(associativity))));

        _FDT((fdt_end_node(fdt)));

        mem_start += node_mem[i];

    }

    /* cpus */

    _FDT((fdt_begin_node(fdt, "cpus")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));

    modelname = g_strdup(cpu_model);

    for (i = 0; i < strlen(modelname); i++) {

        modelname[i] = toupper(modelname[i]);

    }

    /* This is needed during FDT finalization */

    spapr->cpu_model = g_strdup(modelname);

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

        int index = env->cpu_index;

        uint32_t servers_prop[smp_threads];

        uint32_t gservers_prop[smp_threads * 2];

        char *nodename;

        uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),

                           0xffffffff, 0xffffffff};

        uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;

        uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;

        uint32_t page_sizes_prop[64];

        size_t page_sizes_prop_size;

        if ((index % smt) != 0) {

            continue;

        }

        if (asprintf(&nodename, "%s@%x", modelname, index) < 0) {

            fprintf(stderr, "Allocation failure\n");

            exit(1);

        }

        _FDT((fdt_begin_node(fdt, nodename)));

        free(nodename);

        _FDT((fdt_property_cell(fdt, "reg", index)));

        _FDT((fdt_property_string(fdt, "device_type", "cpu")));

        _FDT((fdt_property_cell(fdt, "cpu-version", env->spr[SPR_PVR])));

        _FDT((fdt_property_cell(fdt, "dcache-block-size",

                                env->dcache_line_size)));

        _FDT((fdt_property_cell(fdt, "icache-block-size",

                                env->icache_line_size)));

        _FDT((fdt_property_cell(fdt, "timebase-frequency", tbfreq)));

        _FDT((fdt_property_cell(fdt, "clock-frequency", cpufreq)));

        _FDT((fdt_property_cell(fdt, "ibm,slb-size", env->slb_nr)));

        _FDT((fdt_property(fdt, "ibm,pft-size",

                           pft_size_prop, sizeof(pft_size_prop))));

        _FDT((fdt_property_string(fdt, "status", "okay")));

        _FDT((fdt_property(fdt, "64-bit", NULL, 0)));

        /* Build interrupt servers and gservers properties */

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

            servers_prop[i] = cpu_to_be32(index + i);

            /* Hack, direct the group queues back to cpu 0 */

            gservers_prop[i*2] = cpu_to_be32(index + i);

            gservers_prop[i*2 + 1] = 0;

        }

        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-server#s",

                           servers_prop, sizeof(servers_prop))));

        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-gserver#s",

                           gservers_prop, sizeof(gservers_prop))));

        if (env->mmu_model & POWERPC_MMU_1TSEG) {

            _FDT((fdt_property(fdt, "ibm,processor-segment-sizes",

                               segs, sizeof(segs))));

        }

        /* Advertise VMX/VSX (vector extensions) if available

         *   0 / no property == no vector extensions

         *   1               == VMX / Altivec available

         *   2               == VSX available */

        if (env->insns_flags & PPC_ALTIVEC) {

            uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;

            _FDT((fdt_property_cell(fdt, "ibm,vmx", vmx)));

        }

        /* Advertise DFP (Decimal Floating Point) if available

         *   0 / no property == no DFP

         *   1               == DFP available */

        if (env->insns_flags2 & PPC2_DFP) {

            _FDT((fdt_property_cell(fdt, "ibm,dfp", 1)));

        }

        page_sizes_prop_size = create_page_sizes_prop(env, page_sizes_prop,

                                                      sizeof(page_sizes_prop));

        if (page_sizes_prop_size) {

            _FDT((fdt_property(fdt, "ibm,segment-page-sizes",

                               page_sizes_prop, page_sizes_prop_size)));

        }

        _FDT((fdt_end_node(fdt)));

    }

    g_free(modelname);

    _FDT((fdt_end_node(fdt)));

    /* RTAS */

    _FDT((fdt_begin_node(fdt, "rtas")));

    _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas_prop,

                       sizeof(hypertas_prop))));

    _FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas_prop,

                       sizeof(qemu_hypertas_prop))));

    _FDT((fdt_property(fdt, "ibm,associativity-reference-points",

        refpoints, sizeof(refpoints))));

    _FDT((fdt_end_node(fdt)));

    /* interrupt controller */

    _FDT((fdt_begin_node(fdt, "interrupt-controller")));

    _FDT((fdt_property_string(fdt, "device_type",

                              "PowerPC-External-Interrupt-Presentation")));

    _FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));

    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));

    _FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",

                       interrupt_server_ranges_prop,

                       sizeof(interrupt_server_ranges_prop))));

    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));

    _FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));

    _FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));

    _FDT((fdt_end_node(fdt)));

    /* vdevice */

    _FDT((fdt_begin_node(fdt, "vdevice")));

    _FDT((fdt_property_string(fdt, "device_type", "vdevice")));

    _FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));

    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));

    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));

    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));

    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));

    _FDT((fdt_end_node(fdt)));

    _FDT((fdt_end_node(fdt))); /* close root node */

    _FDT((fdt_finish(fdt)));

    return fdt;

}


void arm_sysctl_init(uint32_t base, uint32_t sys_id)

{

    arm_sysctl_state *s;

    int iomemtype;

    s = (arm_sysctl_state *)qemu_mallocz(sizeof(arm_sysctl_state));

    if (!s)

        return;

    s->base = base;

    s->sys_id = sys_id;

    iomemtype = cpu_register_io_memory(0, arm_sysctl_readfn,

                                       arm_sysctl_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    /* ??? Save/restore.  */

}


static void qobject_input_type_uint64(Visitor *v, const char *name,

                                      uint64_t *obj, Error **errp)

{

    /* FIXME: qobject_to_qint mishandles values over INT64_MAX */

    QObjectInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qobject_input_get_object(qiv, name, true, errp);

    QInt *qint;

    if (!qobj) {

        return;

    }

    qint = qobject_to_qint(qobj);

    if (!qint) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

                   "integer");

        return;

    }

    *obj = qint_get_int(qint);

}


static void av_update_stream_timings(AVFormatContext *ic)

{

    int64_t start_time, start_time1, end_time, end_time1;

    int64_t duration, duration1;

    int i;

    AVStream *st;

    start_time = INT64_MAX;

    end_time = INT64_MIN;

    duration = INT64_MIN;

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

        st = ic->streams[i];

        if (st->start_time != AV_NOPTS_VALUE) {

            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);

            if (start_time1 < start_time)

                start_time = start_time1;

            if (st->duration != AV_NOPTS_VALUE) {

                end_time1 = start_time1

                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);

                if (end_time1 > end_time)

                    end_time = end_time1;

            }

        }

        if (st->duration != AV_NOPTS_VALUE) {

            duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);

            if (duration1 > duration)

                duration = duration1;

        }

    }

    if (start_time != INT64_MAX) {

        ic->start_time = start_time;

        if (end_time != INT64_MIN) {

            if (end_time - start_time > duration)

                duration = end_time - start_time;

        }

    }

    if (duration != INT64_MIN) {

        ic->duration = duration;

        if (ic->file_size > 0) {

            /* compute the bitrate */

            ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /

                (double)ic->duration;

        }

    }

}


static inline int get_a32_user_mem_index(DisasContext *s)

{

    /* Return the core mmu_idx to use for A32/T32 "unprivileged load/store"

     * insns:

     *  if PL2, UNPREDICTABLE (we choose to implement as if PL0)

     *  otherwise, access as if at PL0.

     */

    switch (s->mmu_idx) {

    case ARMMMUIdx_S1E2:        /* this one is UNPREDICTABLE */

    case ARMMMUIdx_S12NSE0:

    case ARMMMUIdx_S12NSE1:

        return arm_to_core_mmu_idx(ARMMMUIdx_S12NSE0);

    case ARMMMUIdx_S1E3:

    case ARMMMUIdx_S1SE0:

    case ARMMMUIdx_S1SE1:

        return arm_to_core_mmu_idx(ARMMMUIdx_S1SE0);

    case ARMMMUIdx_S2NS:

    default:

        g_assert_not_reached();

    }

}


static uint32_t virtio_net_bad_features(VirtIODevice *vdev)

{

    uint32_t features = 0;

    /* Linux kernel 2.6.25.  It understood MAC (as everyone must),

     * but also these: */

    features |= (1 << VIRTIO_NET_F_MAC);

    features |= (1 << VIRTIO_NET_F_GUEST_CSUM);

    features |= (1 << VIRTIO_NET_F_GUEST_TSO4);

    features |= (1 << VIRTIO_NET_F_GUEST_TSO6);

    features |= (1 << VIRTIO_NET_F_GUEST_ECN);

    return features & virtio_net_get_features(vdev);

}


void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)

{

    uint64_t expire_time;

    expire_time = qemu_get_be64(f);

    if (expire_time != -1) {

        qemu_mod_timer(ts, expire_time);

    } else {

        qemu_del_timer(ts);

    }

}


static void qemu_co_queue_next_bh(void *opaque)

{

    Coroutine *next;

    trace_qemu_co_queue_next_bh();

    while ((next = QTAILQ_FIRST(&unlock_bh_queue))) {

        QTAILQ_REMOVE(&unlock_bh_queue, next, co_queue_next);

        qemu_coroutine_enter(next, NULL);

    }

}


static void test_to_from_buf_1(void)

{

     unsigned niov;

     struct iovec *iov;

     size_t sz;

     unsigned char *ibuf, *obuf;

     unsigned i, j, n;

     iov_random(&iov, &niov);

     sz = iov_size(iov, niov);

     ibuf = g_malloc(sz + 8) + 4;

     memcpy(ibuf-4, "aaaa", 4); memcpy(ibuf + sz, "bbbb", 4);

     obuf = g_malloc(sz + 8) + 4;

     memcpy(obuf-4, "xxxx", 4); memcpy(obuf + sz, "yyyy", 4);

     /* fill in ibuf with 0123456... */

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

         ibuf[i] = i & 255;

     }

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

         /* Test from/to buf for offset(i) in [0..sz] up to the end of buffer.

          * For last iteration with offset == sz, the procedure should

          * skip whole vector and process exactly 0 bytes */

         /* first set bytes [i..sz) to some "random" value */

         n = iov_memset(iov, niov, 0, 0xff, -1);

         g_assert(n == sz);

         /* next copy bytes [i..sz) from ibuf to iovec */

         n = iov_from_buf(iov, niov, i, ibuf + i, -1);

         g_assert(n == sz - i);

         /* clear part of obuf */

         memset(obuf + i, 0, sz - i);

         /* and set this part of obuf to values from iovec */

         n = iov_to_buf(iov, niov, i, obuf + i, -1);

         g_assert(n == sz - i);

         /* now compare resulting buffers */

         g_assert(memcmp(ibuf, obuf, sz) == 0);

         /* test just one char */

         n = iov_to_buf(iov, niov, i, obuf + i, 1);

         g_assert(n == (i < sz));

         if (n) {

             g_assert(obuf[i] == (i & 255));

         }

         for (j = i; j <= sz; ++j) {

             /* now test num of bytes cap up to byte no. j,

              * with j in [i..sz]. */

             /* clear iovec */

             n = iov_memset(iov, niov, 0, 0xff, -1);

             g_assert(n == sz);

             /* copy bytes [i..j) from ibuf to iovec */

             n = iov_from_buf(iov, niov, i, ibuf + i, j - i);

             g_assert(n == j - i);

             /* clear part of obuf */

             memset(obuf + i, 0, j - i);

             /* copy bytes [i..j) from iovec to obuf */

             n = iov_to_buf(iov, niov, i, obuf + i, j - i);

             g_assert(n == j - i);

             /* verify result */

             g_assert(memcmp(ibuf, obuf, sz) == 0);

             /* now actually check if the iovec contains the right data */

             test_iov_bytes(iov, niov, i, j - i);

         }

    }

    g_assert(!memcmp(ibuf-4, "aaaa", 4) && !memcmp(ibuf+sz, "bbbb", 4));

    g_free(ibuf-4);

    g_assert(!memcmp(obuf-4, "xxxx", 4) && !memcmp(obuf+sz, "yyyy", 4));

    g_free(obuf-4);

    iov_free(iov, niov);

}


static uint64_t exynos4210_i2c_read(void *opaque, target_phys_addr_t offset,

                                 unsigned size)

{

    Exynos4210I2CState *s = (Exynos4210I2CState *)opaque;

    uint8_t value;

    switch (offset) {

    case I2CCON_ADDR:

        value = s->i2ccon;

        break;

    case I2CSTAT_ADDR:

        value = s->i2cstat;

        break;

    case I2CADD_ADDR:

        value = s->i2cadd;

        break;

    case I2CDS_ADDR:

        value = s->i2cds;

        s->scl_free = true;

        if (EXYNOS4_I2C_MODE(s->i2cstat) == I2CMODE_MASTER_Rx &&

               (s->i2cstat & I2CSTAT_START_BUSY) &&

               !(s->i2ccon & I2CCON_INT_PEND)) {

            exynos4210_i2c_data_receive(s);

        }

        break;

    case I2CLC_ADDR:

        value = s->i2clc;

        break;

    default:

        value = 0;

        DPRINT("ERROR: Bad read offset 0x%x\n", (unsigned int)offset);

        break;

    }

    DPRINT("read %s [0x%02x] -> 0x%02x\n", exynos4_i2c_get_regname(offset),

            (unsigned int)offset, value);

    return value;

}


int unix_socket_incoming(const char *path)

{

    Error *local_err = NULL;

    int fd = unix_listen(path, NULL, 0, &local_err);

    if (local_err != NULL) {

        qerror_report_err(local_err);

        error_free(local_err);

    }

    return fd;

}


static int iscsi_reopen_prepare(BDRVReopenState *state,

                                BlockReopenQueue *queue, Error **errp)

{

    /* NOP */

    return 0;

}


static void raw_probe_alignment(BlockDriverState *bs, Error **errp)

{

    BDRVRawState *s = bs->opaque;

    DWORD sectorsPerCluster, freeClusters, totalClusters, count;

    DISK_GEOMETRY_EX dg;

    BOOL status;

    if (s->type == FTYPE_CD) {

        bs->request_alignment = 2048;

        return;

    }

    if (s->type == FTYPE_HARDDISK) {

        status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,

                                 NULL, 0, &dg, sizeof(dg), &count, NULL);

        if (status != 0) {

            bs->request_alignment = dg.Geometry.BytesPerSector;

            return;

        }

        /* try GetDiskFreeSpace too */

    }

    if (s->drive_path[0]) {

        GetDiskFreeSpace(s->drive_path, &sectorsPerCluster,

                         &dg.Geometry.BytesPerSector,

                         &freeClusters, &totalClusters);

        bs->request_alignment = dg.Geometry.BytesPerSector;

    }

}


static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path,

                              const char *name, V9fsPath *target)

{

    if (ctx->export_flags & V9FS_SM_MAPPED_FILE &&

        local_is_mapped_file_metadata(ctx, name)) {

        errno = EINVAL;

        return -1;

    }

    if (dir_path) {

        v9fs_path_sprintf(target, "%s/%s", dir_path->data, name);

    } else if (strcmp(name, "/")) {

        v9fs_path_sprintf(target, "%s", name);

    } else {

        /* We want the path of the export root to be relative, otherwise

         * "*at()" syscalls would treat it as "/" in the host.

         */

        v9fs_path_sprintf(target, "%s", ".");

    }

    return 0;

}


static inline void gen_op_fcmpes(int fccno, TCGv r_rs1, TCGv r_rs2)

{

    gen_helper_fcmpes(cpu_env, r_rs1, r_rs2);

}


long do_sigreturn(CPUMIPSState *regs)

{

    struct sigframe *frame;

    abi_ulong frame_addr;

    sigset_t blocked;

    target_sigset_t target_set;

    int i;

#if defined(DEBUG_SIGNAL)

    fprintf(stderr, "do_sigreturn\n");

#endif

    frame_addr = regs->active_tc.gpr[29];

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

   	goto badframe;

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

   	if(__get_user(target_set.sig[i], &frame->sf_mask.sig[i]))

	    goto badframe;

    }

    target_to_host_sigset_internal(&blocked, &target_set);

    sigprocmask(SIG_SETMASK, &blocked, NULL);

    if (restore_sigcontext(regs, &frame->sf_sc))

   	goto badframe;

#if 0

    /*

     * Don't let your children do this ...

     */

    __asm__ __volatile__(

   	"move\t$29, %0\n\t"

   	"j\tsyscall_exit"

   	:/* no outputs */

   	:"r" (&regs));

    /* Unreached */

#endif

    regs->active_tc.PC = regs->CP0_EPC;

    mips_set_hflags_isa_mode_from_pc(regs);

    /* I am not sure this is right, but it seems to work

    * maybe a problem with nested signals ? */

    regs->CP0_EPC = 0;

    return -TARGET_QEMU_ESIGRETURN;

badframe:

    force_sig(TARGET_SIGSEGV/*, current*/);

    return 0;

}


static int con_init(struct XenDevice *xendev)

{

    struct XenConsole *con = container_of(xendev, struct XenConsole, xendev);

    char *type, *dom;

    int ret = 0;

    /* setup */

    dom = xs_get_domain_path(xenstore, con->xendev.dom);

    snprintf(con->console, sizeof(con->console), "%s/console", dom);

    free(dom);

    type = xenstore_read_str(con->console, "type");

    if (!type || strcmp(type, "ioemu") != 0) {

	xen_be_printf(xendev, 1, "not for me (type=%s)\n", type);

        ret = -1;

        goto out;

    }

    if (!serial_hds[con->xendev.dev])

	xen_be_printf(xendev, 1, "WARNING: serial line %d not configured\n",

                      con->xendev.dev);

    else

        con->chr = serial_hds[con->xendev.dev];

out:

    qemu_free(type);

    return ret;

}


av_cold int ff_intrax8_common_init(AVCodecContext *avctx,

                                   IntraX8Context *w, IDCTDSPContext *idsp,

                                   int16_t (*block)[64],

                                   int block_last_index[12],

                                   int mb_width, int mb_height)

{

    int ret = x8_vlc_init();

    if (ret < 0)

        return ret;

    w->avctx = avctx;

    w->idsp = *idsp;

    w->mb_width  = mb_width;

    w->mb_height = mb_height;

    w->block = block;

    w->block_last_index = block_last_index;

    // two rows, 2 blocks per cannon mb

    w->prediction_table = av_mallocz(w->mb_width * 2 * 2);

    if (!w->prediction_table)

        return AVERROR(ENOMEM);

    ff_init_scantable(w->idsp.idct_permutation, &w->scantable[0],

                      ff_wmv1_scantable[0]);

    ff_init_scantable(w->idsp.idct_permutation, &w->scantable[1],

                      ff_wmv1_scantable[2]);

    ff_init_scantable(w->idsp.idct_permutation, &w->scantable[2],

                      ff_wmv1_scantable[3]);

    ff_intrax8dsp_init(&w->dsp);

    ff_blockdsp_init(&w->bdsp, avctx);

    return 0;

}


static void string_output_free(Visitor *v)

{

    StringOutputVisitor *sov = to_sov(v);

    string_output_visitor_cleanup(sov);

}


static void external_snapshot_abort(BlkActionState *common)

{

    ExternalSnapshotState *state =

                             DO_UPCAST(ExternalSnapshotState, common, common);

    if (state->new_bs) {

        if (state->new_bs->backing) {

            bdrv_replace_in_backing_chain(state->new_bs, state->old_bs);

        }

    }

}


static void virtio_ccw_device_plugged(DeviceState *d, Error **errp)

{

    VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);

    VirtIODevice *vdev = virtio_bus_get_device(&dev->bus);

    CcwDevice *ccw_dev = CCW_DEVICE(d);

    SubchDev *sch = ccw_dev->sch;

    int n = virtio_get_num_queues(vdev);

    S390FLICState *flic = s390_get_flic();

    if (!virtio_has_feature(vdev->host_features, VIRTIO_F_VERSION_1)) {

        dev->max_rev = 0;

    }

    if (virtio_get_num_queues(vdev) > VIRTIO_CCW_QUEUE_MAX) {

        error_setg(errp, "The number of virtqueues %d "

                   "exceeds ccw limit %d", n,

                   VIRTIO_CCW_QUEUE_MAX);

        return;

    }

    if (virtio_get_num_queues(vdev) > flic->adapter_routes_max_batch) {

        error_setg(errp, "The number of virtqueues %d "

                   "exceeds flic adapter route limit %d", n,

                   flic->adapter_routes_max_batch);

        return;

    }

    sch->id.cu_model = virtio_bus_get_vdev_id(&dev->bus);

    css_generate_sch_crws(sch->cssid, sch->ssid, sch->schid,

                          d->hotplugged, 1);

}


HELPER_LD(lbu, ldub, uint8_t)

HELPER_LD(lhu, lduw, uint16_t)

HELPER_LD(lw, ldl, int32_t)

HELPER_LD(ld, ldq, int64_t)

#undef HELPER_LD

#if defined(CONFIG_USER_ONLY)

#define HELPER_ST(name, insn, type)                                     \

static inline void do_##name(CPUMIPSState *env, target_ulong addr,      \

                             type val, int mem_idx)                     \

{                                                                       \

    cpu_##insn##_data(env, addr, val);                                  \

}

#else

#define HELPER_ST(name, insn, type)                                     \

static inline void do_##name(CPUMIPSState *env, target_ulong addr,      \

                             type val, int mem_idx)                     \

{                                                                       \

    switch (mem_idx)                                                    \

    {                                                                   \

    case 0: cpu_##insn##_kernel(env, addr, val); break;                 \

    case 1: cpu_##insn##_super(env, addr, val); break;                  \

    default:                                                            \

    case 2: cpu_##insn##_user(env, addr, val); break;                   \

    }                                                                   \

}

#endif

HELPER_ST(sb, stb, uint8_t)

HELPER_ST(sh, stw, uint16_t)

HELPER_ST(sw, stl, uint32_t)

HELPER_ST(sd, stq, uint64_t)

#undef HELPER_ST

target_ulong helper_clo (target_ulong arg1)

{

    return clo32(arg1);

}


static void do_video_out(AVFormatContext *s,

                         OutputStream *ost,

                         InputStream *ist,

                         AVFrame *in_picture,

                         int *frame_size, float quality)

{

    int nb_frames, i, ret, format_video_sync;

    AVFrame *final_picture;

    AVCodecContext *enc;

    double sync_ipts;

    enc = ost->st->codec;

    sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);

    /* by default, we output a single frame */

    nb_frames = 1;

    *frame_size = 0;

    format_video_sync = video_sync_method;

    if (format_video_sync < 0)

        format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :

                            (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;

    if (format_video_sync) {

        double vdelta = sync_ipts - ost->sync_opts;

        //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c

        if (vdelta < -1.1)

            nb_frames = 0;

        else if (format_video_sync == 2) {

            if(vdelta<=-0.6){

                nb_frames=0;

            }else if(vdelta>0.6)

                ost->sync_opts= lrintf(sync_ipts);

        }else if (vdelta > 1.1)

            nb_frames = lrintf(vdelta);

//fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);

        if (nb_frames == 0){

            ++nb_frames_drop;

            av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");

        }else if (nb_frames > 1) {

            nb_frames_dup += nb_frames - 1;

            av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames-1);

        }

    }else

        ost->sync_opts= lrintf(sync_ipts);

    nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);

    if (nb_frames <= 0)

        return;

    do_video_resample(ost, ist, in_picture, &final_picture);

    /* duplicates frame if needed */

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

        AVPacket pkt;

        av_init_packet(&pkt);

        pkt.stream_index= ost->index;

        if (s->oformat->flags & AVFMT_RAWPICTURE) {

            /* raw pictures are written as AVPicture structure to

               avoid any copies. We support temporarily the older

               method. */

            enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;

            enc->coded_frame->top_field_first  = in_picture->top_field_first;

            pkt.data= (uint8_t *)final_picture;

            pkt.size=  sizeof(AVPicture);

            pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);

            pkt.flags |= AV_PKT_FLAG_KEY;

            write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);

        } else {

            AVFrame big_picture;

            big_picture= *final_picture;

            /* better than nothing: use input picture interlaced

               settings */

            big_picture.interlaced_frame = in_picture->interlaced_frame;

            if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {

                if (ost->top_field_first == -1)

                    big_picture.top_field_first = in_picture->top_field_first;

                else

                    big_picture.top_field_first = !!ost->top_field_first;

            }

            /* handles same_quant here. This is not correct because it may

               not be a global option */

            big_picture.quality = quality;

            if (!enc->me_threshold)

                big_picture.pict_type = 0;

//            big_picture.pts = AV_NOPTS_VALUE;

            big_picture.pts= ost->sync_opts;

//            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);

//av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);

            if (ost->forced_kf_index < ost->forced_kf_count &&

                big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {

                big_picture.pict_type = AV_PICTURE_TYPE_I;

                ost->forced_kf_index++;

            }

            ret = avcodec_encode_video(enc,

                                       bit_buffer, bit_buffer_size,

                                       &big_picture);

            if (ret < 0) {

                av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

                exit_program(1);

            }

            if(ret>0){

                pkt.data= bit_buffer;

                pkt.size= ret;

                if(enc->coded_frame->pts != AV_NOPTS_VALUE)

                    pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);

/*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",

   pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,

   pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/

                if(enc->coded_frame->key_frame)

                    pkt.flags |= AV_PKT_FLAG_KEY;

                write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);

                *frame_size = ret;

                video_size += ret;

                //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",

                //        enc->frame_number-1, ret, enc->pict_type);

                /* if two pass, output log */

                if (ost->logfile && enc->stats_out) {

                    fprintf(ost->logfile, "%s", enc->stats_out);

                }

            }

        }

        ost->sync_opts++;

        ost->frame_number++;

    }

}


static void vc1_decode_i_blocks_adv(VC1Context *v)

{

    int k, j;

    MpegEncContext *s = &v->s;

    int cbp, val;

    uint8_t *coded_val;

    int mb_pos;

    int mquant = v->pq;

    int mqdiff;

    int overlap;

    GetBitContext *gb = &s->gb;

    /* select codingmode used for VLC tables selection */

    switch(v->y_ac_table_index){

    case 0:

        v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;

        break;

    case 1:

        v->codingset = CS_HIGH_MOT_INTRA;

        break;

    case 2:

        v->codingset = CS_MID_RATE_INTRA;

        break;

    }

    switch(v->c_ac_table_index){

    case 0:

        v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;

        break;

    case 1:

        v->codingset2 = CS_HIGH_MOT_INTER;

        break;

    case 2:

        v->codingset2 = CS_MID_RATE_INTER;

        break;

    }

    /* Set DC scale - y and c use the same */

    s->y_dc_scale = s->y_dc_scale_table[v->pq];

    s->c_dc_scale = s->c_dc_scale_table[v->pq];

    //do frame decode

    s->mb_x = s->mb_y = 0;

    s->mb_intra = 1;

    s->first_slice_line = 1;

    ff_er_add_slice(s, 0, 0, s->mb_width - 1, s->mb_height - 1, (AC_END|DC_END|MV_END));

    for(s->mb_y = 0; s->mb_y < s->mb_height; s->mb_y++) {

        for(s->mb_x = 0; s->mb_x < s->mb_width; s->mb_x++) {

            ff_init_block_index(s);

            ff_update_block_index(s);

            s->dsp.clear_blocks(s->block[0]);

            mb_pos = s->mb_x + s->mb_y * s->mb_stride;

            s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;

            s->current_picture.motion_val[1][s->block_index[0]][0] = 0;

            s->current_picture.motion_val[1][s->block_index[0]][1] = 0;

            // do actual MB decoding and displaying

            cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);

            if(v->acpred_is_raw)

                v->s.ac_pred = get_bits(&v->s.gb, 1);

            else

                v->s.ac_pred = v->acpred_plane[mb_pos];

            if(v->condover == CONDOVER_SELECT) {

                if(v->overflg_is_raw)

                    overlap = get_bits(&v->s.gb, 1);

                else

                    overlap = v->over_flags_plane[mb_pos];

            } else

                overlap = (v->condover == CONDOVER_ALL);

            GET_MQUANT();

            s->current_picture.qscale_table[mb_pos] = mquant;

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

                val = ((cbp >> (5 - k)) & 1);

                if (k < 4) {

                    int pred = vc1_coded_block_pred(&v->s, k, &coded_val);

                    val = val ^ pred;

                    *coded_val = val;

                }

                cbp |= val << (5 - k);

                v->a_avail = !s->first_slice_line || (k==2 || k==3);

                v->c_avail = !!s->mb_x || (k==1 || k==3);

                vc1_decode_i_block_adv(v, s->block[k], k, val, (k<4)? v->codingset : v->codingset2, mquant);

                s->dsp.vc1_inv_trans_8x8(s->block[k]);

                for(j = 0; j < 64; j++) s->block[k][j] += 128;

            }

            vc1_put_block(v, s->block);

            if(overlap) {

                if(s->mb_x) {

                    s->dsp.vc1_h_overlap(s->dest[0], s->linesize, 0);

                    s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize, s->linesize, 0);

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

                        s->dsp.vc1_h_overlap(s->dest[1], s->uvlinesize, s->mb_x&1);

                        s->dsp.vc1_h_overlap(s->dest[2], s->uvlinesize, s->mb_x&1);

                    }

                }

                s->dsp.vc1_h_overlap(s->dest[0] + 8, s->linesize, 1);

                s->dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize, 1);

                if(!s->first_slice_line) {

                    s->dsp.vc1_v_overlap(s->dest[0], s->linesize, 0);

                    s->dsp.vc1_v_overlap(s->dest[0] + 8, s->linesize, 0);

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

                        s->dsp.vc1_v_overlap(s->dest[1], s->uvlinesize, s->mb_y&1);

                        s->dsp.vc1_v_overlap(s->dest[2], s->uvlinesize, s->mb_y&1);

                    }

                }

                s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize, s->linesize, 1);

                s->dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize, 1);

            }

            if(get_bits_count(&s->gb) > v->bits) {

                av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n", get_bits_count(&s->gb), v->bits);

                return;

            }

        }

        ff_draw_horiz_band(s, s->mb_y * 16, 16);

        s->first_slice_line = 0;

    }

}


static int parse_channel_name(char **arg, int *rchannel, int *rnamed)

{

    char buf[8];

    int len, i, channel_id = 0;

    int64_t layout, layout0;

    /* try to parse a channel name, e.g. "FL" */

    if (sscanf(*arg, " %7[A-Z] %n", buf, &len)) {

        layout0 = layout = av_get_channel_layout(buf);

        /* channel_id <- first set bit in layout */

        for (i = 32; i > 0; i >>= 1) {

            if (layout >= (int64_t)1 << i) {

                channel_id += i;

                layout >>= i;

            }

        }

        /* reject layouts that are not a single channel */

        if (channel_id >= MAX_CHANNELS || layout0 != (int64_t)1 << channel_id)

            return AVERROR(EINVAL);

        *rchannel = channel_id;

        *rnamed = 1;

        *arg += len;

        return 0;

    }

    /* try to parse a channel number, e.g. "c2" */

    if (sscanf(*arg, " c%d %n", &channel_id, &len) &&

        channel_id >= 0 && channel_id < MAX_CHANNELS) {

        *rchannel = channel_id;

        *rnamed = 0;

        *arg += len;

        return 0;

    }

    return AVERROR(EINVAL);

}


int qcow2_grow_l1_table(BlockDriverState *bs, int min_size)

{

    BDRVQcowState *s = bs->opaque;

    int new_l1_size, new_l1_size2, ret, i;

    uint64_t *new_l1_table;

    int64_t new_l1_table_offset;

    uint8_t data[12];

    new_l1_size = s->l1_size;

    if (min_size <= new_l1_size)

        return 0;

    if (new_l1_size == 0) {

        new_l1_size = 1;

    }

    while (min_size > new_l1_size) {

        new_l1_size = (new_l1_size * 3 + 1) / 2;

    }

#ifdef DEBUG_ALLOC2

    printf("grow l1_table from %d to %d\n", s->l1_size, new_l1_size);

#endif

    new_l1_size2 = sizeof(uint64_t) * new_l1_size;

    new_l1_table = qemu_mallocz(align_offset(new_l1_size2, 512));

    memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));

    /* write new table (align to cluster) */

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);

    new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);

    if (new_l1_table_offset < 0) {

        qemu_free(new_l1_table);

        return new_l1_table_offset;

    }

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);

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

        new_l1_table[i] = cpu_to_be64(new_l1_table[i]);

    ret = bdrv_pwrite(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);

    if (ret != new_l1_size2)

        goto fail;

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

        new_l1_table[i] = be64_to_cpu(new_l1_table[i]);

    /* set new table */

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);

    cpu_to_be32w((uint32_t*)data, new_l1_size);

    cpu_to_be64w((uint64_t*)(data + 4), new_l1_table_offset);

    ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));

    if (ret != sizeof(data)) {

        goto fail;

    }

    qemu_free(s->l1_table);

    qcow2_free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));

    s->l1_table_offset = new_l1_table_offset;

    s->l1_table = new_l1_table;

    s->l1_size = new_l1_size;

    return 0;

 fail:

    qemu_free(new_l1_table);

    qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2);

    return ret < 0 ? ret : -EIO;

}


static void clr_msg_flags(IPMIBmcSim *ibs,

                          uint8_t *cmd, unsigned int cmd_len,

                          uint8_t *rsp, unsigned int *rsp_len,

                          unsigned int max_rsp_len)

{

    IPMIInterface *s = ibs->parent.intf;

    IPMIInterfaceClass *k = IPMI_INTERFACE_GET_CLASS(s);

    IPMI_CHECK_CMD_LEN(3);

    ibs->msg_flags &= ~cmd[2];

    k->set_atn(s, attn_set(ibs), attn_irq_enabled(ibs));

}


static int pci_ich9_ahci_init(PCIDevice *dev)

{

    struct AHCIPCIState *d;

    d = DO_UPCAST(struct AHCIPCIState, card, dev);

    pci_config_set_vendor_id(d->card.config, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(d->card.config, PCI_DEVICE_ID_INTEL_82801IR);

    pci_config_set_class(d->card.config, PCI_CLASS_STORAGE_SATA);

    pci_config_set_revision(d->card.config, 0x02);

    pci_config_set_prog_interface(d->card.config, AHCI_PROGMODE_MAJOR_REV_1);

    d->card.config[PCI_CACHE_LINE_SIZE] = 0x08;  /* Cache line size */

    d->card.config[PCI_LATENCY_TIMER]   = 0x00;  /* Latency timer */

    pci_config_set_interrupt_pin(d->card.config, 1);

    /* XXX Software should program this register */

    d->card.config[0x90]   = 1 << 6; /* Address Map Register - AHCI mode */

    qemu_register_reset(ahci_reset, d);

    /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */

    pci_register_bar_simple(&d->card, 5, 0x1000, 0, d->ahci.mem);

    msi_init(dev, 0x50, 1, true, false);

    ahci_init(&d->ahci, &dev->qdev, 6);

    d->ahci.irq = d->card.irq[0];

    return 0;

}


static void get_attachment(AVFormatContext *s, AVIOContext *pb, int length)

{

    char mime[1024];

    char description[1024];

    unsigned int filesize;

    AVStream *st;

    int64_t pos = avio_tell(pb);

    avio_get_str16le(pb, INT_MAX, mime, sizeof(mime));

    if (strcmp(mime, "image/jpeg"))

        goto done;

    avio_r8(pb);

    avio_get_str16le(pb, INT_MAX, description, sizeof(description));

    filesize = avio_rl32(pb);

    if (!filesize)

        goto done;

    st = avformat_new_stream(s, NULL);

    if (!st)

        goto done;

    av_dict_set(&st->metadata, "title", description, 0);

    st->codec->codec_id   = AV_CODEC_ID_MJPEG;

    st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;

    st->codec->extradata  = av_mallocz(filesize);

    if (!st->codec->extradata)

        goto done;

    st->codec->extradata_size = filesize;

    avio_read(pb, st->codec->extradata, filesize);

done:

    avio_seek(pb, pos + length, SEEK_SET);

}


static int parse_filename(char *filename, char **representation_id,

                          char **initialization_pattern, char **media_pattern) {

    char *underscore_pos = NULL;

    char *period_pos = NULL;

    char *temp_pos = NULL;

    char *filename_str = av_strdup(filename);

    if (!filename_str) return AVERROR(ENOMEM);

    temp_pos = av_stristr(filename_str, "_");

    while (temp_pos) {

        underscore_pos = temp_pos + 1;

        temp_pos = av_stristr(temp_pos + 1, "_");

    }

    if (!underscore_pos) return -1;

    period_pos = av_stristr(underscore_pos, ".");

    if (!period_pos) return -1;

    *(underscore_pos - 1) = 0;

    if (representation_id) {

        *representation_id = av_malloc(period_pos - underscore_pos + 1);

        if (!(*representation_id)) return AVERROR(ENOMEM);

        av_strlcpy(*representation_id, underscore_pos, period_pos - underscore_pos + 1);

    }

    if (initialization_pattern) {

        *initialization_pattern = av_asprintf("%s_$RepresentationID$.hdr",

                                              filename_str);

        if (!(*initialization_pattern)) return AVERROR(ENOMEM);

    }

    if (media_pattern) {

        *media_pattern = av_asprintf("%s_$RepresentationID$_$Number$.chk",

                                     filename_str);

        if (!(*media_pattern)) return AVERROR(ENOMEM);

    }

    av_free(filename_str);

    return 0;

}


struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,

                                          int64_t whence, Error **errp)

{

    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);

    GuestFileSeek *seek_data = NULL;

    FILE *fh;

    int ret;

    if (!gfh) {

        return NULL;

    fh = gfh->fh;

    ret = fseek(fh, offset, whence);

    if (ret == -1) {

        error_setg_errno(errp, errno, "failed to seek file");

    } else {

        seek_data = g_new0(GuestFileSeek, 1);

        seek_data->position = ftell(fh);

        seek_data->eof = feof(fh);

    clearerr(fh);

    return seek_data;


static void tpm_passthrough_cancel_cmd(TPMBackend *tb)

{

    TPMPassthruState *tpm_pt = TPM_PASSTHROUGH(tb);

    int n;

    /*

     * As of Linux 3.7 the tpm_tis driver does not properly cancel

     * commands on all TPM manufacturers' TPMs.

     * Only cancel if we're busy so we don't cancel someone else's

     * command, e.g., a command executed on the host.

     */

    if (tpm_pt->tpm_executing) {

        if (tpm_pt->cancel_fd >= 0) {

            n = write(tpm_pt->cancel_fd, "-", 1);

            if (n != 1) {

                error_report("Canceling TPM command failed: %s",

                             strerror(errno));

            } else {

                tpm_pt->tpm_op_canceled = true;

            }

        } else {

            error_report("Cannot cancel TPM command due to missing "

                         "TPM sysfs cancel entry");

        }

    }

}


static void celt_denormalize(CeltFrame *f, CeltBlock *block, float *data)

{

    int i, j;

    for (i = f->start_band; i < f->end_band; i++) {

        float *dst = data + (ff_celt_freq_bands[i] << f->size);

        float norm = exp2f(block->energy[i] + ff_celt_mean_energy[i]);

        for (j = 0; j < ff_celt_freq_range[i] << f->size; j++)

            dst[j] *= norm;

    }

}


static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                             const AVFrame *frame, int *got_packet_ptr)

{

    FlacEncodeContext *s;

    const int16_t *samples;

    int frame_bytes, out_bytes, ret;

    s = avctx->priv_data;

    /* when the last block is reached, update the header in extradata */

    if (!frame) {

        s->max_framesize = s->max_encoded_framesize;

        av_md5_final(s->md5ctx, s->md5sum);

        write_streaminfo(s, avctx->extradata);

        return 0;

    }

    samples = (const int16_t *)frame->data[0];

    /* change max_framesize for small final frame */

    if (frame->nb_samples < s->frame.blocksize) {

        s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,

                                                      s->channels, 16);

    }

    init_frame(s, frame->nb_samples);

    copy_samples(s, samples);

    channel_decorrelation(s);

    remove_wasted_bits(s);

    frame_bytes = encode_frame(s);

    /* fallback to verbatim mode if the compressed frame is larger than it

       would be if encoded uncompressed. */

    if (frame_bytes > s->max_framesize) {

        s->frame.verbatim_only = 1;

        frame_bytes = encode_frame(s);

    }

    if ((ret = ff_alloc_packet(avpkt, frame_bytes))) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");

        return ret;

    }

    out_bytes = write_frame(s, avpkt);

    s->frame_count++;

    s->sample_count += frame->nb_samples;

    if ((ret = update_md5_sum(s, samples)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");

        return ret;

    }

    if (out_bytes > s->max_encoded_framesize)

        s->max_encoded_framesize = out_bytes;

    if (out_bytes < s->min_framesize)

        s->min_framesize = out_bytes;

    avpkt->pts      = frame->pts;

    avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);

    avpkt->size     = out_bytes;

    *got_packet_ptr = 1;

    return 0;

}


TC6393xbState *tc6393xb_init(MemoryRegion *sysmem, uint32_t base, qemu_irq irq)

{

    TC6393xbState *s;

    DriveInfo *nand;

    static const MemoryRegionOps tc6393xb_ops = {

        .read = tc6393xb_readb,

        .write = tc6393xb_writeb,

        .endianness = DEVICE_NATIVE_ENDIAN,

        .impl = {

            .min_access_size = 1,

            .max_access_size = 1,

        },

    };

    s = (TC6393xbState *) g_malloc0(sizeof(TC6393xbState));

    s->irq = irq;

    s->gpio_in = qemu_allocate_irqs(tc6393xb_gpio_set, s, TC6393XB_GPIOS);

    s->l3v = qemu_allocate_irq(tc6393xb_l3v, s, 0);

    s->blanked = 1;

    s->sub_irqs = qemu_allocate_irqs(tc6393xb_sub_irq, s, TC6393XB_NR_IRQS);

    nand = drive_get(IF_MTD, 0, 0);

    s->flash = nand_init(nand ? blk_by_legacy_dinfo(nand) : NULL,

                         NAND_MFR_TOSHIBA, 0x76);

    memory_region_init_io(&s->iomem, NULL, &tc6393xb_ops, s, "tc6393xb", 0x10000);

    memory_region_add_subregion(sysmem, base, &s->iomem);

    memory_region_init_ram(&s->vram, NULL, "tc6393xb.vram", 0x100000,

                           &error_abort);

    vmstate_register_ram_global(&s->vram);

    s->vram_ptr = memory_region_get_ram_ptr(&s->vram);

    memory_region_add_subregion(sysmem, base + 0x100000, &s->vram);

    s->scr_width = 480;

    s->scr_height = 640;

    s->con = graphic_console_init(NULL, 0, &tc6393xb_gfx_ops, s);

    return s;

}


static int cdg_decode_frame(AVCodecContext *avctx,

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

{

    GetByteContext gb;

    int buf_size       = avpkt->size;

    int ret;

    uint8_t command, inst;

    uint8_t cdg_data[CDG_DATA_SIZE];

    AVFrame *frame = data;

    CDGraphicsContext *cc = avctx->priv_data;

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

    ret = ff_reget_buffer(avctx, cc->frame);

    if (ret) {

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

        return ret;

    }

    if (!avctx->frame_number)

        memset(cc->frame->data[0], 0, cc->frame->linesize[0] * avctx->height);

    command = bytestream2_get_byte(&gb);

    inst    = bytestream2_get_byte(&gb);

    inst    &= CDG_MASK;

    bytestream2_skip(&gb, 2);

    bytestream2_get_buffer(&gb, cdg_data, sizeof(cdg_data));

    if ((command & CDG_MASK) == CDG_COMMAND) {

        switch (inst) {

        case CDG_INST_MEMORY_PRESET:

            if (!(cdg_data[1] & 0x0F))

                memset(cc->frame->data[0], cdg_data[0] & 0x0F,

                       cc->frame->linesize[0] * CDG_FULL_HEIGHT);

            break;

        case CDG_INST_LOAD_PAL_LO:

        case CDG_INST_LOAD_PAL_HIGH:

            if (buf_size - CDG_HEADER_SIZE < CDG_DATA_SIZE) {

                av_log(avctx, AV_LOG_ERROR, "buffer too small for loading palette\n");

                return AVERROR(EINVAL);

            }

            cdg_load_palette(cc, cdg_data, inst == CDG_INST_LOAD_PAL_LO);

            break;

        case CDG_INST_BORDER_PRESET:

            cdg_border_preset(cc, cdg_data);

            break;

        case CDG_INST_TILE_BLOCK_XOR:

        case CDG_INST_TILE_BLOCK:

            if (buf_size - CDG_HEADER_SIZE < CDG_DATA_SIZE) {

                av_log(avctx, AV_LOG_ERROR, "buffer too small for drawing tile\n");

                return AVERROR(EINVAL);

            }

            ret = cdg_tile_block(cc, cdg_data, inst == CDG_INST_TILE_BLOCK_XOR);

            if (ret) {

                av_log(avctx, AV_LOG_ERROR, "tile is out of range\n");

                return ret;

            }

            break;

        case CDG_INST_SCROLL_PRESET:

        case CDG_INST_SCROLL_COPY:

            if (buf_size - CDG_HEADER_SIZE < CDG_MINIMUM_SCROLL_SIZE) {

                av_log(avctx, AV_LOG_ERROR, "buffer too small for scrolling\n");

                return AVERROR(EINVAL);

            }

            ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);

            if (ret) {

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

                return ret;

            }

            cdg_scroll(cc, cdg_data, frame, inst == CDG_INST_SCROLL_COPY);

            av_frame_unref(cc->frame);

            ret = av_frame_ref(cc->frame, frame);

            if (ret < 0)

                return ret;

            break;

        default:

            break;

        }

        if (!frame->data[0]) {

            ret = av_frame_ref(frame, cc->frame);

            if (ret < 0)

                return ret;

        }

        *got_frame = 1;

    } else {

        *got_frame = 0;

        buf_size   = 0;

    }

    return buf_size;

}


void ff_put_h264_qpel8_mc13_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_8w_msa(src + stride - 2,

                           src - (stride * 2), stride, dst, stride, 8);

}


static void kvm_arm_gic_get(GICState *s)

{

    uint32_t reg;

    int i;

    int cpu;

    if (!kvm_arm_gic_can_save_restore(s)) {

            DPRINTF("Cannot get kernel gic state, no kernel interface");

            return;

    }

    /*****************************************************************

     * Distributor State

     */

    /* GICD_CTLR -> s->enabled */

    kvm_gicd_access(s, 0x0, 0, &reg, false);

    s->enabled = reg & 1;

    /* Sanity checking on GICD_TYPER -> s->num_irq, s->num_cpu */

    kvm_gicd_access(s, 0x4, 0, &reg, false);

    s->num_irq = ((reg & 0x1f) + 1) * 32;

    s->num_cpu = ((reg & 0xe0) >> 5) + 1;

    if (s->num_irq > GIC_MAXIRQ) {

            fprintf(stderr, "Too many IRQs reported from the kernel: %d\n",

                    s->num_irq);

            abort();

    }

    /* GICD_IIDR -> ? */

    kvm_gicd_access(s, 0x8, 0, &reg, false);

    /* Verify no GROUP 1 interrupts configured in the kernel */

    for_each_irq_reg(i, s->num_irq, 1) {

        kvm_gicd_access(s, 0x80 + (i * 4), 0, &reg, false);

        if (reg != 0) {

            fprintf(stderr, "Unsupported GICD_IGROUPRn value: %08x\n",

                    reg);

            abort();

        }

    }

    /* Clear all the IRQ settings */

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

        memset(&s->irq_state[i], 0, sizeof(s->irq_state[0]));

    }

    /* GICD_ISENABLERn -> irq_state[n].enabled */

    kvm_dist_get(s, 0x100, 1, s->num_irq, translate_enabled);

    /* GICD_ISPENDRn -> irq_state[n].pending + irq_state[n].level */

    kvm_dist_get(s, 0x200, 1, s->num_irq, translate_pending);

    /* GICD_ISACTIVERn -> irq_state[n].active */

    kvm_dist_get(s, 0x300, 1, s->num_irq, translate_active);

    /* GICD_ICFRn -> irq_state[n].trigger */

    kvm_dist_get(s, 0xc00, 2, s->num_irq, translate_trigger);

    /* GICD_IPRIORITYRn -> s->priorityX[irq] */

    kvm_dist_get(s, 0x400, 8, s->num_irq, translate_priority);

    /* GICD_ITARGETSRn -> s->irq_target[irq] */

    kvm_dist_get(s, 0x800, 8, s->num_irq, translate_targets);

    /* GICD_CPENDSGIRn -> s->sgi_pending */

    kvm_dist_get(s, 0xf10, 8, GIC_NR_SGIS, translate_sgisource);

    /*****************************************************************

     * CPU Interface(s) State

     */

    for (cpu = 0; cpu < s->num_cpu; cpu++) {

        /* GICC_CTLR -> s->cpu_enabled[cpu] */

        kvm_gicc_access(s, 0x00, cpu, &reg, false);

        s->cpu_enabled[cpu] = (reg & 1);

        /* GICC_PMR -> s->priority_mask[cpu] */

        kvm_gicc_access(s, 0x04, cpu, &reg, false);

        s->priority_mask[cpu] = (reg & 0xff);

        /* GICC_BPR -> s->bpr[cpu] */

        kvm_gicc_access(s, 0x08, cpu, &reg, false);

        s->bpr[cpu] = (reg & 0x7);

        /* GICC_ABPR -> s->abpr[cpu] */

        kvm_gicc_access(s, 0x1c, cpu, &reg, false);

        s->abpr[cpu] = (reg & 0x7);

        /* GICC_APRn -> s->apr[n][cpu] */

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

            kvm_gicc_access(s, 0xd0 + i * 4, cpu, &reg, false);

            s->apr[i][cpu] = reg;

        }

    }

}


static void xvid_idct_add(uint8_t *dest, ptrdiff_t line_size, int16_t *block)

{

    ff_xvid_idct(block);

    ff_add_pixels_clamped(block, dest, line_size);

}