static const AVClass *urlcontext_child_class_next(const AVClass *prev)

{

    URLProtocol *p = NULL;

    /* find the protocol that corresponds to prev */

    while (prev && (p = ffurl_protocol_next(p)))

        if (p->priv_data_class == prev)

            break;

    /* find next protocol with priv options */

    while (p = ffurl_protocol_next(p))

        if (p->priv_data_class)

            return p->priv_data_class;

    return NULL;

}


static void do_change_vnc(const char *target)

{

    if (strcmp(target, "passwd") == 0 ||

	strcmp(target, "password") == 0) {

	char password[9];

	monitor_readline("Password: ", 1, password, sizeof(password)-1);

	password[sizeof(password)-1] = '\0';

	if (vnc_display_password(NULL, password) < 0)

	    term_printf("could not set VNC server password\n");

    } else {

	if (vnc_display_open(NULL, target) < 0)

	    term_printf("could not start VNC server on %s\n", target);

    }

}


int ff_get_cpu_flags_x86(void)

{

    int rval = 0;

    int eax, ebx, ecx, edx;

    int max_std_level, max_ext_level, std_caps=0, ext_caps=0;

    int family=0, model=0;

    union { int i[3]; char c[12]; } vendor;

#if ARCH_X86_32

    x86_reg a, c;

    __asm__ volatile (

        /* See if CPUID instruction is supported ... */

        /* ... Get copies of EFLAGS into eax and ecx */

        "pushfl\n\t"

        "pop %0\n\t"

        "mov %0, %1\n\t"

        /* ... Toggle the ID bit in one copy and store */

        /*     to the EFLAGS reg */

        "xor $0x200000, %0\n\t"

        "push %0\n\t"

        "popfl\n\t"

        /* ... Get the (hopefully modified) EFLAGS */

        "pushfl\n\t"

        "pop %0\n\t"

        : "=a" (a), "=c" (c)

        :

        : "cc"

        );

    if (a == c)

        return 0; /* CPUID not supported */

#endif

    cpuid(0, max_std_level, vendor.i[0], vendor.i[2], vendor.i[1]);

    if(max_std_level >= 1){

        cpuid(1, eax, ebx, ecx, std_caps);

        family = ((eax>>8)&0xf) + ((eax>>20)&0xff);

        model  = ((eax>>4)&0xf) + ((eax>>12)&0xf0);

        if (std_caps & (1<<23))

            rval |= AV_CPU_FLAG_MMX;

        if (std_caps & (1<<25))

            rval |= AV_CPU_FLAG_MMX2

#if HAVE_SSE

                  | AV_CPU_FLAG_SSE;

        if (std_caps & (1<<26))

            rval |= AV_CPU_FLAG_SSE2;

        if (ecx & 1)

            rval |= AV_CPU_FLAG_SSE3;

        if (ecx & 0x00000200 )

            rval |= AV_CPU_FLAG_SSSE3;

        if (ecx & 0x00080000 )

            rval |= AV_CPU_FLAG_SSE4;

        if (ecx & 0x00100000 )

            rval |= AV_CPU_FLAG_SSE42;

#if HAVE_AVX

        /* Check OXSAVE and AVX bits */

        if ((ecx & 0x18000000) == 0x18000000) {

            /* Check for OS support */

            xgetbv(0, eax, edx);

            if ((eax & 0x6) == 0x6)

                rval |= AV_CPU_FLAG_AVX;

        }

#endif

#endif

                  ;

    }

    cpuid(0x80000000, max_ext_level, ebx, ecx, edx);

    if(max_ext_level >= 0x80000001){

        cpuid(0x80000001, eax, ebx, ecx, ext_caps);

        if (ext_caps & (1<<31))

            rval |= AV_CPU_FLAG_3DNOW;

        if (ext_caps & (1<<30))

            rval |= AV_CPU_FLAG_3DNOWEXT;

        if (ext_caps & (1<<23))

            rval |= AV_CPU_FLAG_MMX;

        if (ext_caps & (1<<22))

            rval |= AV_CPU_FLAG_MMX2;

        /* Allow for selectively disabling SSE2 functions on AMD processors

           with SSE2 support but not SSE4a. This includes Athlon64, some

           Opteron, and some Sempron processors. MMX, SSE, or 3DNow! are faster

           than SSE2 often enough to utilize this special-case flag.

           AV_CPU_FLAG_SSE2 and AV_CPU_FLAG_SSE2SLOW are both set in this case

           so that SSE2 is used unless explicitly disabled by checking

           AV_CPU_FLAG_SSE2SLOW. */

        if (!strncmp(vendor.c, "AuthenticAMD", 12) &&

            rval & AV_CPU_FLAG_SSE2 && !(ecx & 0x00000040)) {

            rval |= AV_CPU_FLAG_SSE2SLOW;

        }

    }

    if (!strncmp(vendor.c, "GenuineIntel", 12)) {

        if (family == 6 && (model == 9 || model == 13 || model == 14)) {

            /* 6/9 (pentium-m "banias"), 6/13 (pentium-m "dothan"), and 6/14 (core1 "yonah")

            * theoretically support sse2, but it's usually slower than mmx,

            * so let's just pretend they don't. AV_CPU_FLAG_SSE2 is disabled and

            * AV_CPU_FLAG_SSE2SLOW is enabled so that SSE2 is not used unless

            * explicitly enabled by checking AV_CPU_FLAG_SSE2SLOW. The same

            * situation applies for AV_CPU_FLAG_SSE3 and AV_CPU_FLAG_SSE3SLOW. */

            if (rval & AV_CPU_FLAG_SSE2) rval ^= AV_CPU_FLAG_SSE2SLOW|AV_CPU_FLAG_SSE2;

            if (rval & AV_CPU_FLAG_SSE3) rval ^= AV_CPU_FLAG_SSE3SLOW|AV_CPU_FLAG_SSE3;

        }

        /* The Atom processor has SSSE3 support, which is useful in many cases,

         * but sometimes the SSSE3 version is slower than the SSE2 equivalent

         * on the Atom, but is generally faster on other processors supporting

         * SSSE3. This flag allows for selectively disabling certain SSSE3

         * functions on the Atom. */

        if (family == 6 && model == 28)

            rval |= AV_CPU_FLAG_ATOM;

    }

    return rval;

}


static inline void cvtyuvtoRGB (SwsContext *c,

			   vector signed short Y, vector signed short U, vector signed short V,

			   vector signed short *R, vector signed short *G, vector signed short *B)

{

  vector signed   short vx,ux,uvx;

  Y = vec_mradds (Y, c->CY, c->OY);

  U  = vec_sub (U,(vector signed short)

  			vec_splat((vector signed short)AVV(128),0));

  V  = vec_sub (V,(vector signed short)

  			vec_splat((vector signed short)AVV(128),0));

  //   ux  = (CBU*(u<<c->CSHIFT)+0x4000)>>15;

  ux = vec_sl (U, c->CSHIFT);

  *B = vec_mradds (ux, c->CBU, Y);

  // vx  = (CRV*(v<<c->CSHIFT)+0x4000)>>15;

  vx = vec_sl (V, c->CSHIFT);

  *R = vec_mradds (vx, c->CRV, Y);

  // uvx = ((CGU*u) + (CGV*v))>>15;

  uvx = vec_mradds (U, c->CGU, Y);

  *G = vec_mradds (V, c->CGV, uvx);

}


void usb_generic_async_ctrl_complete(USBDevice *s, USBPacket *p)

{

    if (p->len < 0) {

        s->setup_state = SETUP_STATE_IDLE;

    }

    switch (s->setup_state) {

    case SETUP_STATE_SETUP:

        if (p->len < s->setup_len) {

            s->setup_len = p->len;

        }

        s->setup_state = SETUP_STATE_DATA;

        p->len = 8;

        break;

    case SETUP_STATE_ACK:

        s->setup_state = SETUP_STATE_IDLE;

        p->len = 0;

        break;

    default:

        break;

    }

    usb_packet_complete(s, p);

}


static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,

                              const uint8_t *buf, int buf_size)

{

    AVCodecContext *enc = ost->st->codec;

    AVFrame *frame = NULL;

    AVPacket pkt;

    int ret, got_packet;

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    if (buf && buf_size) {

        if (!ost->output_frame) {

            ost->output_frame = avcodec_alloc_frame();

            if (!ost->output_frame) {

                av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");

                exit_program(1);

            }

        }

        frame = ost->output_frame;

        if (frame->extended_data != frame->data)

            av_freep(&frame->extended_data);

        avcodec_get_frame_defaults(frame);

        frame->nb_samples  = buf_size /

                             (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));

        if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,

                                            buf, buf_size, 1)) < 0) {

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

            exit_program(1);

        }

        frame->pts = ost->sync_opts;

        ost->sync_opts += frame->nb_samples;

    }

    got_packet = 0;

    update_benchmark(NULL);

    if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {

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

        exit_program(1);

    }

    update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);

    ret = pkt.size;

    if (got_packet) {

        if (pkt.pts != AV_NOPTS_VALUE)

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

        if (pkt.dts != AV_NOPTS_VALUE) {

            int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);

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

            if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE &&  max > pkt.dts) {

                av_log(s, max - pkt.dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt.dts, max);

                pkt.pts = pkt.dts = max;

            }

        }

        if (pkt.duration > 0)

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

        write_frame(s, &pkt, ost);

        audio_size += pkt.size;

        av_free_packet(&pkt);

    }

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "

               "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

               av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),

               av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));

    }

    return ret;

}


static void rng_egd_opened(RngBackend *b, Error **errp)
{
    RngEgd *s = RNG_EGD(b);
    if (s->chr_name == NULL) {
        error_set(errp, QERR_INVALID_PARAMETER_VALUE,
                  "chardev", "a valid character device");
    s->chr = qemu_chr_find(s->chr_name);
    if (s->chr == NULL) {
        error_set(errp, QERR_DEVICE_NOT_FOUND, s->chr_name);
    /* FIXME we should resubmit pending requests when the CDS reconnects. */
    qemu_chr_add_handlers(s->chr, rng_egd_chr_can_read, rng_egd_chr_read,
                          NULL, s);


static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,

                              int64_t *ppos, int64_t pos_limit)

{

    MpegTSContext *ts = s->priv_data;

    int64_t pos, timestamp;

    uint8_t buf[TS_PACKET_SIZE];

    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;

    pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;

        while(pos < pos_limit) {

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

            if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)

                return AV_NOPTS_VALUE;

            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&

                parse_pcr(&timestamp, &pcr_l, buf) == 0) {

                *ppos = pos;

                return timestamp;

            }

            pos += ts->raw_packet_size;

        }

    return AV_NOPTS_VALUE;

}


static enum AVPixelFormat get_pixel_format(H264Context *h)

{

#define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \

                     CONFIG_H264_D3D11VA_HWACCEL + \

                     CONFIG_H264_VAAPI_HWACCEL + \

                     (CONFIG_H264_VDA_HWACCEL * 2) + \

                     CONFIG_H264_VDPAU_HWACCEL)

    enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;

    const enum AVPixelFormat *choices = pix_fmts;

    switch (h->sps.bit_depth_luma) {

    case 9:

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB) {

                *fmt++ = AV_PIX_FMT_GBRP9;

            } else

                *fmt++ = AV_PIX_FMT_YUV444P9;

        } else if (CHROMA422(h))

            *fmt++ = AV_PIX_FMT_YUV422P9;

        else

            *fmt++ = AV_PIX_FMT_YUV420P9;

        break;

    case 10:

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB) {

                *fmt++ = AV_PIX_FMT_GBRP10;

            } else

                *fmt++ = AV_PIX_FMT_YUV444P10;

        } else if (CHROMA422(h))

            *fmt++ = AV_PIX_FMT_YUV422P10;

        else

            *fmt++ = AV_PIX_FMT_YUV420P10;

        break;

    case 8:

#if CONFIG_H264_VDPAU_HWACCEL

        *fmt++ = AV_PIX_FMT_VDPAU;

#endif

        if (CHROMA444(h)) {

            if (h->avctx->colorspace == AVCOL_SPC_RGB)

                *fmt++ = AV_PIX_FMT_GBRP;

            else if (h->avctx->color_range == AVCOL_RANGE_JPEG)

                *fmt++ = AV_PIX_FMT_YUVJ444P;

            else

                *fmt++ = AV_PIX_FMT_YUV444P;

        } else if (CHROMA422(h)) {

            if (h->avctx->color_range == AVCOL_RANGE_JPEG)

                *fmt++ = AV_PIX_FMT_YUVJ422P;

            else

                *fmt++ = AV_PIX_FMT_YUV422P;

        } else {

#if CONFIG_H264_DXVA2_HWACCEL

            *fmt++ = AV_PIX_FMT_DXVA2_VLD;

#endif

#if CONFIG_H264_D3D11VA_HWACCEL

            *fmt++ = AV_PIX_FMT_D3D11VA_VLD;

#endif

#if CONFIG_H264_VAAPI_HWACCEL

            *fmt++ = AV_PIX_FMT_VAAPI;

#endif

#if CONFIG_H264_VDA_HWACCEL

            *fmt++ = AV_PIX_FMT_VDA_VLD;

            *fmt++ = AV_PIX_FMT_VDA;

#endif

            if (h->avctx->codec->pix_fmts)

                choices = h->avctx->codec->pix_fmts;

            else if (h->avctx->color_range == AVCOL_RANGE_JPEG)

                *fmt++ = AV_PIX_FMT_YUVJ420P;

            else

                *fmt++ = AV_PIX_FMT_YUV420P;

        }

        break;

    default:

        av_log(h->avctx, AV_LOG_ERROR,

               "Unsupported bit depth %d\n", h->sps.bit_depth_luma);

        return AVERROR_INVALIDDATA;

    }

    *fmt = AV_PIX_FMT_NONE;

    return ff_get_format(h->avctx, choices);

}


static void mv88w8618_eth_init(NICInfo *nd, uint32_t base, qemu_irq irq)

{

    mv88w8618_eth_state *s;

    int iomemtype;

    qemu_check_nic_model(nd, "mv88w8618");

    s = qemu_mallocz(sizeof(mv88w8618_eth_state));

    s->irq = irq;

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

                                 eth_receive, eth_can_receive, s);

    iomemtype = cpu_register_io_memory(0, mv88w8618_eth_readfn,

                                       mv88w8618_eth_writefn, s);

    cpu_register_physical_memory(base, MP_ETH_SIZE, iomemtype);

}


static int vnc_update_client_sync(VncState *vs, int has_dirty)

{

    int ret = vnc_update_client(vs, has_dirty);

    vnc_jobs_join(vs);

    return ret;

}


static struct omap_tipb_bridge_s *omap_tipb_bridge_init(

    MemoryRegion *memory, hwaddr base,

    qemu_irq abort_irq, omap_clk clk)

{

    struct omap_tipb_bridge_s *s = (struct omap_tipb_bridge_s *)

            g_malloc0(sizeof(struct omap_tipb_bridge_s));

    s->abort = abort_irq;

    omap_tipb_bridge_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_tipb_bridge_ops, s,

                          "omap-tipb-bridge", 0x100);

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

    return s;

}


static void seqvideo_decode(SeqVideoContext *seq, const unsigned char *data, int data_size)

{

    GetBitContext gb;

    int flags, i, j, x, y, op;

    unsigned char c[3];

    unsigned char *dst;

    uint32_t *palette;

    flags = *data++;

    if (flags & 1) {

        palette = (uint32_t *)seq->frame.data[1];

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

            for (j = 0; j < 3; j++, data++)

                c[j] = (*data << 2) | (*data >> 4);

            palette[i] = AV_RB24(c);

        }

        seq->frame.palette_has_changed = 1;

    }

    if (flags & 2) {

        init_get_bits(&gb, data, 128 * 8); data += 128;

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

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

                dst = &seq->frame.data[0][y * seq->frame.linesize[0] + x];

                op = get_bits(&gb, 2);

                switch (op) {

                case 1:

                    data = seq_decode_op1(seq, data, dst);

                    break;

                case 2:

                    data = seq_decode_op2(seq, data, dst);

                    break;

                case 3:

                    data = seq_decode_op3(seq, data, dst);

                    break;

                }

            }

    }

}


static int get_video_buffer(AVFrame *frame, int align)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);

    int ret, i;

    if (!desc)

        return AVERROR(EINVAL);

    if ((ret = av_image_check_size(frame->width, frame->height, 0, NULL)) < 0)

        return ret;

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

        ret = av_image_fill_linesizes(frame->linesize, frame->format,

                                      frame->width);

        if (ret < 0)

            return ret;

        for (i = 0; i < 4 && frame->linesize[i]; i++)

            frame->linesize[i] = FFALIGN(frame->linesize[i], align);

    }

    for (i = 0; i < 4 && frame->linesize[i]; i++) {

        int h = frame->height;

        if (i == 1 || i == 2)

            h = -((-h) >> desc->log2_chroma_h);

        frame->buf[i] = av_buffer_alloc(frame->linesize[i] * h);

        if (!frame->buf[i])

            goto fail;

        frame->data[i] = frame->buf[i]->data;

    }

    if (desc->flags & PIX_FMT_PAL || desc->flags & PIX_FMT_PSEUDOPAL) {

        av_buffer_unref(&frame->buf[1]);

        frame->buf[1] = av_buffer_alloc(1024);

        if (!frame->buf[1])

            goto fail;

        frame->data[1] = frame->buf[1]->data;

    }

    frame->extended_data = frame->data;

    return 0;

fail:

    av_frame_unref(frame);

    return AVERROR(ENOMEM);

}


static int build_table(VLC *vlc, int table_nb_bits, int nb_codes,

                       VLCcode *codes, int flags)

{

    int table_size, table_index, index, code_prefix, symbol, subtable_bits;

    int i, j, k, n, nb, inc;

    uint32_t code;

    VLC_TYPE (*table)[2];

    table_size = 1 << table_nb_bits;

    if (table_nb_bits > 30)

       return -1;

    table_index = alloc_table(vlc, table_size, flags & INIT_VLC_USE_NEW_STATIC);

    av_dlog(NULL, "new table index=%d size=%d\n", table_index, table_size);

    if (table_index < 0)

        return table_index;

    table = &vlc->table[table_index];

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

        table[i][1] = 0; //bits

        table[i][0] = -1; //codes

    }

    /* first pass: map codes and compute auxiliary table sizes */

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

        n      = codes[i].bits;

        code   = codes[i].code;

        symbol = codes[i].symbol;

        av_dlog(NULL, "i=%d n=%d code=0x%x\n", i, n, code);

        if (n <= table_nb_bits) {

            /* no need to add another table */

            j = code >> (32 - table_nb_bits);

            nb = 1 << (table_nb_bits - n);

            inc = 1;

            if (flags & INIT_VLC_LE) {

                j = bitswap_32(code);

                inc = 1 << n;

            }

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

                av_dlog(NULL, "%4x: code=%d n=%d\n", j, i, n);

                if (table[j][1] /*bits*/ != 0) {

                    av_log(NULL, AV_LOG_ERROR, "incorrect codes\n");

                    return AVERROR_INVALIDDATA;

                }

                table[j][1] = n; //bits

                table[j][0] = symbol;

                j += inc;

            }

        } else {

            /* fill auxiliary table recursively */

            n -= table_nb_bits;

            code_prefix = code >> (32 - table_nb_bits);

            subtable_bits = n;

            codes[i].bits = n;

            codes[i].code = code << table_nb_bits;

            for (k = i+1; k < nb_codes; k++) {

                n = codes[k].bits - table_nb_bits;

                if (n <= 0)

                    break;

                code = codes[k].code;

                if (code >> (32 - table_nb_bits) != code_prefix)

                    break;

                codes[k].bits = n;

                codes[k].code = code << table_nb_bits;

                subtable_bits = FFMAX(subtable_bits, n);

            }

            subtable_bits = FFMIN(subtable_bits, table_nb_bits);

            j = (flags & INIT_VLC_LE) ? bitswap_32(code_prefix) >> (32 - table_nb_bits) : code_prefix;

            table[j][1] = -subtable_bits;

            av_dlog(NULL, "%4x: n=%d (subtable)\n",

                    j, codes[i].bits + table_nb_bits);

            index = build_table(vlc, subtable_bits, k-i, codes+i, flags);

            if (index < 0)

                return index;

            /* note: realloc has been done, so reload tables */

            table = &vlc->table[table_index];

            table[j][0] = index; //code

            av_assert0(table[j][0] == index);

            i = k-1;

        }

    }

    return table_index;

}


static void h264_h_loop_filter_luma_intra_c(uint8_t *pix, int stride, int alpha, int beta)

{

    h264_loop_filter_luma_intra_c(pix, 1, stride, alpha, beta);

}


static inline void do_imdct(AC3DecodeContext *s, int channels)

{

    int ch;

    for (ch=1; ch<=channels; ch++) {

        if (s->block_switch[ch]) {

            int i;

            float *x = s->tmp_output+128;

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

                x[i] = s->transform_coeffs[ch][2*i];

            ff_imdct_half(&s->imdct_256, s->tmp_output, x);

            s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, s->add_bias, 128);

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

                x[i] = s->transform_coeffs[ch][2*i+1];

            ff_imdct_half(&s->imdct_256, s->delay[ch-1], x);

        } else {

            ff_imdct_half(&s->imdct_512, s->tmp_output, s->transform_coeffs[ch]);

            s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, s->add_bias, 128);

            memcpy(s->delay[ch-1], s->tmp_output+128, 128*sizeof(float));

        }

    }

}


static void parse_header_digest(struct iscsi_context *iscsi, const char *target)

{

    QemuOptsList *list;

    QemuOpts *opts;

    const char *digest = NULL;

    list = qemu_find_opts("iscsi");

    if (!list) {

        return;

    }

    opts = qemu_opts_find(list, target);

    if (opts == NULL) {

        opts = QTAILQ_FIRST(&list->head);

        if (!opts) {

            return;

        }

    }

    digest = qemu_opt_get(opts, "header-digest");

    if (!digest) {

        return;

    }

    if (!strcmp(digest, "CRC32C")) {

        iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C);

    } else if (!strcmp(digest, "NONE")) {

        iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE);

    } else if (!strcmp(digest, "CRC32C-NONE")) {

        iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_CRC32C_NONE);

    } else if (!strcmp(digest, "NONE-CRC32C")) {

        iscsi_set_header_digest(iscsi, ISCSI_HEADER_DIGEST_NONE_CRC32C);

    } else {

        error_report("Invalid header-digest setting : %s", digest);

    }

}


void visit_type_str(Visitor *v, char **obj, const char *name, Error **errp)

{

    if (!error_is_set(errp)) {

        v->type_str(v, obj, name, errp);

    }

}


static int http_send_data(HTTPContext *c)

{

    int len, ret;

    while (c->buffer_ptr >= c->buffer_end) {

        ret = http_prepare_data(c);

        if (ret < 0)

            return -1;

        else if (ret == 0) {

            break;

        } else {

            /* state change requested */

            return 0;

        }

    }

    if (c->buffer_end > c->buffer_ptr) {

        len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);

        if (len < 0) {

            if (errno != EAGAIN && errno != EINTR) {

                /* error : close connection */

                return -1;

            }

        } else {

            c->buffer_ptr += len;

            c->data_count += len;

        }

    }

    return 0;

}


static void m68060_cpu_initfn(Object *obj)

{

    M68kCPU *cpu = M68K_CPU(obj);

    CPUM68KState *env = &cpu->env;

    m68k_set_feature(env, M68K_FEATURE_M68000);

    m68k_set_feature(env, M68K_FEATURE_USP);

    m68k_set_feature(env, M68K_FEATURE_WORD_INDEX);

    m68k_set_feature(env, M68K_FEATURE_BRAL);

    m68k_set_feature(env, M68K_FEATURE_BCCL);

    m68k_set_feature(env, M68K_FEATURE_BITFIELD);

    m68k_set_feature(env, M68K_FEATURE_EXT_FULL);

    m68k_set_feature(env, M68K_FEATURE_SCALED_INDEX);

    m68k_set_feature(env, M68K_FEATURE_LONG_MULDIV);

    m68k_set_feature(env, M68K_FEATURE_FPU);

    m68k_set_feature(env, M68K_FEATURE_CAS);

    m68k_set_feature(env, M68K_FEATURE_BKPT);

    m68k_set_feature(env, M68K_FEATURE_RTD);

}


void mips_r4k_init (ram_addr_t ram_size, int vga_ram_size,

                    const char *boot_device,

                    const char *kernel_filename, const char *kernel_cmdline,

                    const char *initrd_filename, const char *cpu_model)

{

    char buf[1024];

    unsigned long bios_offset;

    int bios_size;

    CPUState *env;

    RTCState *rtc_state;

    int i;

    qemu_irq *i8259;

    int index;

    BlockDriverState *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_MIPS64

        cpu_model = "R4000";

#else

        cpu_model = "24Kf";

#endif

    env = cpu_init(cpu_model);

    if (!env) {

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

    qemu_register_reset(main_cpu_reset, env);

    /* allocate RAM */

    cpu_register_physical_memory(0, ram_size, IO_MEM_RAM);

    if (!mips_qemu_iomemtype) {

        mips_qemu_iomemtype = cpu_register_io_memory(0, mips_qemu_read,

                                                     mips_qemu_write, NULL);

    cpu_register_physical_memory(0x1fbf0000, 0x10000, mips_qemu_iomemtype);

    /* Try to load a BIOS image. If this fails, we continue regardless,

       but initialize the hardware ourselves. When a kernel gets

       preloaded we also initialize the hardware, since the BIOS wasn't

       run. */

    bios_offset = ram_size + vga_ram_size;

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    snprintf(buf, sizeof(buf), "%s/%s", bios_dir, bios_name);

    bios_size = load_image(buf, phys_ram_base + bios_offset);

    if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) {

	cpu_register_physical_memory(0x1fc00000,

				     BIOS_SIZE, bios_offset | IO_MEM_ROM);

    } else if ((index = drive_get_index(IF_PFLASH, 0, 0)) > -1) {

        uint32_t mips_rom = 0x00400000;

        cpu_register_physical_memory(0x1fc00000, mips_rom,

	                     qemu_ram_alloc(mips_rom) | IO_MEM_ROM);

        if (!pflash_cfi01_register(0x1fc00000, qemu_ram_alloc(mips_rom),

            drives_table[index].bdrv, sector_len, mips_rom / sector_len,

            4, 0, 0, 0, 0)) {

            fprintf(stderr, "qemu: Error registering flash memory.\n");

    else {

	/* not fatal */

        fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n",

		buf);

    if (kernel_filename) {

        loaderparams.ram_size = ram_size;

        loaderparams.kernel_filename = kernel_filename;

        loaderparams.kernel_cmdline = kernel_cmdline;

        loaderparams.initrd_filename = initrd_filename;

        load_kernel (env);

    /* Init CPU internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /* The PIC is attached to the MIPS CPU INT0 pin */

    i8259 = i8259_init(env->irq[2]);

    rtc_state = rtc_init(0x70, i8259[8]);

    /* Register 64 KB of ISA IO space at 0x14000000 */

    isa_mmio_init(0x14000000, 0x00010000);

    isa_mem_base = 0x10000000;

    pit = pit_init(0x40, i8259[0]);

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

        if (serial_hds[i]) {

            serial_init(serial_io[i], i8259[serial_irq[i]], 115200,

                        serial_hds[i]);

    isa_vga_init(phys_ram_base + ram_size, ram_size,

                 vga_ram_size);

    if (nd_table[0].vlan)

        isa_ne2000_init(0x300, i8259[9], &nd_table[0]);

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

        fprintf(stderr, "qemu: too many IDE bus\n");

    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {

        index = drive_get_index(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

        if (index != -1)

            hd[i] = drives_table[index].bdrv;

        else

            hd[i] = NULL;

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

        isa_ide_init(ide_iobase[i], ide_iobase2[i], i8259[ide_irq[i]],

                     hd[MAX_IDE_DEVS * i],

		     hd[MAX_IDE_DEVS * i + 1]);

    i8042_init(i8259[1], i8259[12], 0x60);


static void windowing_and_mdct_ltp(AACContext *ac, float *out,

                                   float *in, IndividualChannelStream *ics)

{

    const float *lwindow      = ics->use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;

    const float *swindow      = ics->use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;

    const float *lwindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;

    const float *swindow_prev = ics->use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;

    if (ics->window_sequence[0] != LONG_STOP_SEQUENCE) {

        ac->dsp.vector_fmul(in, in, lwindow_prev, 1024);

    } else {

        memset(in, 0, 448 * sizeof(float));

        ac->dsp.vector_fmul(in + 448, in + 448, swindow_prev, 128);

        memcpy(in + 576, in + 576, 448 * sizeof(float));

    }

    if (ics->window_sequence[0] != LONG_START_SEQUENCE) {

        ac->dsp.vector_fmul_reverse(in + 1024, in + 1024, lwindow, 1024);

    } else {

        memcpy(in + 1024, in + 1024, 448 * sizeof(float));

        ac->dsp.vector_fmul_reverse(in + 1024 + 448, in + 1024 + 448, swindow, 128);

        memset(in + 1024 + 576, 0, 448 * sizeof(float));

    }

    ac->mdct_ltp.mdct_calc(&ac->mdct_ltp, out, in);

}


static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    int ret;

    st = avformat_new_stream(c->fc, NULL);

    if (!st) return AVERROR(ENOMEM);

    st->id = c->fc->nb_streams;

    sc = av_mallocz(sizeof(MOVStreamContext));

    if (!sc) return AVERROR(ENOMEM);

    st->priv_data = sc;

    st->codec->codec_type = AVMEDIA_TYPE_DATA;

    sc->ffindex = st->index;

    c->trak_index = st->index;

    if ((ret = mov_read_default(c, pb, atom)) < 0)

        return ret;

    c->trak_index = -1;

    /* sanity checks */

    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||

                            (!sc->sample_size && !sc->sample_count))) {

        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",

               st->index);

        return 0;

    }

    fix_timescale(c, sc);

    avpriv_set_pts_info(st, 64, 1, sc->time_scale);

    mov_build_index(c, st);

    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {

        MOVDref *dref = &sc->drefs[sc->dref_id - 1];

        if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,

                          &c->fc->interrupt_callback) < 0)

            av_log(c->fc, AV_LOG_ERROR,

                   "stream %d, error opening alias: path='%s', dir='%s', "

                   "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",

                   st->index, dref->path, dref->dir, dref->filename,

                   dref->volume, dref->nlvl_from, dref->nlvl_to);

    } else {

        sc->pb = c->fc->pb;

        sc->pb_is_copied = 1;

    }

    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

        if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&

            sc->height && sc->width &&

            (st->codec->width != sc->width || st->codec->height != sc->height)) {

            st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /

                                             ((double)st->codec->width * sc->height), INT_MAX);

        }

#if FF_API_R_FRAME_RATE

        if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))

            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,

                      sc->time_scale, sc->stts_data[0].duration, INT_MAX);

#endif

    }

    // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.

    if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&

        TAG_IS_AVCI(st->codec->codec_tag)) {

        ret = ff_generate_avci_extradata(st);

        if (ret < 0)

            return ret;

    }

    switch (st->codec->codec_id) {

#if CONFIG_H261_DECODER

    case AV_CODEC_ID_H261:

#endif

#if CONFIG_H263_DECODER

    case AV_CODEC_ID_H263:

#endif

#if CONFIG_MPEG4_DECODER

    case AV_CODEC_ID_MPEG4:

#endif

        st->codec->width = 0; /* let decoder init width/height */

        st->codec->height= 0;

        break;

    }

    // If the duration of the mp3 packets is not constant, then they could need a parser

    if (st->codec->codec_id == AV_CODEC_ID_MP3

        && sc->stts_count > 3

        && sc->stts_count*10 > st->nb_frames

        && sc->time_scale == st->codec->sample_rate) {

            st->need_parsing = AVSTREAM_PARSE_FULL;

    }

    /* Do not need those anymore. */

    av_freep(&sc->chunk_offsets);

    av_freep(&sc->stsc_data);

    av_freep(&sc->sample_sizes);

    av_freep(&sc->keyframes);

    av_freep(&sc->stts_data);

    av_freep(&sc->stps_data);

    av_freep(&sc->elst_data);

    av_freep(&sc->rap_group);

    return 0;

}


static int mxg_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    int ret;

    unsigned int size;

    uint8_t *startmarker_ptr, *end, *search_end, marker;

    MXGContext *mxg = s->priv_data;

    while (!avio_feof(s->pb) && !s->pb->error){

        if (mxg->cache_size <= OVERREAD_SIZE) {

            /* update internal buffer */

            ret = mxg_update_cache(s, DEFAULT_PACKET_SIZE + OVERREAD_SIZE);

            if (ret < 0)

                return ret;

        }

        end = mxg->buffer_ptr + mxg->cache_size;

        /* find start marker - 0xff */

        if (mxg->cache_size > OVERREAD_SIZE) {

            search_end = end - OVERREAD_SIZE;

            startmarker_ptr = mxg_find_startmarker(mxg->buffer_ptr, search_end);

        } else {

            search_end = end;

            startmarker_ptr = mxg_find_startmarker(mxg->buffer_ptr, search_end);

            if (startmarker_ptr >= search_end - 1 ||

                *(startmarker_ptr + 1) != EOI) break;

        }

        if (startmarker_ptr != search_end) { /* start marker found */

            marker = *(startmarker_ptr + 1);

            mxg->buffer_ptr = startmarker_ptr + 2;

            mxg->cache_size = end - mxg->buffer_ptr;

            if (marker == SOI) {

                mxg->soi_ptr = startmarker_ptr;

            } else if (marker == EOI) {

                if (!mxg->soi_ptr) {

                    av_log(s, AV_LOG_WARNING, "Found EOI before SOI, skipping\n");

                    continue;

                }

                pkt->pts = pkt->dts = mxg->dts;

                pkt->stream_index = 0;

#if FF_API_DESTRUCT_PACKET

FF_DISABLE_DEPRECATION_WARNINGS

                pkt->destruct = NULL;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

                pkt->buf  = NULL;

                pkt->size = mxg->buffer_ptr - mxg->soi_ptr;

                pkt->data = mxg->soi_ptr;

                if (mxg->soi_ptr - mxg->buffer > mxg->cache_size) {

                    if (mxg->cache_size > 0) {

                        memcpy(mxg->buffer, mxg->buffer_ptr, mxg->cache_size);

                    }

                    mxg->buffer_ptr = mxg->buffer;

                }

                mxg->soi_ptr = 0;

                return pkt->size;

            } else if ( (SOF0 <= marker && marker <= SOF15) ||

                        (SOS  <= marker && marker <= COM) ) {

                /* all other markers that start marker segment also contain

                   length value (see specification for JPEG Annex B.1) */

                size = AV_RB16(mxg->buffer_ptr);

                if (size < 2)

                    return AVERROR(EINVAL);

                if (mxg->cache_size < size) {

                    ret = mxg_update_cache(s, size);

                    if (ret < 0)

                        return ret;

                    startmarker_ptr = mxg->buffer_ptr - 2;

                    mxg->cache_size = 0;

                } else {

                    mxg->cache_size -= size;

                }

                mxg->buffer_ptr += size;

                if (marker == APP13 && size >= 16) { /* audio data */

                    /* time (GMT) of first sample in usec since 1970, little-endian */

                    pkt->pts = pkt->dts = AV_RL64(startmarker_ptr + 8);

                    pkt->stream_index = 1;

#if FF_API_DESTRUCT_PACKET

FF_DISABLE_DEPRECATION_WARNINGS

                    pkt->destruct = NULL;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

                    pkt->buf  = NULL;

                    pkt->size = size - 14;

                    pkt->data = startmarker_ptr + 16;

                    if (startmarker_ptr - mxg->buffer > mxg->cache_size) {

                        if (mxg->cache_size > 0) {

                            memcpy(mxg->buffer, mxg->buffer_ptr, mxg->cache_size);

                        }

                        mxg->buffer_ptr = mxg->buffer;

                    }

                    return pkt->size;

                } else if (marker == COM && size >= 18 &&

                           !strncmp(startmarker_ptr + 4, "MXF", 3)) {

                    /* time (GMT) of video frame in usec since 1970, little-endian */

                    mxg->dts = AV_RL64(startmarker_ptr + 12);

                }

            }

        } else {

            /* start marker not found */

            mxg->buffer_ptr = search_end;

            mxg->cache_size = OVERREAD_SIZE;

        }

    }

    return AVERROR_EOF;

}


static uint32_t pci_unin_config_readl (void *opaque,

                                       target_phys_addr_t addr)

{

    UNINState *s = opaque;

    return s->config_reg;

}


static int amf_parse_object(AVFormatContext *s, AVStream *astream,

                            AVStream *vstream, const char *key,

                            int64_t max_pos, int depth)

{

    AVCodecContext *acodec, *vcodec;

    FLVContext *flv = s->priv_data;

    AVIOContext *ioc;

    AMFDataType amf_type;

    char str_val[256];

    double num_val;

    num_val  = 0;

    ioc      = s->pb;

    amf_type = avio_r8(ioc);

    switch (amf_type) {

    case AMF_DATA_TYPE_NUMBER:

        num_val = av_int2double(avio_rb64(ioc));

        break;

    case AMF_DATA_TYPE_BOOL:

        num_val = avio_r8(ioc);

        break;

    case AMF_DATA_TYPE_STRING:

        if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0)

            return -1;

        break;

    case AMF_DATA_TYPE_OBJECT:

        if ((vstream || astream) && key &&

            ioc->seekable &&

            !strcmp(KEYFRAMES_TAG, key) && depth == 1)

            if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,

                                      max_pos) < 0)

                av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");

        while (avio_tell(ioc) < max_pos - 2 &&

               amf_get_string(ioc, str_val, sizeof(str_val)) > 0)

            if (amf_parse_object(s, astream, vstream, str_val, max_pos,

                                 depth + 1) < 0)

                return -1;     // if we couldn't skip, bomb out.

        if (avio_r8(ioc) != AMF_END_OF_OBJECT)

            return -1;

        break;

    case AMF_DATA_TYPE_NULL:

    case AMF_DATA_TYPE_UNDEFINED:

    case AMF_DATA_TYPE_UNSUPPORTED:

        break;     // these take up no additional space

    case AMF_DATA_TYPE_MIXEDARRAY:

        avio_skip(ioc, 4);     // skip 32-bit max array index

        while (avio_tell(ioc) < max_pos - 2 &&

               amf_get_string(ioc, str_val, sizeof(str_val)) > 0)

            // this is the only case in which we would want a nested

            // parse to not skip over the object

            if (amf_parse_object(s, astream, vstream, str_val, max_pos,

                                 depth + 1) < 0)

                return -1;

        if (avio_r8(ioc) != AMF_END_OF_OBJECT)

            return -1;

        break;

    case AMF_DATA_TYPE_ARRAY:

    {

        unsigned int arraylen, i;

        arraylen = avio_rb32(ioc);

        for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)

            if (amf_parse_object(s, NULL, NULL, NULL, max_pos,

                                 depth + 1) < 0)

                return -1;      // if we couldn't skip, bomb out.

    }

    break;

    case AMF_DATA_TYPE_DATE:

        avio_skip(ioc, 8 + 2);  // timestamp (double) and UTC offset (int16)

        break;

    default:                    // unsupported type, we couldn't skip

        return -1;

    }

    if (key) {

        // stream info doesn't live any deeper than the first object

        if (depth == 1) {

            acodec = astream ? astream->codec : NULL;

            vcodec = vstream ? vstream->codec : NULL;

            if (amf_type == AMF_DATA_TYPE_NUMBER ||

                amf_type == AMF_DATA_TYPE_BOOL) {

                if (!strcmp(key, "duration"))

                    s->duration = num_val * AV_TIME_BASE;

                else if (!strcmp(key, "videodatarate") && vcodec &&

                         0 <= (int)(num_val * 1024.0))

                    vcodec->bit_rate = num_val * 1024.0;

                else if (!strcmp(key, "audiodatarate") && acodec &&

                         0 <= (int)(num_val * 1024.0))

                    acodec->bit_rate = num_val * 1024.0;

                else if (!strcmp(key, "datastream")) {

                    AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);

                    if (!st)

                        return AVERROR(ENOMEM);

                    st->codec->codec_id = AV_CODEC_ID_TEXT;

                } else if (flv->trust_metadata) {

                    if (!strcmp(key, "videocodecid") && vcodec) {

                        flv_set_video_codec(s, vstream, num_val, 0);

                    } else if (!strcmp(key, "audiocodecid") && acodec) {

                        int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;

                        flv_set_audio_codec(s, astream, acodec, id);

                    } else if (!strcmp(key, "audiosamplerate") && acodec) {

                        acodec->sample_rate = num_val;

                    } else if (!strcmp(key, "audiosamplesize") && acodec) {

                        acodec->bits_per_coded_sample = num_val;

                    } else if (!strcmp(key, "stereo") && acodec) {

                        acodec->channels       = num_val + 1;

                        acodec->channel_layout = acodec->channels == 2 ?

                                                 AV_CH_LAYOUT_STEREO :

                                                 AV_CH_LAYOUT_MONO;

                    } else if (!strcmp(key, "width") && vcodec) {

                        vcodec->width = num_val;

                    } else if (!strcmp(key, "height") && vcodec) {

                        vcodec->height = num_val;

                    }

                }

            }

        }

        if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&

           ((!acodec && !strcmp(key, "audiocodecid")) ||

            (!vcodec && !strcmp(key, "videocodecid"))))

                s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object

        if (!strcmp(key, "duration")        ||

            !strcmp(key, "filesize")        ||

            !strcmp(key, "width")           ||

            !strcmp(key, "height")          ||

            !strcmp(key, "videodatarate")   ||

            !strcmp(key, "framerate")       ||

            !strcmp(key, "videocodecid")    ||

            !strcmp(key, "audiodatarate")   ||

            !strcmp(key, "audiosamplerate") ||

            !strcmp(key, "audiosamplesize") ||

            !strcmp(key, "stereo")          ||

            !strcmp(key, "audiocodecid")    ||

            !strcmp(key, "datastream"))

            return 0;

        s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;

        if (amf_type == AMF_DATA_TYPE_BOOL) {

            av_strlcpy(str_val, num_val > 0 ? "true" : "false",

                       sizeof(str_val));

            av_dict_set(&s->metadata, key, str_val, 0);

        } else if (amf_type == AMF_DATA_TYPE_NUMBER) {

            snprintf(str_val, sizeof(str_val), "%.f", num_val);

            av_dict_set(&s->metadata, key, str_val, 0);

        } else if (amf_type == AMF_DATA_TYPE_STRING)

            av_dict_set(&s->metadata, key, str_val, 0);

    }

    return 0;

}


static TCGv_i64 gen_subq_msw(TCGv_i64 a, TCGv b)

{

    TCGv_i64 tmp64 = tcg_temp_new_i64();

    tcg_gen_extu_i32_i64(tmp64, b);

    dead_tmp(b);

    tcg_gen_shli_i64(tmp64, tmp64, 32);

    tcg_gen_sub_i64(a, tmp64, a);

    tcg_temp_free_i64(tmp64);

    return a;

}


static void decode_component(DiracContext *s, int comp)

{

    AVCodecContext *avctx = s->avctx;

    SubBand *bands[3*MAX_DWT_LEVELS+1];

    enum dirac_subband orientation;

    int level, num_bands = 0;

    /* Unpack all subbands at all levels. */

    for (level = 0; level < s->wavelet_depth; level++) {

        for (orientation = !!level; orientation < 4; orientation++) {

            SubBand *b = &s->plane[comp].band[level][orientation];

            bands[num_bands++] = b;

            align_get_bits(&s->gb);

            /* [DIRAC_STD] 13.4.2 subband() */

            b->length = svq3_get_ue_golomb(&s->gb);

            if (b->length) {

                b->quant = svq3_get_ue_golomb(&s->gb);

                align_get_bits(&s->gb);

                b->coeff_data = s->gb.buffer + get_bits_count(&s->gb)/8;

                b->length = FFMIN(b->length, get_bits_left(&s->gb)/8);

                skip_bits_long(&s->gb, b->length*8);

            }

        }

        /* arithmetic coding has inter-level dependencies, so we can only execute one level at a time */

        if (s->is_arith)

            avctx->execute(avctx, decode_subband_arith, &s->plane[comp].band[level][!!level],

                           NULL, 4-!!level, sizeof(SubBand));

    }

    /* golomb coding has no inter-level dependencies, so we can execute all subbands in parallel */

    if (!s->is_arith)

        avctx->execute(avctx, decode_subband_golomb, bands, NULL, num_bands, sizeof(SubBand*));

}


static void ppc_heathrow_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    const char *boot_device = machine->boot_order;

    MemoryRegion *sysmem = get_system_memory();

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    char *filename;

    qemu_irq *pic, **heathrow_irqs;

    int linux_boot, i;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios = g_new(MemoryRegion, 1);

    MemoryRegion *isa = g_new(MemoryRegion, 1);

    uint32_t kernel_base, initrd_base, cmdline_base = 0;

    int32_t kernel_size, initrd_size;

    PCIBus *pci_bus;

    PCIDevice *macio;

    MACIOIDEState *macio_ide;

    DeviceState *dev;

    BusState *adb_bus;

    int bios_size;

    MemoryRegion *pic_mem;

    MemoryRegion *escc_mem, *escc_bar = g_new(MemoryRegion, 1);

    uint16_t ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    void *fw_cfg;

    uint64_t tbfreq;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

        cpu_model = "G3";

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

        cpu = cpu_ppc_init(cpu_model);

        if (cpu == NULL) {

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

            exit(1);

        }

        env = &cpu->env;

        /* Set time-base frequency to 16.6 Mhz */

        cpu_ppc_tb_init(env,  TBFREQ);

        qemu_register_reset(ppc_heathrow_reset, cpu);

    }

    /* allocate RAM */

    if (ram_size > (2047 << 20)) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d MB, maximum 2047 MB\n",

                ((unsigned int)ram_size / (1 << 20)));

        exit(1);

    }

    memory_region_allocate_system_memory(ram, NULL, "ppc_heathrow.ram",

                                         ram_size);

    memory_region_add_subregion(sysmem, 0, ram);

    /* allocate and load BIOS */

    memory_region_init_ram(bios, NULL, "ppc_heathrow.bios", BIOS_SIZE);

    vmstate_register_ram_global(bios);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    memory_region_set_readonly(bios, true);

    memory_region_add_subregion(sysmem, PROM_ADDR, bios);

    /* Load OpenBIOS (ELF) */

    if (filename) {

        bios_size = load_elf(filename, 0, NULL, NULL, NULL, NULL,

                             1, ELF_MACHINE, 0);

        g_free(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PowerPC bios '%s'\n", bios_name);

        exit(1);

    }

    if (linux_boot) {

        uint64_t lowaddr = 0;

        int bswap_needed;

#ifdef BSWAP_NEEDED

        bswap_needed = 1;

#else

        bswap_needed = 0;

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,

                               NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0);

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, kernel_base,

                                    ram_size - kernel_base, bswap_needed,

                                    TARGET_PAGE_SIZE);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              kernel_base,

                                              ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n",

                      kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                hw_error("qemu: could not load initial ram disk '%s'\n",

                         initrd_filename);

                exit(1);

            }

            cmdline_base = round_page(initrd_base + initrd_size);

        } else {

            initrd_base = 0;

            initrd_size = 0;

            cmdline_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        for (i = 0; boot_device[i] != '\0'; i++) {

            /* TOFIX: for now, the second IDE channel is not properly

             *        used by OHW. The Mac floppy disk are not emulated.

             *        For now, OHW cannot boot from the network.

             */

#if 0

            if (boot_device[i] >= 'a' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

#else

            if (boot_device[i] >= 'c' && boot_device[i] <= 'd') {

                ppc_boot_device = boot_device[i];

                break;

            }

#endif

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for G3 Beige machine\n");

            exit(1);

        }

    }

    /* Register 2 MB of ISA IO space */

    memory_region_init_alias(isa, NULL, "isa_mmio",

                             get_system_io(), 0, 0x00200000);

    memory_region_add_subregion(sysmem, 0xfe000000, isa);

    /* XXX: we register only 1 output pin for heathrow PIC */

    heathrow_irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));

    heathrow_irqs[0] =

        g_malloc0(smp_cpus * sizeof(qemu_irq) * 1);

    /* Connect the heathrow PIC outputs to the 6xx bus */

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

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

            heathrow_irqs[i] = heathrow_irqs[0] + (i * 1);

            heathrow_irqs[i][0] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            break;

        default:

            hw_error("Bus model not supported on OldWorld Mac machine\n");

        }

    }

    /* Timebase Frequency */

    if (kvm_enabled()) {

        tbfreq = kvmppc_get_tbfreq();

    } else {

        tbfreq = TBFREQ;

    }

    /* init basic PC hardware */

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        hw_error("Only 6xx bus is supported on heathrow machine\n");

    }

    pic = heathrow_pic_init(&pic_mem, 1, heathrow_irqs);

    pci_bus = pci_grackle_init(0xfec00000, pic,

                               get_system_memory(),

                               get_system_io());

    pci_vga_init(pci_bus);

    escc_mem = escc_init(0, pic[0x0f], pic[0x10], serial_hds[0],

                               serial_hds[1], ESCC_CLOCK, 4);

    memory_region_init_alias(escc_bar, NULL, "escc-bar",

                             escc_mem, 0, memory_region_size(escc_mem));

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

        pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL);

    ide_drive_get(hd, MAX_IDE_BUS);

    macio = pci_create(pci_bus, -1, TYPE_OLDWORLD_MACIO);

    dev = DEVICE(macio);

    qdev_connect_gpio_out(dev, 0, pic[0x12]); /* CUDA */

    qdev_connect_gpio_out(dev, 1, pic[0x0D]); /* IDE-0 */

    qdev_connect_gpio_out(dev, 2, pic[0x02]); /* IDE-0 DMA */

    qdev_connect_gpio_out(dev, 3, pic[0x0E]); /* IDE-1 */

    qdev_connect_gpio_out(dev, 4, pic[0x03]); /* IDE-1 DMA */

    macio_init(macio, pic_mem, escc_bar);

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[0]"));

    macio_ide_init_drives(macio_ide, hd);

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[1]"));

    macio_ide_init_drives(macio_ide, &hd[MAX_IDE_DEVS]);

    dev = DEVICE(object_resolve_path_component(OBJECT(macio), "cuda"));

    adb_bus = qdev_get_child_bus(dev, "adb.0");

    dev = qdev_create(adb_bus, TYPE_ADB_KEYBOARD);

    qdev_init_nofail(dev);

    dev = qdev_create(adb_bus, TYPE_ADB_MOUSE);

    qdev_init_nofail(dev);

    if (usb_enabled(false)) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

    }

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8)

        graphic_depth = 15;

    /* No PCI init: the BIOS will do it */

    fw_cfg = fw_cfg_init(0, 0, CFG_ADDR, CFG_ADDR + 2);

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

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

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

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, ARCH_HEATHROW);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, cmdline_base);

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE, kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0);

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, ppc_boot_device);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_IS_KVM, kvm_enabled());

    if (kvm_enabled()) {

#ifdef CONFIG_KVM

        uint8_t *hypercall;

        hypercall = g_malloc(16);

        kvmppc_get_hypercall(env, hypercall, 16);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16);

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid());

#endif

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, tbfreq);

    /* Mac OS X requires a "known good" clock-frequency value; pass it one. */

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, CLOCKFREQ);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_BUSFREQ, BUSFREQ);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)

{

    int i;

    int dc_y_table;

    int dc_c_table;

    int ac_y_table;

    int ac_c_table;

    int residual_eob_run = 0;

    VLC *y_tables[64];

    VLC *c_tables[64];

    s->dct_tokens[0][0] = s->dct_tokens_base;

    if (get_bits_left(gb) < 16)

    /* fetch the DC table indexes */

    dc_y_table = get_bits(gb, 4);

    dc_c_table = get_bits(gb, 4);

    /* unpack the Y plane DC coefficients */

    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,

                                   0, residual_eob_run);

    if (residual_eob_run < 0)

        return residual_eob_run;

    /* reverse prediction of the Y-plane DC coefficients */

    reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);

    /* unpack the C plane DC coefficients */

    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,

                                   1, residual_eob_run);

    if (residual_eob_run < 0)

        return residual_eob_run;

    residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,

                                   2, residual_eob_run);

    if (residual_eob_run < 0)

        return residual_eob_run;

    /* reverse prediction of the C-plane DC coefficients */

    if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {

        reverse_dc_prediction(s, s->fragment_start[1],

                              s->fragment_width[1], s->fragment_height[1]);

        reverse_dc_prediction(s, s->fragment_start[2],

                              s->fragment_width[1], s->fragment_height[1]);

    }

    /* fetch the AC table indexes */

    ac_y_table = get_bits(gb, 4);

    ac_c_table = get_bits(gb, 4);

    /* build tables of AC VLC tables */

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

        y_tables[i] = &s->ac_vlc_1[ac_y_table];

        c_tables[i] = &s->ac_vlc_1[ac_c_table];

    }

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

        y_tables[i] = &s->ac_vlc_2[ac_y_table];

        c_tables[i] = &s->ac_vlc_2[ac_c_table];

    }

    for (i = 15; i <= 27; i++) {

        y_tables[i] = &s->ac_vlc_3[ac_y_table];

        c_tables[i] = &s->ac_vlc_3[ac_c_table];

    }

    for (i = 28; i <= 63; i++) {

        y_tables[i] = &s->ac_vlc_4[ac_y_table];

        c_tables[i] = &s->ac_vlc_4[ac_c_table];

    }

    /* decode all AC coefficients */

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

        residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,

                                       0, residual_eob_run);

        if (residual_eob_run < 0)

            return residual_eob_run;

        residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,

                                       1, residual_eob_run);

        if (residual_eob_run < 0)

            return residual_eob_run;

        residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,

                                       2, residual_eob_run);

        if (residual_eob_run < 0)

            return residual_eob_run;

    }

    return 0;

}


static void free_device_list(AVOpenCLDeviceList *device_list)

{

    int i, j;

    if (!device_list)

        return;

    for (i = 0; i < device_list->platform_num; i++) {

        if (!device_list->platform_node[i])

            continue;

        for (j = 0; j < device_list->platform_node[i]->device_num; j++) {

            av_freep(&(device_list->platform_node[i]->device_node[j]->device_name));

            av_freep(&(device_list->platform_node[i]->device_node[j]));

        }

        av_freep(&device_list->platform_node[i]->device_node);

        av_freep(&(device_list->platform_node[i]->platform_name));

        av_freep(&device_list->platform_node[i]);

    }

    av_freep(&device_list->platform_node);

    device_list->platform_num = 0;

}


void qemu_cond_init(QemuCond *cond)

{

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

    cond->sema = CreateSemaphore(NULL, 0, LONG_MAX, NULL);

    if (!cond->sema) {

        error_exit(GetLastError(), __func__);

    }

    cond->continue_event = CreateEvent(NULL,    /* security */

                                       FALSE,   /* auto-reset */

                                       FALSE,   /* not signaled */

                                       NULL);   /* name */

    if (!cond->continue_event) {

        error_exit(GetLastError(), __func__);

    }

}


void helper_rfdi(CPUPPCState *env)

{

    do_rfi(env, env->spr[SPR_BOOKE_DSRR0], SPR_BOOKE_DSRR1,

           ~((target_ulong)0x3FFF0000), 0);

}


static void choose_sample_rate(AVStream *st, AVCodec *codec)

{

    if(codec && codec->supported_samplerates){

        const int *p= codec->supported_samplerates;

        int best;

        int best_dist=INT_MAX;

        for(; *p; p++){

            int dist= abs(st->codec->sample_rate - *p);

            if(dist < best_dist){

                best_dist= dist;

                best= *p;

            }

        }

        if(best_dist){

            av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);

        }

        st->codec->sample_rate= best;

    }

}


unsigned iov_copy(struct iovec *dst_iov, unsigned int dst_iov_cnt,

                 const struct iovec *iov, unsigned int iov_cnt,

                 size_t offset, size_t bytes)

{

    size_t len;

    unsigned int i, j;

    for (i = 0, j = 0; i < iov_cnt && j < dst_iov_cnt && bytes; i++) {

        if (offset >= iov[i].iov_len) {

            offset -= iov[i].iov_len;

            continue;

        }

        len = MIN(bytes, iov[i].iov_len - offset);

        dst_iov[j].iov_base = iov[i].iov_base + offset;

        dst_iov[j].iov_len = len;

        j++;

        bytes -= len;

        offset = 0;

    }

    assert(offset == 0);

    return j;

}


static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)

    FDCharDriver *s = chr->opaque;

    switch(cmd) {

    case CHR_IOCTL_SERIAL_SET_PARAMS:

            QEMUSerialSetParams *ssp = arg;

            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,

                            ssp->data_bits, ssp->stop_bits);

    case CHR_IOCTL_SERIAL_SET_BREAK:

            int enable = *(int *)arg;

            if (enable)

                tcsendbreak(s->fd_in, 1);

    default:

        return -ENOTSUP;

    return 0;


static int spapr_populate_drconf_memory(sPAPRMachineState *spapr, void *fdt)

{

    MachineState *machine = MACHINE(spapr);

    int ret, i, offset;

    uint64_t lmb_size = SPAPR_MEMORY_BLOCK_SIZE;

    uint32_t prop_lmb_size[] = {0, cpu_to_be32(lmb_size)};

    uint32_t nr_lmbs = (machine->maxram_size - machine->ram_size)/lmb_size;

    uint32_t *int_buf, *cur_index, buf_len;

    int nr_nodes = nb_numa_nodes ? nb_numa_nodes : 1;

    /* Allocate enough buffer size to fit in ibm,dynamic-memory */

    buf_len = nr_lmbs * SPAPR_DR_LMB_LIST_ENTRY_SIZE * sizeof(uint32_t) +

                sizeof(uint32_t);

    cur_index = int_buf = g_malloc0(buf_len);

    offset = fdt_add_subnode(fdt, 0, "ibm,dynamic-reconfiguration-memory");

    ret = fdt_setprop(fdt, offset, "ibm,lmb-size", prop_lmb_size,

                    sizeof(prop_lmb_size));

    if (ret < 0) {

        goto out;

    }

    ret = fdt_setprop_cell(fdt, offset, "ibm,memory-flags-mask", 0xff);

    if (ret < 0) {

        goto out;

    }

    ret = fdt_setprop_cell(fdt, offset, "ibm,memory-preservation-time", 0x0);

    if (ret < 0) {

        goto out;

    }

    /* ibm,dynamic-memory */

    int_buf[0] = cpu_to_be32(nr_lmbs);

    cur_index++;

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

        sPAPRDRConnector *drc;

        sPAPRDRConnectorClass *drck;

        uint64_t addr = i * lmb_size + spapr->hotplug_memory.base;;

        uint32_t *dynamic_memory = cur_index;

        drc = spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_LMB,

                                       addr/lmb_size);

        g_assert(drc);

        drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

        dynamic_memory[0] = cpu_to_be32(addr >> 32);

        dynamic_memory[1] = cpu_to_be32(addr & 0xffffffff);

        dynamic_memory[2] = cpu_to_be32(drck->get_index(drc));

        dynamic_memory[3] = cpu_to_be32(0); /* reserved */

        dynamic_memory[4] = cpu_to_be32(numa_get_node(addr, NULL));

        if (addr < machine->ram_size ||

                    memory_region_present(get_system_memory(), addr)) {

            dynamic_memory[5] = cpu_to_be32(SPAPR_LMB_FLAGS_ASSIGNED);

        } else {

            dynamic_memory[5] = cpu_to_be32(0);

        }

        cur_index += SPAPR_DR_LMB_LIST_ENTRY_SIZE;

    }

    ret = fdt_setprop(fdt, offset, "ibm,dynamic-memory", int_buf, buf_len);

    if (ret < 0) {

        goto out;

    }

    /* ibm,associativity-lookup-arrays */

    cur_index = int_buf;

    int_buf[0] = cpu_to_be32(nr_nodes);

    int_buf[1] = cpu_to_be32(4); /* Number of entries per associativity list */

    cur_index += 2;

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

        uint32_t associativity[] = {

            cpu_to_be32(0x0),

            cpu_to_be32(0x0),

            cpu_to_be32(0x0),

            cpu_to_be32(i)

        };

        memcpy(cur_index, associativity, sizeof(associativity));

        cur_index += 4;

    }

    ret = fdt_setprop(fdt, offset, "ibm,associativity-lookup-arrays", int_buf,

            (cur_index - int_buf) * sizeof(uint32_t));

out:

    g_free(int_buf);

    return ret;

}


static int http_server(struct sockaddr_in my_addr)

{

    int server_fd, tmp, ret;

    struct sockaddr_in from_addr;

    struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 1], *poll_entry;

    HTTPContext *c, **cp;

    long cur_time;

    server_fd = socket(AF_INET,SOCK_STREAM,0);

    if (server_fd < 0) {

        perror ("socket");

        return -1;

    }

    tmp = 1;

    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));

    if (bind (server_fd, (struct sockaddr *) &my_addr, sizeof (my_addr)) < 0) {

        perror ("bind");

        close(server_fd);

        return -1;

    }

    if (listen (server_fd, 5) < 0) {

        perror ("listen");

        close(server_fd);

        return -1;

    }

    http_log("ffserver started.\n");

    start_children(first_feed);

    fcntl(server_fd, F_SETFL, O_NONBLOCK);

    first_http_ctx = NULL;

    nb_connections = 0;

    first_http_ctx = NULL;

    for(;;) {

        poll_entry = poll_table;

        poll_entry->fd = server_fd;

        poll_entry->events = POLLIN;

        poll_entry++;

        /* wait for events on each HTTP handle */

        c = first_http_ctx;

        while (c != NULL) {

            int fd;

            fd = c->fd;

            switch(c->state) {

            case HTTPSTATE_WAIT_REQUEST:

                c->poll_entry = poll_entry;

                poll_entry->fd = fd;

                poll_entry->events = POLLIN;

                poll_entry++;

                break;

            case HTTPSTATE_SEND_HEADER:

            case HTTPSTATE_SEND_DATA_HEADER:

            case HTTPSTATE_SEND_DATA:

            case HTTPSTATE_SEND_DATA_TRAILER:

                c->poll_entry = poll_entry;

                poll_entry->fd = fd;

                poll_entry->events = POLLOUT;

                poll_entry++;

                break;

            case HTTPSTATE_RECEIVE_DATA:

                c->poll_entry = poll_entry;

                poll_entry->fd = fd;

                poll_entry->events = POLLIN;

                poll_entry++;

                break;

            case HTTPSTATE_WAIT_FEED:

                /* need to catch errors */

                c->poll_entry = poll_entry;

                poll_entry->fd = fd;

                poll_entry->events = POLLIN;/* Maybe this will work */

                poll_entry++;

                break;

            default:

                c->poll_entry = NULL;

                break;

            }

            c = c->next;

        }

        /* wait for an event on one connection. We poll at least every

           second to handle timeouts */

        do {

            ret = poll(poll_table, poll_entry - poll_table, 1000);

        } while (ret == -1);

        cur_time = gettime_ms();

        /* now handle the events */

        cp = &first_http_ctx;

        while ((*cp) != NULL) {

            c = *cp;

            if (handle_http (c, cur_time) < 0) {

                /* close and free the connection */

                log_connection(c);

                close(c->fd);

                if (c->fmt_in)

                    av_close_input_file(c->fmt_in);

                *cp = c->next;

                nb_bandwidth -= c->bandwidth;

                av_free(c->buffer);

                av_free(c->pbuffer);

                av_free(c);

                nb_connections--;

            } else {

                cp = &c->next;

            }

        }

        /* new connection request ? */

        poll_entry = poll_table;

        if (poll_entry->revents & POLLIN) {

            int fd, len;

            len = sizeof(from_addr);

            fd = accept(server_fd, (struct sockaddr *)&from_addr,

                        &len);

            if (fd >= 0) {

                fcntl(fd, F_SETFL, O_NONBLOCK);

                /* XXX: should output a warning page when coming

                   close to the connection limit */

                if (nb_connections >= nb_max_connections) {

                    c = NULL;

                } else {

                    /* add a new connection */

                    c = av_mallocz(sizeof(HTTPContext));

                    if (c) {

                        c->next = first_http_ctx;

                        first_http_ctx = c;

                        c->fd = fd;

                        c->poll_entry = NULL;

                        c->from_addr = from_addr;

                        c->state = HTTPSTATE_WAIT_REQUEST;

                        c->buffer = av_malloc(c->buffer_size = IOBUFFER_INIT_SIZE);

                        c->pbuffer = av_malloc(c->pbuffer_size = PBUFFER_INIT_SIZE);

                        if (!c->buffer || !c->pbuffer) {

                            av_free(c->buffer);

                            av_free(c->pbuffer);

                            av_freep(&c);

                        } else {

                            c->buffer_ptr = c->buffer;

                            c->buffer_end = c->buffer + c->buffer_size;

                            c->timeout = cur_time + REQUEST_TIMEOUT;

                            c->start_time = cur_time;

                            nb_connections++;

                        }

                    }

                }

                if (!c) {

                    close(fd);

                }

            }

        }

        poll_entry++;

    }

}


int kvm_arch_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint *bp)

{

    uint8_t t[sizeof(diag_501)];

    if (cpu_memory_rw_debug(cs, bp->pc, t, sizeof(diag_501), 0)) {

        return -EINVAL;

    } else if (memcmp(t, diag_501, sizeof(diag_501))) {

        return -EINVAL;

    } else if (cpu_memory_rw_debug(cs, bp->pc, (uint8_t *)&bp->saved_insn,

                                   sizeof(diag_501), 1)) {

        return -EINVAL;

    }

    return 0;

}


static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,

                                         unsigned long *bitmap)

{

    unsigned int i, j;

    unsigned long page_number, addr, addr1, c;

    unsigned int len = ((section->size / TARGET_PAGE_SIZE) + HOST_LONG_BITS - 1) / HOST_LONG_BITS;

    /*

     * bitmap-traveling is faster than memory-traveling (for addr...)

     * especially when most of the memory is not dirty.

     */

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

        if (bitmap[i] != 0) {

            c = leul_to_cpu(bitmap[i]);

            do {

                j = ffsl(c) - 1;

                c &= ~(1ul << j);

                page_number = i * HOST_LONG_BITS + j;

                addr1 = page_number * TARGET_PAGE_SIZE;

                addr = section->offset_within_region + addr1;

                memory_region_set_dirty(section->mr, addr);

            } while (c != 0);

        }

    }

    return 0;

}


static int ppc_hash64_pte_prot(PowerPCCPU *cpu,

                               ppc_slb_t *slb, ppc_hash_pte64_t pte)

{

    CPUPPCState *env = &cpu->env;

    unsigned pp, key;

    /* Some pp bit combinations have undefined behaviour, so default

     * to no access in those cases */

    int prot = 0;

    key = !!(msr_pr ? (slb->vsid & SLB_VSID_KP)

             : (slb->vsid & SLB_VSID_KS));

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

    if (key == 0) {

        switch (pp) {

        case 0x0:

        case 0x1:

        case 0x2:

            prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

            break;

        case 0x3:

        case 0x6:

            prot = PAGE_READ | PAGE_EXEC;

            break;

        }

    } else {

        switch (pp) {

        case 0x0:

        case 0x6:

            break;

        case 0x1:

        case 0x3:

            prot = PAGE_READ | PAGE_EXEC;

            break;

        case 0x2:

            prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

            break;

        }

    }

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

    if (!(pte.pte1 & HPTE64_R_N) || (pte.pte1 & HPTE64_R_G)

        || (slb->vsid & SLB_VSID_N)) {

        prot |= PAGE_EXEC;

    }

    return prot;

}


static int rd_frame(CinepakEncContext *s, AVFrame *frame, unsigned char *buf, int buf_size)

{

    int num_strips, strip, h, i, y, size, temp_size, best_size;

    AVPicture last_pict, pict, scratch_pict;

    int64_t best_score = 0, score, score_temp;

    //TODO: support encoding zero strips (meaning skip the whole frame)

    for(num_strips = MIN_STRIPS; num_strips <= MAX_STRIPS && num_strips <= s->h / MB_SIZE; num_strips++) {

        score = 0;

        size = 0;

        h = s->h / num_strips;

        //make h into next multiple of 4

        h += 4 - (h & 3);

        for(strip = 0; strip < num_strips; strip++) {

            y = strip*h;

            get_sub_picture(s, 0, y, (AVPicture*)frame,            &pict);

            get_sub_picture(s, 0, y, (AVPicture*)&s->last_frame,    &last_pict);

            get_sub_picture(s, 0, y, (AVPicture*)&s->scratch_frame, &scratch_pict);

            if((temp_size = rd_strip(s, y, FFMIN(h, s->h - y), frame->key_frame, &last_pict, &pict, &scratch_pict, s->frame_buf + CVID_HEADER_SIZE, &score_temp)) < 0)

                return temp_size;

            score += score_temp;

            size += temp_size;

        }

        if(best_score == 0 || score < best_score) {

            best_score = score;

            best_size = size + write_cvid_header(s, s->frame_buf, num_strips, size);

            av_log(s->avctx, AV_LOG_INFO, "best number of strips so far: %2i, %12li, %i B\n", num_strips, score, best_size);

            FFSWAP(AVFrame, s->best_frame, s->scratch_frame);

        }

    }

    memcpy(buf, s->frame_buf, best_size);

    return best_size;

}


void ff_hevc_set_qPy(HEVCContext *s, int xC, int yC,

                     int xBase, int yBase, int log2_cb_size)

{

    int qp_y = get_qPy_pred(s, xC, yC, xBase, yBase, log2_cb_size);

    if (s->HEVClc->tu.cu_qp_delta != 0) {

        int off = s->sps->qp_bd_offset;

        s->HEVClc->qp_y = ((qp_y + s->HEVClc->tu.cu_qp_delta + 52 + 2 * off) %

                          (52 + off)) - off;

    } else

        s->HEVClc->qp_y = qp_y;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->vmsd = &sdhci_vmstate;

    dc->props = sdhci_sysbus_properties;

    dc->realize = sdhci_sysbus_realize;

    dc->reset = sdhci_poweron_reset;

}


grlib_gptimer_writel(void *opaque, target_phys_addr_t addr, uint32_t value)

{

    GPTimerUnit        *unit = opaque;

    target_phys_addr_t  timer_addr;

    int                 id;

    addr &= 0xff;

    /* Unit registers */

    switch (addr) {

    case SCALER_OFFSET:

        value &= 0xFFFF; /* clean up the value */

        unit->scaler = value;

        trace_grlib_gptimer_writel(-1, "scaler:", unit->scaler);

        return;

    case SCALER_RELOAD_OFFSET:

        value &= 0xFFFF; /* clean up the value */

        unit->reload = value;

        trace_grlib_gptimer_writel(-1, "reload:", unit->reload);

        grlib_gptimer_set_scaler(unit, value);

        return;

    case CONFIG_OFFSET:

        /* Read Only (disable timer freeze not supported) */

        trace_grlib_gptimer_writel(-1, "config (Read Only):", 0);

        return;

    default:

        break;

    }

    timer_addr = (addr % TIMER_BASE);

    id         = (addr - TIMER_BASE) / TIMER_BASE;

    if (id >= 0 && id < unit->nr_timers) {

        /* GPTimer registers */

        switch (timer_addr) {

        case COUNTER_OFFSET:

            trace_grlib_gptimer_writel(id, "counter:", value);

            unit->timers[id].counter = value;

            grlib_gptimer_enable(&unit->timers[id]);

            return;

        case COUNTER_RELOAD_OFFSET:

            trace_grlib_gptimer_writel(id, "reload:", value);

            unit->timers[id].reload = value;

            return;

        case CONFIG_OFFSET:

            trace_grlib_gptimer_writel(id, "config:", value);

            if (value & GPTIMER_INT_PENDING) {

                /* clear pending bit */

                value &= ~GPTIMER_INT_PENDING;

            } else {

                /* keep pending bit */

                value |= unit->timers[id].config & GPTIMER_INT_PENDING;

            }

            unit->timers[id].config = value;

            /* gptimer_restart calls gptimer_enable, so if "enable" and "load"

               bits are present, we just have to call restart. */

            if (value & GPTIMER_LOAD) {

                grlib_gptimer_restart(&unit->timers[id]);

            } else if (value & GPTIMER_ENABLE) {

                grlib_gptimer_enable(&unit->timers[id]);

            }

            /* These fields must always be read as 0 */

            value &= ~(GPTIMER_LOAD & GPTIMER_DEBUG_HALT);

            unit->timers[id].config = value;

            return;

        default:

            break;

        }

    }

    trace_grlib_gptimer_unknown_register("write", addr);

}


static void check_watchpoint(int offset, int len, MemTxAttrs attrs, int flags)

{

    CPUState *cpu = current_cpu;

    CPUClass *cc = CPU_GET_CLASS(cpu);

    CPUArchState *env = cpu->env_ptr;

    target_ulong pc, cs_base;

    target_ulong vaddr;

    CPUWatchpoint *wp;

    uint32_t cpu_flags;

    if (cpu->watchpoint_hit) {

        /* We re-entered the check after replacing the TB. Now raise

         * the debug interrupt so that is will trigger after the

         * current instruction. */

        cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);

        return;

    }

    vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;

    vaddr = cc->adjust_watchpoint_address(cpu, vaddr, len);

    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {

        if (cpu_watchpoint_address_matches(wp, vaddr, len)

            && (wp->flags & flags)) {

            if (flags == BP_MEM_READ) {

                wp->flags |= BP_WATCHPOINT_HIT_READ;

            } else {

                wp->flags |= BP_WATCHPOINT_HIT_WRITE;

            }

            wp->hitaddr = vaddr;

            wp->hitattrs = attrs;

            if (!cpu->watchpoint_hit) {

                if (wp->flags & BP_CPU &&

                    !cc->debug_check_watchpoint(cpu, wp)) {

                    wp->flags &= ~BP_WATCHPOINT_HIT;

                    continue;

                }

                cpu->watchpoint_hit = wp;

                /* The tb_lock will be reset when cpu_loop_exit or

                 * cpu_loop_exit_noexc longjmp back into the cpu_exec

                 * main loop.

                 */

                tb_lock();

                tb_check_watchpoint(cpu);

                if (wp->flags & BP_STOP_BEFORE_ACCESS) {

                    cpu->exception_index = EXCP_DEBUG;

                    cpu_loop_exit(cpu);

                } else {

                    cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);

                    tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);

                    cpu_loop_exit_noexc(cpu);

                }

            }

        } else {

            wp->flags &= ~BP_WATCHPOINT_HIT;

        }

    }

}


DISAS_INSN(shift_im)

{

    TCGv reg;

    int tmp;

    TCGv shift;

    set_cc_op(s, CC_OP_FLAGS);

    reg = DREG(insn, 0);

    tmp = (insn >> 9) & 7;

    if (tmp == 0)

        tmp = 8;

    shift = tcg_const_i32(tmp);

    /* No need to flush flags becuse we know we will set C flag.  */

    if (insn & 0x100) {

        gen_helper_shl_cc(reg, cpu_env, reg, shift);

    } else {

        if (insn & 8) {

            gen_helper_shr_cc(reg, cpu_env, reg, shift);

        } else {

            gen_helper_sar_cc(reg, cpu_env, reg, shift);

        }

    }

}


static target_ulong h_protect(PowerPCCPU *cpu, sPAPRMachineState *spapr,

                              target_ulong opcode, target_ulong *args)

{

    CPUPPCState *env = &cpu->env;

    target_ulong flags = args[0];

    target_ulong pte_index = args[1];

    target_ulong avpn = args[2];

    uint64_t token;

    target_ulong v, r, rb;

    if (!valid_pte_index(env, pte_index)) {

        return H_PARAMETER;

    }

    token = ppc_hash64_start_access(cpu, pte_index);

    v = ppc_hash64_load_hpte0(cpu, token, 0);

    r = ppc_hash64_load_hpte1(cpu, token, 0);

    ppc_hash64_stop_access(token);

    if ((v & HPTE64_V_VALID) == 0 ||

        ((flags & H_AVPN) && (v & ~0x7fULL) != avpn)) {

        return H_NOT_FOUND;

    }

    r &= ~(HPTE64_R_PP0 | HPTE64_R_PP | HPTE64_R_N |

           HPTE64_R_KEY_HI | HPTE64_R_KEY_LO);

    r |= (flags << 55) & HPTE64_R_PP0;

    r |= (flags << 48) & HPTE64_R_KEY_HI;

    r |= flags & (HPTE64_R_PP | HPTE64_R_N | HPTE64_R_KEY_LO);

    rb = compute_tlbie_rb(v, r, pte_index);

    ppc_hash64_store_hpte(cpu, pte_index,

                          (v & ~HPTE64_V_VALID) | HPTE64_V_HPTE_DIRTY, 0);

    ppc_tlb_invalidate_one(env, rb);

    /* Don't need a memory barrier, due to qemu's global lock */

    ppc_hash64_store_hpte(cpu, pte_index, v | HPTE64_V_HPTE_DIRTY, r);

    return H_SUCCESS;

}


static int kvm_get_msrs(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    struct kvm_msr_entry *msrs = cpu->kvm_msr_buf->entries;

    int ret, i;

    uint64_t mtrr_top_bits;

    kvm_msr_buf_reset(cpu);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_CS, 0);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_ESP, 0);

    kvm_msr_entry_add(cpu, MSR_IA32_SYSENTER_EIP, 0);

    kvm_msr_entry_add(cpu, MSR_PAT, 0);

    if (has_msr_star) {

        kvm_msr_entry_add(cpu, MSR_STAR, 0);

    }

    if (has_msr_hsave_pa) {

        kvm_msr_entry_add(cpu, MSR_VM_HSAVE_PA, 0);

    }

    if (has_msr_tsc_aux) {

        kvm_msr_entry_add(cpu, MSR_TSC_AUX, 0);

    }

    if (has_msr_tsc_adjust) {

        kvm_msr_entry_add(cpu, MSR_TSC_ADJUST, 0);

    }

    if (has_msr_tsc_deadline) {

        kvm_msr_entry_add(cpu, MSR_IA32_TSCDEADLINE, 0);

    }

    if (has_msr_misc_enable) {

        kvm_msr_entry_add(cpu, MSR_IA32_MISC_ENABLE, 0);

    }

    if (has_msr_smbase) {

        kvm_msr_entry_add(cpu, MSR_IA32_SMBASE, 0);

    }

    if (has_msr_feature_control) {

        kvm_msr_entry_add(cpu, MSR_IA32_FEATURE_CONTROL, 0);

    }

    if (has_msr_bndcfgs) {

        kvm_msr_entry_add(cpu, MSR_IA32_BNDCFGS, 0);

    }

    if (has_msr_xss) {

        kvm_msr_entry_add(cpu, MSR_IA32_XSS, 0);

    }

    if (!env->tsc_valid) {

        kvm_msr_entry_add(cpu, MSR_IA32_TSC, 0);

        env->tsc_valid = !runstate_is_running();

    }

#ifdef TARGET_X86_64

    if (lm_capable_kernel) {

        kvm_msr_entry_add(cpu, MSR_CSTAR, 0);

        kvm_msr_entry_add(cpu, MSR_KERNELGSBASE, 0);

        kvm_msr_entry_add(cpu, MSR_FMASK, 0);

        kvm_msr_entry_add(cpu, MSR_LSTAR, 0);

    }

#endif

    kvm_msr_entry_add(cpu, MSR_KVM_SYSTEM_TIME, 0);

    kvm_msr_entry_add(cpu, MSR_KVM_WALL_CLOCK, 0);

    if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_ASYNC_PF)) {

        kvm_msr_entry_add(cpu, MSR_KVM_ASYNC_PF_EN, 0);

    }

    if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_PV_EOI)) {

        kvm_msr_entry_add(cpu, MSR_KVM_PV_EOI_EN, 0);

    }

    if (env->features[FEAT_KVM] & (1 << KVM_FEATURE_STEAL_TIME)) {

        kvm_msr_entry_add(cpu, MSR_KVM_STEAL_TIME, 0);

    }

    if (has_msr_architectural_pmu) {

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR_CTRL, 0);

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_CTRL, 0);

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_STATUS, 0);

        kvm_msr_entry_add(cpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 0);

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

            kvm_msr_entry_add(cpu, MSR_CORE_PERF_FIXED_CTR0 + i, 0);

        }

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

            kvm_msr_entry_add(cpu, MSR_P6_PERFCTR0 + i, 0);

            kvm_msr_entry_add(cpu, MSR_P6_EVNTSEL0 + i, 0);

        }

    }

    if (env->mcg_cap) {

        kvm_msr_entry_add(cpu, MSR_MCG_STATUS, 0);

        kvm_msr_entry_add(cpu, MSR_MCG_CTL, 0);

        if (has_msr_mcg_ext_ctl) {

            kvm_msr_entry_add(cpu, MSR_MCG_EXT_CTL, 0);

        }

        for (i = 0; i < (env->mcg_cap & 0xff) * 4; i++) {

            kvm_msr_entry_add(cpu, MSR_MC0_CTL + i, 0);

        }

    }

    if (has_msr_hv_hypercall) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_HYPERCALL, 0);

        kvm_msr_entry_add(cpu, HV_X64_MSR_GUEST_OS_ID, 0);

    }

    if (cpu->hyperv_vapic) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_APIC_ASSIST_PAGE, 0);

    }

    if (cpu->hyperv_time) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_REFERENCE_TSC, 0);

    }

    if (has_msr_hv_crash) {

        int j;

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

            kvm_msr_entry_add(cpu, HV_X64_MSR_CRASH_P0 + j, 0);

        }

    }

    if (has_msr_hv_runtime) {

        kvm_msr_entry_add(cpu, HV_X64_MSR_VP_RUNTIME, 0);

    }

    if (cpu->hyperv_synic) {

        uint32_t msr;

        kvm_msr_entry_add(cpu, HV_X64_MSR_SCONTROL, 0);

        kvm_msr_entry_add(cpu, HV_X64_MSR_SIEFP, 0);

        kvm_msr_entry_add(cpu, HV_X64_MSR_SIMP, 0);

        for (msr = HV_X64_MSR_SINT0; msr <= HV_X64_MSR_SINT15; msr++) {

            kvm_msr_entry_add(cpu, msr, 0);

        }

    }

    if (has_msr_hv_stimer) {

        uint32_t msr;

        for (msr = HV_X64_MSR_STIMER0_CONFIG; msr <= HV_X64_MSR_STIMER3_COUNT;

             msr++) {

            kvm_msr_entry_add(cpu, msr, 0);

        }

    }

    if (env->features[FEAT_1_EDX] & CPUID_MTRR) {

        kvm_msr_entry_add(cpu, MSR_MTRRdefType, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix64K_00000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_80000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix16K_A0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_C8000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_D8000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_E8000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F0000, 0);

        kvm_msr_entry_add(cpu, MSR_MTRRfix4K_F8000, 0);

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

            kvm_msr_entry_add(cpu, MSR_MTRRphysBase(i), 0);

            kvm_msr_entry_add(cpu, MSR_MTRRphysMask(i), 0);

        }

    }

    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_MSRS, cpu->kvm_msr_buf);

    if (ret < 0) {

        return ret;

    }

    if (ret < cpu->kvm_msr_buf->nmsrs) {

        struct kvm_msr_entry *e = &cpu->kvm_msr_buf->entries[ret];

        error_report("error: failed to get MSR 0x%" PRIx32,

                     (uint32_t)e->index);

    }

    assert(ret == cpu->kvm_msr_buf->nmsrs);

    /*

     * MTRR masks: Each mask consists of 5 parts

     * a  10..0: must be zero

     * b  11   : valid bit

     * c n-1.12: actual mask bits

     * d  51..n: reserved must be zero

     * e  63.52: reserved must be zero

     *

     * 'n' is the number of physical bits supported by the CPU and is

     * apparently always <= 52.   We know our 'n' but don't know what

     * the destinations 'n' is; it might be smaller, in which case

     * it masks (c) on loading. It might be larger, in which case

     * we fill 'd' so that d..c is consistent irrespetive of the 'n'

     * we're migrating to.

     */

    if (cpu->fill_mtrr_mask) {

        QEMU_BUILD_BUG_ON(TARGET_PHYS_ADDR_SPACE_BITS > 52);

        assert(cpu->phys_bits <= TARGET_PHYS_ADDR_SPACE_BITS);

        mtrr_top_bits = MAKE_64BIT_MASK(cpu->phys_bits, 52 - cpu->phys_bits);

    } else {

        mtrr_top_bits = 0;

    }

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

        uint32_t index = msrs[i].index;

        switch (index) {

        case MSR_IA32_SYSENTER_CS:

            env->sysenter_cs = msrs[i].data;

            break;

        case MSR_IA32_SYSENTER_ESP:

            env->sysenter_esp = msrs[i].data;

            break;

        case MSR_IA32_SYSENTER_EIP:

            env->sysenter_eip = msrs[i].data;

            break;

        case MSR_PAT:

            env->pat = msrs[i].data;

            break;

        case MSR_STAR:

            env->star = msrs[i].data;

            break;

#ifdef TARGET_X86_64

        case MSR_CSTAR:

            env->cstar = msrs[i].data;

            break;

        case MSR_KERNELGSBASE:

            env->kernelgsbase = msrs[i].data;

            break;

        case MSR_FMASK:

            env->fmask = msrs[i].data;

            break;

        case MSR_LSTAR:

            env->lstar = msrs[i].data;

            break;

#endif

        case MSR_IA32_TSC:

            env->tsc = msrs[i].data;

            break;

        case MSR_TSC_AUX:

            env->tsc_aux = msrs[i].data;

            break;

        case MSR_TSC_ADJUST:

            env->tsc_adjust = msrs[i].data;

            break;

        case MSR_IA32_TSCDEADLINE:

            env->tsc_deadline = msrs[i].data;

            break;

        case MSR_VM_HSAVE_PA:

            env->vm_hsave = msrs[i].data;

            break;

        case MSR_KVM_SYSTEM_TIME:

            env->system_time_msr = msrs[i].data;

            break;

        case MSR_KVM_WALL_CLOCK:

            env->wall_clock_msr = msrs[i].data;

            break;

        case MSR_MCG_STATUS:

            env->mcg_status = msrs[i].data;

            break;

        case MSR_MCG_CTL:

            env->mcg_ctl = msrs[i].data;

            break;

        case MSR_MCG_EXT_CTL:

            env->mcg_ext_ctl = msrs[i].data;

            break;

        case MSR_IA32_MISC_ENABLE:

            env->msr_ia32_misc_enable = msrs[i].data;

            break;

        case MSR_IA32_SMBASE:

            env->smbase = msrs[i].data;

            break;

        case MSR_IA32_FEATURE_CONTROL:

            env->msr_ia32_feature_control = msrs[i].data;

            break;

        case MSR_IA32_BNDCFGS:

            env->msr_bndcfgs = msrs[i].data;

            break;

        case MSR_IA32_XSS:

            env->xss = msrs[i].data;

            break;

        default:

            if (msrs[i].index >= MSR_MC0_CTL &&

                msrs[i].index < MSR_MC0_CTL + (env->mcg_cap & 0xff) * 4) {

                env->mce_banks[msrs[i].index - MSR_MC0_CTL] = msrs[i].data;

            }

            break;

        case MSR_KVM_ASYNC_PF_EN:

            env->async_pf_en_msr = msrs[i].data;

            break;

        case MSR_KVM_PV_EOI_EN:

            env->pv_eoi_en_msr = msrs[i].data;

            break;

        case MSR_KVM_STEAL_TIME:

            env->steal_time_msr = msrs[i].data;

            break;

        case MSR_CORE_PERF_FIXED_CTR_CTRL:

            env->msr_fixed_ctr_ctrl = msrs[i].data;

            break;

        case MSR_CORE_PERF_GLOBAL_CTRL:

            env->msr_global_ctrl = msrs[i].data;

            break;

        case MSR_CORE_PERF_GLOBAL_STATUS:

            env->msr_global_status = msrs[i].data;

            break;

        case MSR_CORE_PERF_GLOBAL_OVF_CTRL:

            env->msr_global_ovf_ctrl = msrs[i].data;

            break;

        case MSR_CORE_PERF_FIXED_CTR0 ... MSR_CORE_PERF_FIXED_CTR0 + MAX_FIXED_COUNTERS - 1:

            env->msr_fixed_counters[index - MSR_CORE_PERF_FIXED_CTR0] = msrs[i].data;

            break;

        case MSR_P6_PERFCTR0 ... MSR_P6_PERFCTR0 + MAX_GP_COUNTERS - 1:

            env->msr_gp_counters[index - MSR_P6_PERFCTR0] = msrs[i].data;

            break;

        case MSR_P6_EVNTSEL0 ... MSR_P6_EVNTSEL0 + MAX_GP_COUNTERS - 1:

            env->msr_gp_evtsel[index - MSR_P6_EVNTSEL0] = msrs[i].data;

            break;

        case HV_X64_MSR_HYPERCALL:

            env->msr_hv_hypercall = msrs[i].data;

            break;

        case HV_X64_MSR_GUEST_OS_ID:

            env->msr_hv_guest_os_id = msrs[i].data;

            break;

        case HV_X64_MSR_APIC_ASSIST_PAGE:

            env->msr_hv_vapic = msrs[i].data;

            break;

        case HV_X64_MSR_REFERENCE_TSC:

            env->msr_hv_tsc = msrs[i].data;

            break;

        case HV_X64_MSR_CRASH_P0 ... HV_X64_MSR_CRASH_P4:

            env->msr_hv_crash_params[index - HV_X64_MSR_CRASH_P0] = msrs[i].data;

            break;

        case HV_X64_MSR_VP_RUNTIME:

            env->msr_hv_runtime = msrs[i].data;

            break;

        case HV_X64_MSR_SCONTROL:

            env->msr_hv_synic_control = msrs[i].data;

            break;

        case HV_X64_MSR_SIEFP:

            env->msr_hv_synic_evt_page = msrs[i].data;

            break;

        case HV_X64_MSR_SIMP:

            env->msr_hv_synic_msg_page = msrs[i].data;

            break;

        case HV_X64_MSR_SINT0 ... HV_X64_MSR_SINT15:

            env->msr_hv_synic_sint[index - HV_X64_MSR_SINT0] = msrs[i].data;

            break;

        case HV_X64_MSR_STIMER0_CONFIG:

        case HV_X64_MSR_STIMER1_CONFIG:

        case HV_X64_MSR_STIMER2_CONFIG:

        case HV_X64_MSR_STIMER3_CONFIG:

            env->msr_hv_stimer_config[(index - HV_X64_MSR_STIMER0_CONFIG)/2] =

                                msrs[i].data;

            break;

        case HV_X64_MSR_STIMER0_COUNT:

        case HV_X64_MSR_STIMER1_COUNT:

        case HV_X64_MSR_STIMER2_COUNT:

        case HV_X64_MSR_STIMER3_COUNT:

            env->msr_hv_stimer_count[(index - HV_X64_MSR_STIMER0_COUNT)/2] =

                                msrs[i].data;

            break;

        case MSR_MTRRdefType:

            env->mtrr_deftype = msrs[i].data;

            break;

        case MSR_MTRRfix64K_00000:

            env->mtrr_fixed[0] = msrs[i].data;

            break;

        case MSR_MTRRfix16K_80000:

            env->mtrr_fixed[1] = msrs[i].data;

            break;

        case MSR_MTRRfix16K_A0000:

            env->mtrr_fixed[2] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_C0000:

            env->mtrr_fixed[3] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_C8000:

            env->mtrr_fixed[4] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_D0000:

            env->mtrr_fixed[5] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_D8000:

            env->mtrr_fixed[6] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_E0000:

            env->mtrr_fixed[7] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_E8000:

            env->mtrr_fixed[8] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_F0000:

            env->mtrr_fixed[9] = msrs[i].data;

            break;

        case MSR_MTRRfix4K_F8000:

            env->mtrr_fixed[10] = msrs[i].data;

            break;

        case MSR_MTRRphysBase(0) ... MSR_MTRRphysMask(MSR_MTRRcap_VCNT - 1):

            if (index & 1) {

                env->mtrr_var[MSR_MTRRphysIndex(index)].mask = msrs[i].data |

                                                               mtrr_top_bits;

            } else {

                env->mtrr_var[MSR_MTRRphysIndex(index)].base = msrs[i].data;

            }

            break;

        }

    }

    return 0;

}


static void blk_mig_unlock(void)

{

    qemu_mutex_unlock(&block_mig_state.lock);

}


static void do_tb_flush(CPUState *cpu, void *data)

{

    unsigned tb_flush_req = (unsigned) (uintptr_t) data;

    tb_lock();

    /* If it's already been done on request of another CPU,

     * just retry.

     */

    if (tcg_ctx.tb_ctx.tb_flush_count != tb_flush_req) {

        goto done;

    }

#if defined(DEBUG_FLUSH)

    printf("qemu: flush code_size=%ld nb_tbs=%d avg_tb_size=%ld\n",

           (unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer),

           tcg_ctx.tb_ctx.nb_tbs, tcg_ctx.tb_ctx.nb_tbs > 0 ?

           ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)) /

           tcg_ctx.tb_ctx.nb_tbs : 0);

#endif

    if ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)

        > tcg_ctx.code_gen_buffer_size) {

        cpu_abort(cpu, "Internal error: code buffer overflow\n");

    }

    CPU_FOREACH(cpu) {

        int i;

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

            atomic_set(&cpu->tb_jmp_cache[i], NULL);

        }

    }

    tcg_ctx.tb_ctx.nb_tbs = 0;

    qht_reset_size(&tcg_ctx.tb_ctx.htable, CODE_GEN_HTABLE_SIZE);

    page_flush_tb();

    tcg_ctx.code_gen_ptr = tcg_ctx.code_gen_buffer;

    /* XXX: flush processor icache at this point if cache flush is

       expensive */

    atomic_mb_set(&tcg_ctx.tb_ctx.tb_flush_count,

                  tcg_ctx.tb_ctx.tb_flush_count + 1);

done:

    tb_unlock();

}