static void chomp6(ChannelData *ctx, int16_t *output, uint8_t val,

                   const uint16_t tab1[],

                   const int16_t *tab2, int tab2_stride,

                   uint32_t numChannels)

{

    int16_t current;

    current = tab2[((ctx->index & 0x7f0) >> 4)*tab2_stride + val];

    if ((ctx->previous ^ current) >= 0) {

        ctx->factor = FFMIN(ctx->factor + 506, 32767);

    } else {

        if (ctx->factor - 314 < -32768)

            ctx->factor = -32767;

        else

            ctx->factor -= 314;

    }

    current = mace_broken_clip_int16(current + ctx->level);

    ctx->level = ((current*ctx->factor) >> 15);

    current >>= 1;

    output[0] = QT_8S_2_16S(ctx->previous + ctx->prev2 -

                            ((ctx->prev2-current) >> 2));

    output[numChannels] = QT_8S_2_16S(ctx->previous + current +

                                      ((ctx->prev2-current) >> 2));

    ctx->prev2 = ctx->previous;

    ctx->previous = current;

    if ((ctx->index += tab1[val] - (ctx->index >> 5)) < 0)

        ctx->index = 0;

}


aio_read_done(void *opaque, int ret)

{

	struct aio_ctx *ctx = opaque;

	struct timeval t2;

	gettimeofday(&t2, NULL);

	if (ret < 0) {

		printf("readv failed: %s\n", strerror(-ret));

		return;

	}

	if (ctx->Pflag) {

		void *cmp_buf = malloc(ctx->qiov.size);

		memset(cmp_buf, ctx->pattern, ctx->qiov.size);

		if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {

			printf("Pattern verification failed at offset %lld, "

				"%zd bytes\n",

				(long long) ctx->offset, ctx->qiov.size);

		}

		free(cmp_buf);

	}

	if (ctx->qflag) {

		return;

	}

	if (ctx->vflag) {

		dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);

	}

	/* Finally, report back -- -C gives a parsable format */

	t2 = tsub(t2, ctx->t1);

	print_report("read", &t2, ctx->offset, ctx->qiov.size,

		     ctx->qiov.size, 1, ctx->Cflag);

	qemu_io_free(ctx->buf);

	free(ctx);

}


void helper_retry(void)

{

    env->pc = env->tsptr->tpc;

    env->npc = env->tsptr->tnpc;

    PUT_CCR(env, env->tsptr->tstate >> 32);

    env->asi = (env->tsptr->tstate >> 24) & 0xff;

    change_pstate((env->tsptr->tstate >> 8) & 0xf3f);

    PUT_CWP64(env, env->tsptr->tstate & 0xff);

    env->tl--;

    env->tsptr = &env->ts[env->tl & MAXTL_MASK];

}


static void slirp_hostfwd(SlirpState *s, Monitor *mon, const char *redir_str,

                          int legacy_format)

{

    struct in_addr host_addr = { .s_addr = INADDR_ANY };

    struct in_addr guest_addr = { .s_addr = 0 };

    int host_port, guest_port;

    const char *p;

    char buf[256];

    int is_udp;

    char *end;

    p = redir_str;

    if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

        goto fail_syntax;

    }

    if (!strcmp(buf, "tcp") || buf[0] == '\0') {

        is_udp = 0;

    } else if (!strcmp(buf, "udp")) {

        is_udp = 1;

    } else {

        goto fail_syntax;

    }

    if (!legacy_format) {

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

        if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {

            goto fail_syntax;

        }

    }

    if (get_str_sep(buf, sizeof(buf), &p, legacy_format ? ':' : '-') < 0) {

        goto fail_syntax;

    }

    host_port = strtol(buf, &end, 0);

    if (*end != '\0' || host_port < 1 || host_port > 65535) {

        goto fail_syntax;

    }

    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

        goto fail_syntax;

    }

    if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {

        goto fail_syntax;

    }

    guest_port = strtol(p, &end, 0);

    if (*end != '\0' || guest_port < 1 || guest_port > 65535) {

        goto fail_syntax;

    }

    if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,

                          guest_port) < 0) {

        config_error(mon, "could not set up host forwarding rule '%s'\n",

                     redir_str);

    }

    return;

 fail_syntax:

    config_error(mon, "invalid host forwarding rule '%s'\n", redir_str);

}


static inline int RENAME(yuv420_rgb24)(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

             int srcSliceH, uint8_t* dst[], int dstStride[]){

    int y, h_size;

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    h_size= (c->dstW+7)&~7;

    if(h_size*3 > FFABS(dstStride[0])) h_size-=8;

    __asm__ __volatile__ ("pxor %mm4, %mm4;" /* zero mm4 */ );

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

	uint8_t *_image = dst[0] + (y+srcSliceY)*dstStride[0];

	uint8_t *_py = src[0] + y*srcStride[0];

	uint8_t *_pu = src[1] + (y>>1)*srcStride[1];

	uint8_t *_pv = src[2] + (y>>1)*srcStride[2];

	long index= -h_size/2;

	    /* this mmx assembly code deals with SINGLE scan line at a time, it convert 8

	       pixels in each iteration */

	    __asm__ __volatile__ (

	/* load data for start of next scan line */

		     "movd (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "movq (%5, %0, 2), %%mm6;" /* Load 8  Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

//		    ".balign 16			\n\t"

		    "1:				\n\t"

YUV2RGB

	/* mm0=B, %%mm2=G, %%mm1=R */

#ifdef HAVE_MMX2

			"movq "MANGLE(M24A)", %%mm4	\n\t"

			"movq "MANGLE(M24C)", %%mm7	\n\t"

			"pshufw $0x50, %%mm0, %%mm5	\n\t" /* B3 B2 B3 B2  B1 B0 B1 B0 */

			"pshufw $0x50, %%mm2, %%mm3	\n\t" /* G3 G2 G3 G2  G1 G0 G1 G0 */

			"pshufw $0x00, %%mm1, %%mm6	\n\t" /* R1 R0 R1 R0  R1 R0 R1 R0 */

			"pand %%mm4, %%mm5		\n\t" /*    B2        B1       B0 */

			"pand %%mm4, %%mm3		\n\t" /*    G2        G1       G0 */

			"pand %%mm7, %%mm6		\n\t" /*       R1        R0       */

			"psllq $8, %%mm3		\n\t" /* G2        G1       G0    */

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

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

			MOVNTQ" %%mm6, (%1)		\n\t"

			"psrlq $8, %%mm2		\n\t" /* 00 G7 G6 G5  G4 G3 G2 G1 */

			"pshufw $0xA5, %%mm0, %%mm5	\n\t" /* B5 B4 B5 B4  B3 B2 B3 B2 */

			"pshufw $0x55, %%mm2, %%mm3	\n\t" /* G4 G3 G4 G3  G4 G3 G4 G3 */

			"pshufw $0xA5, %%mm1, %%mm6	\n\t" /* R5 R4 R5 R4  R3 R2 R3 R2 */

			"pand "MANGLE(M24B)", %%mm5	\n\t" /* B5       B4        B3    */

			"pand %%mm7, %%mm3		\n\t" /*       G4        G3       */

			"pand %%mm4, %%mm6		\n\t" /*    R4        R3       R2 */

			"por %%mm5, %%mm3		\n\t" /* B5    G4 B4     G3 B3    */

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

			MOVNTQ" %%mm6, 8(%1)		\n\t"

			"pshufw $0xFF, %%mm0, %%mm5	\n\t" /* B7 B6 B7 B6  B7 B6 B6 B7 */

			"pshufw $0xFA, %%mm2, %%mm3	\n\t" /* 00 G7 00 G7  G6 G5 G6 G5 */

			"pshufw $0xFA, %%mm1, %%mm6	\n\t" /* R7 R6 R7 R6  R5 R4 R5 R4 */

			"movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

			"pand %%mm7, %%mm5		\n\t" /*       B7        B6       */

			"pand %%mm4, %%mm3		\n\t" /*    G7        G6       G5 */

			"pand "MANGLE(M24B)", %%mm6	\n\t" /* R7       R6        R5    */

			"movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

\

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

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

			MOVNTQ" %%mm6, 16(%1)		\n\t"

			"movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

			"pxor %%mm4, %%mm4		\n\t"

#else

			"pxor %%mm4, %%mm4		\n\t"

			"movq %%mm0, %%mm5		\n\t" /* B */

			"movq %%mm1, %%mm6		\n\t" /* R */

			"punpcklbw %%mm2, %%mm0		\n\t" /* GBGBGBGB 0 */

			"punpcklbw %%mm4, %%mm1		\n\t" /* 0R0R0R0R 0 */

			"punpckhbw %%mm2, %%mm5		\n\t" /* GBGBGBGB 2 */

			"punpckhbw %%mm4, %%mm6		\n\t" /* 0R0R0R0R 2 */

			"movq %%mm0, %%mm7		\n\t" /* GBGBGBGB 0 */

			"movq %%mm5, %%mm3		\n\t" /* GBGBGBGB 2 */

			"punpcklwd %%mm1, %%mm7		\n\t" /* 0RGB0RGB 0 */

			"punpckhwd %%mm1, %%mm0		\n\t" /* 0RGB0RGB 1 */

			"punpcklwd %%mm6, %%mm5		\n\t" /* 0RGB0RGB 2 */

			"punpckhwd %%mm6, %%mm3		\n\t" /* 0RGB0RGB 3 */

			"movq %%mm7, %%mm2		\n\t" /* 0RGB0RGB 0 */

			"movq %%mm0, %%mm6		\n\t" /* 0RGB0RGB 1 */

			"movq %%mm5, %%mm1		\n\t" /* 0RGB0RGB 2 */

			"movq %%mm3, %%mm4		\n\t" /* 0RGB0RGB 3 */

			"psllq $40, %%mm7		\n\t" /* RGB00000 0 */

			"psllq $40, %%mm0		\n\t" /* RGB00000 1 */

			"psllq $40, %%mm5		\n\t" /* RGB00000 2 */

			"psllq $40, %%mm3		\n\t" /* RGB00000 3 */

			"punpckhdq %%mm2, %%mm7		\n\t" /* 0RGBRGB0 0 */

			"punpckhdq %%mm6, %%mm0		\n\t" /* 0RGBRGB0 1 */

			"punpckhdq %%mm1, %%mm5		\n\t" /* 0RGBRGB0 2 */

			"punpckhdq %%mm4, %%mm3		\n\t" /* 0RGBRGB0 3 */

			"psrlq $8, %%mm7		\n\t" /* 00RGBRGB 0 */

			"movq %%mm0, %%mm6		\n\t" /* 0RGBRGB0 1 */

			"psllq $40, %%mm0		\n\t" /* GB000000 1 */

			"por %%mm0, %%mm7		\n\t" /* GBRGBRGB 0 */

			MOVNTQ" %%mm7, (%1)		\n\t"

			"movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

			"psrlq $24, %%mm6		\n\t" /* 0000RGBR 1 */

			"movq %%mm5, %%mm1		\n\t" /* 0RGBRGB0 2 */

			"psllq $24, %%mm5		\n\t" /* BRGB0000 2 */

			"por %%mm5, %%mm6		\n\t" /* BRGBRGBR 1 */

			MOVNTQ" %%mm6, 8(%1)		\n\t"

			"movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

			"psrlq $40, %%mm1		\n\t" /* 000000RG 2 */

			"psllq $8, %%mm3		\n\t" /* RGBRGB00 3 */

			"por %%mm3, %%mm1		\n\t" /* RGBRGBRG 2 */

			MOVNTQ" %%mm1, 16(%1)		\n\t"

			"movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

			"pxor %%mm4, %%mm4		\n\t"

#endif

		     "add $24, %1			\n\t"

		     "add $4, %0			\n\t"

		     " js 1b				\n\t"

		     : "+r" (index), "+r" (_image)

		     : "r" (_pu - index), "r" (_pv - index), "r"(&c->redDither), "r" (_py - 2*index)

		     );

    }

    __asm__ __volatile__ (EMMS);

    return srcSliceH;

}


static void mux_chr_read(void *opaque, const uint8_t *buf, int size)

{

    CharDriverState *chr = opaque;

    MuxDriver *d = chr->opaque;

    int m = chr->focus;

    int i;

    mux_chr_accept_input (opaque);

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

        if (mux_proc_byte(chr, d, buf[i])) {

            if (d->prod == d->cons &&

                d->chr_can_read[m] &&

                d->chr_can_read[m](d->ext_opaque[m]))

                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);

            else

                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];

        }

}


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

{

    VideoData *s = s1->priv_data;

    AVStream *st;

    int width, height;

    int video_fd, frame_size;

    int ret, frame_rate, frame_rate_base;

    int desired_palette, desired_depth;

    struct video_tuner tuner;

    struct video_audio audio;

    struct video_picture pict;

    int j;

    int vformat_num = sizeof(video_formats) / sizeof(video_formats[0]);

    if (ap->width <= 0 || ap->height <= 0 || ap->time_base.den <= 0) {

        av_log(s1, AV_LOG_ERROR, "Bad capture size (%dx%d) or wrong time base (%d)\n",

            ap->width, ap->height, ap->time_base.den);

        return -1;

    }

    width = ap->width;

    height = ap->height;

    frame_rate      = ap->time_base.den;

    frame_rate_base = ap->time_base.num;

    if((unsigned)width > 32767 || (unsigned)height > 32767) {

        av_log(s1, AV_LOG_ERROR, "Capture size is out of range: %dx%d\n",

            width, height);

        return -1;

    }

    st = av_new_stream(s1, 0);

    if (!st)

        return AVERROR(ENOMEM);

    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    s->width = width;

    s->height = height;

    s->frame_rate      = frame_rate;

    s->frame_rate_base = frame_rate_base;

    video_fd = open(s1->filename, O_RDWR);

    if (video_fd < 0) {

        av_log(s1, AV_LOG_ERROR, "%s: %s\n", s1->filename, strerror(errno));

        goto fail;

    }

    if (ioctl(video_fd,VIDIOCGCAP, &s->video_cap) < 0) {

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

        goto fail;

    }

    if (!(s->video_cap.type & VID_TYPE_CAPTURE)) {

        av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not handle capture\n");

        goto fail;

    }

    desired_palette = -1;

    desired_depth = -1;

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

        if (ap->pix_fmt == video_formats[j].pix_fmt) {

            desired_palette = video_formats[j].palette;

            desired_depth = video_formats[j].depth;

            break;

        }

    }

    /* set tv standard */

    if (ap->standard && !ioctl(video_fd, VIDIOCGTUNER, &tuner)) {

        if (!strcasecmp(ap->standard, "pal"))

            tuner.mode = VIDEO_MODE_PAL;

        else if (!strcasecmp(ap->standard, "secam"))

            tuner.mode = VIDEO_MODE_SECAM;

        else

            tuner.mode = VIDEO_MODE_NTSC;

        ioctl(video_fd, VIDIOCSTUNER, &tuner);

    }

    /* unmute audio */

    audio.audio = 0;

    ioctl(video_fd, VIDIOCGAUDIO, &audio);

    memcpy(&s->audio_saved, &audio, sizeof(audio));

    audio.flags &= ~VIDEO_AUDIO_MUTE;

    ioctl(video_fd, VIDIOCSAUDIO, &audio);

    ioctl(video_fd, VIDIOCGPICT, &pict);

#if 0

    printf("v4l: colour=%d hue=%d brightness=%d constrast=%d whiteness=%d\n",

           pict.colour,

           pict.hue,

           pict.brightness,

           pict.contrast,

           pict.whiteness);

#endif

    /* try to choose a suitable video format */

    pict.palette = desired_palette;

    pict.depth= desired_depth;

    if (desired_palette == -1 || (ret = ioctl(video_fd, VIDIOCSPICT, &pict)) < 0) {

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

            pict.palette = video_formats[j].palette;

            pict.depth = video_formats[j].depth;

            if (-1 != ioctl(video_fd, VIDIOCSPICT, &pict))

                break;

        }

        if (j >= vformat_num)

            goto fail1;

    }

    ret = ioctl(video_fd,VIDIOCGMBUF,&s->gb_buffers);

    if (ret < 0) {

        /* try to use read based access */

        struct video_window win;

        int val;

        win.x = 0;

        win.y = 0;

        win.width = width;

        win.height = height;

        win.chromakey = -1;

        win.flags = 0;

        ioctl(video_fd, VIDIOCSWIN, &win);

        s->frame_format = pict.palette;

        val = 1;

        ioctl(video_fd, VIDIOCCAPTURE, &val);

        s->time_frame = av_gettime() * s->frame_rate / s->frame_rate_base;

        s->use_mmap = 0;

    } else {

        s->video_buf = mmap(0,s->gb_buffers.size,PROT_READ|PROT_WRITE,MAP_SHARED,video_fd,0);

        if ((unsigned char*)-1 == s->video_buf) {

            s->video_buf = mmap(0,s->gb_buffers.size,PROT_READ|PROT_WRITE,MAP_PRIVATE,video_fd,0);

            if ((unsigned char*)-1 == s->video_buf) {

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

                goto fail;

            }

        }

        s->gb_frame = 0;

        s->time_frame = av_gettime() * s->frame_rate / s->frame_rate_base;

        /* start to grab the first frame */

        s->gb_buf.frame = s->gb_frame % s->gb_buffers.frames;

        s->gb_buf.height = height;

        s->gb_buf.width = width;

        s->gb_buf.format = pict.palette;

        ret = ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf);

        if (ret < 0) {

            if (errno != EAGAIN) {

            fail1:

                av_log(s1, AV_LOG_ERROR, "Fatal: grab device does not support suitable format\n");

            } else {

                av_log(s1, AV_LOG_ERROR,"Fatal: grab device does not receive any video signal\n");

            }

            goto fail;

        }

        for (j = 1; j < s->gb_buffers.frames; j++) {

          s->gb_buf.frame = j;

          ioctl(video_fd, VIDIOCMCAPTURE, &s->gb_buf);

        }

        s->frame_format = s->gb_buf.format;

        s->use_mmap = 1;

    }

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

        if (s->frame_format == video_formats[j].palette) {

            frame_size = width * height * video_formats[j].depth / 8;

            st->codec->pix_fmt = video_formats[j].pix_fmt;

            break;

        }

    }

    if (j >= vformat_num)

        goto fail;

    s->fd = video_fd;

    s->frame_size = frame_size;

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_RAWVIDEO;

    st->codec->width = width;

    st->codec->height = height;

    st->codec->time_base.den      = frame_rate;

    st->codec->time_base.num = frame_rate_base;

    st->codec->bit_rate = frame_size * 1/av_q2d(st->codec->time_base) * 8;

    return 0;

 fail:

    if (video_fd >= 0)

        close(video_fd);

    av_free(st);

    return AVERROR(EIO);

}


static void ipvideo_decode_opcodes(IpvideoContext *s, AVFrame *frame)

{

    int x, y;

    unsigned char opcode;

    int ret;

    GetBitContext gb;

    bytestream2_skip(&s->stream_ptr, 14); /* data starts 14 bytes in */

    if (!s->is_16bpp) {

        /* this is PAL8, so make the palette available */

        memcpy(frame->data[1], s->pal, AVPALETTE_SIZE);

        s->stride = frame->linesize[0];

    } else {

        s->stride = frame->linesize[0] >> 1;

        s->mv_ptr = s->stream_ptr;

        bytestream2_skip(&s->mv_ptr, bytestream2_get_le16(&s->stream_ptr));

    }

    s->line_inc = s->stride - 8;

    s->upper_motion_limit_offset = (s->avctx->height - 8) * frame->linesize[0]

                                  + (s->avctx->width - 8) * (1 + s->is_16bpp);

    init_get_bits(&gb, s->decoding_map, s->decoding_map_size * 8);

    for (y = 0; y < s->avctx->height; y += 8) {

        for (x = 0; x < s->avctx->width; x += 8) {

            opcode = get_bits(&gb, 4);

            ff_tlog(s->avctx,

                    "  block @ (%3d, %3d): encoding 0x%X, data ptr offset %d\n",

                    x, y, opcode, bytestream2_tell(&s->stream_ptr));

            if (!s->is_16bpp) {

                s->pixel_ptr = frame->data[0] + x

                              + y*frame->linesize[0];

                ret = ipvideo_decode_block[opcode](s, frame);

            } else {

                s->pixel_ptr = frame->data[0] + x*2

                              + y*frame->linesize[0];

                ret = ipvideo_decode_block16[opcode](s, frame);

            }

            if (ret != 0) {

                av_log(s->avctx, AV_LOG_ERROR, "decode problem on frame %d, @ block (%d, %d)\n",

                       s->avctx->frame_number, x, y);

            }

        }

    }

    if (bytestream2_get_bytes_left(&s->stream_ptr) > 1) {

        av_log(s->avctx, AV_LOG_DEBUG,

               "decode finished with %d bytes left over\n",

               bytestream2_get_bytes_left(&s->stream_ptr));

    }

}


static void gluster_finish_aiocb(struct glfs_fd *fd, ssize_t ret, void *arg)

{

    GlusterAIOCB *acb = (GlusterAIOCB *)arg;

    BlockDriverState *bs = acb->common.bs;

    BDRVGlusterState *s = bs->opaque;

    int retval;

    acb->ret = ret;

    retval = qemu_write_full(s->fds[GLUSTER_FD_WRITE], &acb, sizeof(acb));

    if (retval != sizeof(acb)) {

        /*

         * Gluster AIO callback thread failed to notify the waiting

         * QEMU thread about IO completion.

         *

         * Complete this IO request and make the disk inaccessible for

         * subsequent reads and writes.

         */

        error_report("Gluster failed to notify QEMU about IO completion");

        qemu_mutex_lock_iothread(); /* We are in gluster thread context */

        acb->common.cb(acb->common.opaque, -EIO);

        qemu_aio_release(acb);

        close(s->fds[GLUSTER_FD_READ]);

        close(s->fds[GLUSTER_FD_WRITE]);

        qemu_aio_set_fd_handler(s->fds[GLUSTER_FD_READ], NULL, NULL, NULL);

        bs->drv = NULL; /* Make the disk inaccessible */

        qemu_mutex_unlock_iothread();

    }

}


static void close_htab_fd(sPAPRMachineState *spapr)

{

    if (spapr->htab_fd >= 0) {

        close(spapr->htab_fd);

    }

    spapr->htab_fd = -1;

}


static void intel_hda_update_irq(IntelHDAState *d)

{

    int msi = d->msi && msi_enabled(&d->pci);

    int level;

    intel_hda_update_int_sts(d);

    if (d->int_sts & (1 << 31) && d->int_ctl & (1 << 31)) {

        level = 1;

    } else {

        level = 0;

    }

    dprint(d, 2, "%s: level %d [%s]\n", __FUNCTION__,

           level, msi ? "msi" : "intx");

    if (msi) {

        if (level) {

            msi_notify(&d->pci, 0);

        }

    } else {

        pci_set_irq(&d->pci, level);

    }

}


static int gxf_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {

    int res = 0;

    uint64_t pos;

    uint64_t maxlen = 100 * 1024 * 1024;

    AVStream *st = s->streams[0];

    int64_t start_time = s->streams[stream_index]->start_time;

    int64_t found;

    int idx;

    if (timestamp < start_time) timestamp = start_time;

    idx = av_index_search_timestamp(st, timestamp - start_time,

                                    AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);

    if (idx < 0)

        return -1;

    pos = st->index_entries[idx].pos;

    if (idx < st->nb_index_entries - 2)

        maxlen = st->index_entries[idx + 2].pos - pos;

    maxlen = FFMAX(maxlen, 200 * 1024);

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

    if (res < 0)

        return res;

    found = gxf_resync_media(s, maxlen, -1, timestamp);

    if (FFABS(found - timestamp) > 4)

        return -1;

    return 0;

}


static int iscsi_aio_discard_acb(IscsiAIOCB *acb) {

    struct iscsi_context *iscsi = acb->iscsilun->iscsi;

    struct unmap_list list[1];

    acb->canceled   = 0;

    acb->bh         = NULL;

    acb->status     = -EINPROGRESS;

    acb->buf        = NULL;

    list[0].lba = sector_qemu2lun(acb->sector_num, acb->iscsilun);

    list[0].num = acb->nb_sectors * BDRV_SECTOR_SIZE / acb->iscsilun->block_size;

    acb->task = iscsi_unmap_task(iscsi, acb->iscsilun->lun,

                                 0, 0, &list[0], 1,

                                 iscsi_unmap_cb,

                                 acb);

    if (acb->task == NULL) {

        error_report("iSCSI: Failed to send unmap command. %s",

                     iscsi_get_error(iscsi));

        return -1;

    }

    return 0;

}


static void vmsa_tcr_el1_write(CPUARMState *env, const ARMCPRegInfo *ri,

                               uint64_t value)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    /* For AArch64 the A1 bit could result in a change of ASID, so TLB flush. */

    tlb_flush(CPU(cpu), 1);

    env->cp15.c2_control = value;

}


cpu_mips_check_sign_extensions (CPUState *env, FILE *f,

                                int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

                                int flags)

{

    int i;

    if (!SIGN_EXT_P(env->active_tc.PC))

        cpu_fprintf(f, "BROKEN: pc=0x" TARGET_FMT_lx "\n", env->active_tc.PC);

    if (!SIGN_EXT_P(env->active_tc.HI[0]))

        cpu_fprintf(f, "BROKEN: HI=0x" TARGET_FMT_lx "\n", env->active_tc.HI[0]);

    if (!SIGN_EXT_P(env->active_tc.LO[0]))

        cpu_fprintf(f, "BROKEN: LO=0x" TARGET_FMT_lx "\n", env->active_tc.LO[0]);

    if (!SIGN_EXT_P(env->btarget))

        cpu_fprintf(f, "BROKEN: btarget=0x" TARGET_FMT_lx "\n", env->btarget);

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

        if (!SIGN_EXT_P(env->active_tc.gpr[i]))

            cpu_fprintf(f, "BROKEN: %s=0x" TARGET_FMT_lx "\n", regnames[i], env->active_tc.gpr[i]);

    }

    if (!SIGN_EXT_P(env->CP0_EPC))

        cpu_fprintf(f, "BROKEN: EPC=0x" TARGET_FMT_lx "\n", env->CP0_EPC);

    if (!SIGN_EXT_P(env->lladdr))

        cpu_fprintf(f, "BROKEN: LLAddr=0x" TARGET_FMT_lx "\n", env->lladdr);

}


void qemu_register_clock_reset_notifier(QEMUClock *clock,

                                        Notifier *notifier)

{

    qemu_clock_register_reset_notifier(clock->type, notifier);

}


static int match_format(const char *name, const char *names)

{

    const char *p;

    int len, namelen;

    if (!name || !names)

        return 0;

    namelen = strlen(name);

    while ((p = strchr(names, ','))) {

        len = FFMAX(p - names, namelen);

        if (!av_strncasecmp(name, names, len))

            return 1;

        names = p + 1;

    }

    return !av_strcasecmp(name, names);

}


static int check_refcounts_l1(BlockDriverState *bs,

                              uint16_t *refcount_table,

                              int refcount_table_size,

                              int64_t l1_table_offset, int l1_size,

                              int check_copied)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2;

    int l2_size, i, j, nb_csectors, refcount;

    l2_table = NULL;

    l1_size2 = l1_size * sizeof(uint64_t);

    inc_refcounts(bs, refcount_table, refcount_table_size,

                  l1_table_offset, l1_size2);

    l1_table = qemu_malloc(l1_size2);

    if (bdrv_pread(s->hd, l1_table_offset,

                   l1_table, l1_size2) != l1_size2)

        goto fail;

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

        be64_to_cpus(&l1_table[i]);

    l2_size = s->l2_size * sizeof(uint64_t);

    l2_table = qemu_malloc(l2_size);

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

        l2_offset = l1_table[i];

        if (l2_offset) {

            if (check_copied) {

                refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);

                if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {

                    printf("ERROR OFLAG_COPIED: l2_offset=%llx refcount=%d\n",

                           l2_offset, refcount);

                }

            }

            l2_offset &= ~QCOW_OFLAG_COPIED;

            if (bdrv_pread(s->hd, l2_offset, l2_table, l2_size) != l2_size)

                goto fail;

            for(j = 0; j < s->l2_size; j++) {

                offset = be64_to_cpu(l2_table[j]);

                if (offset != 0) {

                    if (offset & QCOW_OFLAG_COMPRESSED) {

                        if (offset & QCOW_OFLAG_COPIED) {

                            printf("ERROR: cluster %lld: copied flag must never be set for compressed clusters\n",

                                   offset >> s->cluster_bits);

                            offset &= ~QCOW_OFLAG_COPIED;

                        }

                        nb_csectors = ((offset >> s->csize_shift) &

                                       s->csize_mask) + 1;

                        offset &= s->cluster_offset_mask;

                        inc_refcounts(bs, refcount_table,

                                      refcount_table_size,

                                      offset & ~511, nb_csectors * 512);

                    } else {

                        if (check_copied) {

                            refcount = get_refcount(bs, (offset & ~QCOW_OFLAG_COPIED) >> s->cluster_bits);

                            if ((refcount == 1) != ((offset & QCOW_OFLAG_COPIED) != 0)) {

                                printf("ERROR OFLAG_COPIED: offset=%llx refcount=%d\n",

                                       offset, refcount);

                            }

                        }

                        offset &= ~QCOW_OFLAG_COPIED;

                        inc_refcounts(bs, refcount_table,

                                      refcount_table_size,

                                      offset, s->cluster_size);

                    }

                }

            }

            inc_refcounts(bs, refcount_table,

                          refcount_table_size,

                          l2_offset,

                          s->cluster_size);

        }

    }

    qemu_free(l1_table);

    qemu_free(l2_table);

    return 0;

 fail:

    printf("ERROR: I/O error in check_refcounts_l1\n");

    qemu_free(l1_table);

    qemu_free(l2_table);

    return -EIO;

}


static void ide_sector_read_cb(void *opaque, int ret)

{

    IDEState *s = opaque;

    int n;

    s->pio_aiocb = NULL;

    s->status &= ~BUSY_STAT;

    if (ret == -ECANCELED) {

        return;

    }

    block_acct_done(bdrv_get_stats(s->bs), &s->acct);

    if (ret != 0) {

        if (ide_handle_rw_error(s, -ret, IDE_RETRY_PIO |

                                IDE_RETRY_READ)) {

            return;

        }

    }

    n = s->nsector;

    if (n > s->req_nb_sectors) {

        n = s->req_nb_sectors;

    }

    /* Allow the guest to read the io_buffer */

    ide_transfer_start(s, s->io_buffer, n * BDRV_SECTOR_SIZE, ide_sector_read);

    ide_set_irq(s->bus);

    ide_set_sector(s, ide_get_sector(s) + n);

    s->nsector -= n;

}


static void logerr (struct audio_pt *pt, int err, const char *fmt, ...)

{

    va_list ap;

    va_start (ap, fmt);

    AUD_vlog (pt->drv, fmt, ap);

    va_end (ap);

    AUD_log (NULL, "\n");

    AUD_log (pt->drv, "Reason: %s\n", strerror (err));

}


static void slavio_timer_reset(DeviceState *d)

{

    SLAVIO_TIMERState *s = container_of(d, SLAVIO_TIMERState, busdev.qdev);

    unsigned int i;

    CPUTimerState *curr_timer;

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

        curr_timer = &s->cputimer[i];

        curr_timer->limit = 0;

        curr_timer->count = 0;

        curr_timer->reached = 0;

        if (i < s->num_cpus) {

            ptimer_set_limit(curr_timer->timer,

                             LIMIT_TO_PERIODS(TIMER_MAX_COUNT32), 1);

            ptimer_run(curr_timer->timer, 0);

        }

        curr_timer->running = 1;

    }

    s->cputimer_mode = 0;

}


static void coroutine_delete(Coroutine *co)

{

    if (CONFIG_COROUTINE_POOL) {

        qemu_mutex_lock(&pool_lock);

        if (pool_size < pool_max_size) {

            QSLIST_INSERT_HEAD(&pool, co, pool_next);

            co->caller = NULL;

            pool_size++;

            qemu_mutex_unlock(&pool_lock);

            return;

        }

        qemu_mutex_unlock(&pool_lock);

    }

    qemu_coroutine_delete(co);

}


static void arm_post_translate_insn(CPUARMState *env, DisasContext *dc)

{

    if (dc->condjmp && !dc->base.is_jmp) {

        gen_set_label(dc->condlabel);

        dc->condjmp = 0;

    }

    /* Translation stops when a conditional branch is encountered.

     * Otherwise the subsequent code could get translated several times.

     * Also stop translation when a page boundary is reached.  This

     * ensures prefetch aborts occur at the right place.

     *

     * We want to stop the TB if the next insn starts in a new page,

     * or if it spans between this page and the next. This means that

     * if we're looking at the last halfword in the page we need to

     * see if it's a 16-bit Thumb insn (which will fit in this TB)

     * or a 32-bit Thumb insn (which won't).

     * This is to avoid generating a silly TB with a single 16-bit insn

     * in it at the end of this page (which would execute correctly

     * but isn't very efficient).

     */

    if (dc->base.is_jmp == DISAS_NEXT

        && (dc->pc >= dc->next_page_start

            || (dc->pc >= dc->next_page_start - 3

                && insn_crosses_page(env, dc)))) {

        dc->base.is_jmp = DISAS_TOO_MANY;

    }

    dc->base.pc_next = dc->pc;

    translator_loop_temp_check(&dc->base);

}


static void r2d_init(MachineState *machine)

{

    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;

    SuperHCPU *cpu;

    CPUSH4State *env;

    ResetData *reset_info;

    struct SH7750State *s;

    MemoryRegion *sdram = g_new(MemoryRegion, 1);

    qemu_irq *irq;

    DriveInfo *dinfo;

    int i;

    DeviceState *dev;

    SysBusDevice *busdev;

    MemoryRegion *address_space_mem = get_system_memory();

    PCIBus *pci_bus;

    if (cpu_model == NULL) {

        cpu_model = "SH7751R";

    }

    cpu = cpu_sh4_init(cpu_model);

    if (cpu == NULL) {

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

        exit(1);

    }

    env = &cpu->env;

    reset_info = g_malloc0(sizeof(ResetData));

    reset_info->cpu = cpu;

    reset_info->vector = env->pc;

    qemu_register_reset(main_cpu_reset, reset_info);

    /* Allocate memory space */

    memory_region_init_ram(sdram, NULL, "r2d.sdram", SDRAM_SIZE, &error_abort);

    vmstate_register_ram_global(sdram);

    memory_region_add_subregion(address_space_mem, SDRAM_BASE, sdram);

    /* Register peripherals */

    s = sh7750_init(cpu, address_space_mem);

    irq = r2d_fpga_init(address_space_mem, 0x04000000, sh7750_irl(s));

    dev = qdev_create(NULL, "sh_pci");

    busdev = SYS_BUS_DEVICE(dev);

    qdev_init_nofail(dev);

    pci_bus = PCI_BUS(qdev_get_child_bus(dev, "pci"));

    sysbus_mmio_map(busdev, 0, P4ADDR(0x1e200000));

    sysbus_mmio_map(busdev, 1, A7ADDR(0x1e200000));

    sysbus_connect_irq(busdev, 0, irq[PCI_INTA]);

    sysbus_connect_irq(busdev, 1, irq[PCI_INTB]);

    sysbus_connect_irq(busdev, 2, irq[PCI_INTC]);

    sysbus_connect_irq(busdev, 3, irq[PCI_INTD]);

    sm501_init(address_space_mem, 0x10000000, SM501_VRAM_SIZE,

               irq[SM501], serial_hds[2]);

    /* onboard CF (True IDE mode, Master only). */

    dinfo = drive_get(IF_IDE, 0, 0);

    dev = qdev_create(NULL, "mmio-ide");

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_connect_irq(busdev, 0, irq[CF_IDE]);

    qdev_prop_set_uint32(dev, "shift", 1);

    qdev_init_nofail(dev);

    sysbus_mmio_map(busdev, 0, 0x14001000);

    sysbus_mmio_map(busdev, 1, 0x1400080c);

    mmio_ide_init_drives(dev, dinfo, NULL);

    /* onboard flash memory */

    dinfo = drive_get(IF_PFLASH, 0, 0);

    pflash_cfi02_register(0x0, NULL, "r2d.flash", FLASH_SIZE,

                          dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL,

                          (16 * 1024), FLASH_SIZE >> 16,

                          1, 4, 0x0000, 0x0000, 0x0000, 0x0000,

                          0x555, 0x2aa, 0);

    /* NIC: rtl8139 on-board, and 2 slots. */

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

        pci_nic_init_nofail(&nd_table[i], pci_bus,

                            "rtl8139", i==0 ? "2" : NULL);

    /* USB keyboard */

    usbdevice_create("keyboard");

    /* Todo: register on board registers */

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

    if (kernel_filename) {

        int kernel_size;

        kernel_size = load_image_targphys(kernel_filename,

                                          SDRAM_BASE + LINUX_LOAD_OFFSET,

                                          INITRD_LOAD_OFFSET - LINUX_LOAD_OFFSET);

        if (kernel_size < 0) {

          fprintf(stderr, "qemu: could not load kernel '%s'\n", kernel_filename);

          exit(1);

        }

        /* initialization which should be done by firmware */

        stl_phys(&address_space_memory, SH7750_BCR1, 1<<3); /* cs3 SDRAM */

        stw_phys(&address_space_memory, SH7750_BCR2, 3<<(3*2)); /* cs3 32bit */

        reset_info->vector = (SDRAM_BASE + LINUX_LOAD_OFFSET) | 0xa0000000; /* Start from P2 area */

    }

    if (initrd_filename) {

        int initrd_size;

        initrd_size = load_image_targphys(initrd_filename,

                                          SDRAM_BASE + INITRD_LOAD_OFFSET,

                                          SDRAM_SIZE - INITRD_LOAD_OFFSET);

        if (initrd_size < 0) {

          fprintf(stderr, "qemu: could not load initrd '%s'\n", initrd_filename);

          exit(1);

        }

        /* initialization which should be done by firmware */

        boot_params.loader_type = 1;

        boot_params.initrd_start = INITRD_LOAD_OFFSET;

        boot_params.initrd_size = initrd_size;

    }

    if (kernel_cmdline) {

        /* I see no evidence that this .kernel_cmdline buffer requires

           NUL-termination, so using strncpy should be ok. */

        strncpy(boot_params.kernel_cmdline, kernel_cmdline,

                sizeof(boot_params.kernel_cmdline));

    }

    rom_add_blob_fixed("boot_params", &boot_params, sizeof(boot_params),

                       SDRAM_BASE + BOOT_PARAMS_OFFSET);

}


static void gen_compute_eflags_s(DisasContext *s, TCGv reg, bool inv)

{

    switch (s->cc_op) {

    case CC_OP_DYNAMIC:

        gen_compute_eflags(s);

        /* FALLTHRU */

    case CC_OP_EFLAGS:

        tcg_gen_shri_tl(reg, cpu_cc_src, 7);

        tcg_gen_andi_tl(reg, reg, 1);

        if (inv) {

            tcg_gen_xori_tl(reg, reg, 1);

        }

        break;

    default:

        {

            int size = (s->cc_op - CC_OP_ADDB) & 3;

            TCGv t0 = gen_ext_tl(reg, cpu_cc_dst, size, true);

            tcg_gen_setcondi_tl(inv ? TCG_COND_GE : TCG_COND_LT, reg, t0, 0);

        }

        break;

    }

}


static void gen_compute_eflags_z(DisasContext *s, TCGv reg, bool inv)

{

    switch (s->cc_op) {

    case CC_OP_DYNAMIC:

        gen_compute_eflags(s);

        /* FALLTHRU */

    case CC_OP_EFLAGS:

        tcg_gen_shri_tl(reg, cpu_cc_src, 6);

        tcg_gen_andi_tl(reg, reg, 1);

        if (inv) {

            tcg_gen_xori_tl(reg, reg, 1);

        }

        break;

    default:

        {

            int size = (s->cc_op - CC_OP_ADDB) & 3;

            TCGv t0 = gen_ext_tl(reg, cpu_cc_dst, size, false);

            tcg_gen_setcondi_tl(inv ? TCG_COND_NE : TCG_COND_EQ, reg, t0, 0);

        }

        break;

    }

}


uint32_t omap_badwidth_read16(void *opaque, target_phys_addr_t addr)

{

    uint16_t ret;

    OMAP_16B_REG(addr);

    cpu_physical_memory_read(addr, (void *) &ret, 2);

    return ret;

}


void nelly_decode_block(NellyMoserDecodeContext *s, unsigned char block[NELLY_BLOCK_LEN], float audio[NELLY_SAMPLES])

{

    int i,j;

    float buf[NELLY_FILL_LEN], pows[NELLY_FILL_LEN];

    float *aptr, *bptr, *pptr, val, pval;

    int bits[NELLY_BUF_LEN];

    unsigned char v;

    init_get_bits(&s->gb, block, NELLY_BLOCK_LEN * 8);

    bptr = buf;

    pptr = pows;

    val = nelly_init_table[get_bits(&s->gb, 6)];

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

        if (i > 0)

            val += nelly_delta_table[get_bits(&s->gb, 5)];

        pval = pow(2, val/2048);

        for (j = 0; j < nelly_band_sizes_table[i]; j++) {

            *bptr++ = val;

            *pptr++ = pval;

        }

    }

    get_sample_bits(buf, bits);

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

        aptr = audio + i * NELLY_BUF_LEN;

        init_get_bits(&s->gb, block, NELLY_BLOCK_LEN * 8);

        skip_bits(&s->gb, NELLY_HEADER_BITS + i*NELLY_DETAIL_BITS);

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

            if (bits[j] <= 0) {

                aptr[j] = M_SQRT1_2*pows[j];

                if (av_random(&s->random_state) & 1)

                    aptr[j] *= -1.0;

            } else {

                v = get_bits(&s->gb, bits[j]);

                aptr[j] = dequantization_table[(1<<bits[j])-1+v]*pows[j];

            }

        }

        memset(&aptr[NELLY_FILL_LEN], 0,

               (NELLY_BUF_LEN - NELLY_FILL_LEN) * sizeof(float));

        s->imdct_ctx.fft.imdct_calc(&s->imdct_ctx, s->imdct_out,

                                    aptr, s->imdct_tmp);

        /* XXX: overlapping and windowing should be part of a more

           generic imdct function */

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

            aptr[j] = s->imdct_out[j + NELLY_BUF_LEN + NELLY_BUF_LEN / 2];

            aptr[j + NELLY_BUF_LEN / 2] = s->imdct_out[j];

        }

        overlap_and_window(s, s->state, aptr);

    }

}


AioContext *qemu_get_aio_context(void)

{

    return qemu_aio_context;

}


void bios_linker_loader_add_checksum(GArray *linker, const char *file,

                                     void *table,

                                     void *start, unsigned size,

                                     uint8_t *checksum)

{

    BiosLinkerLoaderEntry entry;

    memset(&entry, 0, sizeof entry);

    strncpy(entry.cksum.file, file, sizeof entry.cksum.file - 1);

    entry.command = cpu_to_le32(BIOS_LINKER_LOADER_COMMAND_ADD_CHECKSUM);

    entry.cksum.offset = cpu_to_le32(checksum - (uint8_t *)table);

    entry.cksum.start = cpu_to_le32((uint8_t *)start - (uint8_t *)table);

    entry.cksum.length = cpu_to_le32(size);

    g_array_append_val(linker, entry);

}


void build_legacy_cpu_hotplug_aml(Aml *ctx, MachineState *machine,

                                  uint16_t io_base, uint16_t io_len)

{

    Aml *dev;

    Aml *crs;

    Aml *pkg;

    Aml *field;

    Aml *method;

    Aml *if_ctx;

    Aml *else_ctx;

    int i, apic_idx;

    Aml *sb_scope = aml_scope("_SB");

    uint8_t madt_tmpl[8] = {0x00, 0x08, 0x00, 0x00, 0x00, 0, 0, 0};

    Aml *cpu_id = aml_arg(0);

    Aml *cpu_on = aml_local(0);

    Aml *madt = aml_local(1);

    Aml *cpus_map = aml_name(CPU_ON_BITMAP);

    Aml *zero = aml_int(0);

    Aml *one = aml_int(1);

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(machine);

    PCMachineState *pcms = PC_MACHINE(machine);

    /*

     * _MAT method - creates an madt apic buffer

     * cpu_id = Arg0 = Processor ID = Local APIC ID

     * cpu_on = Local0 = CPON flag for this cpu

     * madt = Local1 = Buffer (in madt apic form) to return

     */

    method = aml_method(CPU_MAT_METHOD, 1, AML_NOTSERIALIZED);

    aml_append(method,

        aml_store(aml_derefof(aml_index(cpus_map, cpu_id)), cpu_on));

    aml_append(method,

        aml_store(aml_buffer(sizeof(madt_tmpl), madt_tmpl), madt));

    /* Update the processor id, lapic id, and enable/disable status */

    aml_append(method, aml_store(cpu_id, aml_index(madt, aml_int(2))));

    aml_append(method, aml_store(cpu_id, aml_index(madt, aml_int(3))));

    aml_append(method, aml_store(cpu_on, aml_index(madt, aml_int(4))));

    aml_append(method, aml_return(madt));

    aml_append(sb_scope, method);

    /*

     * _STA method - return ON status of cpu

     * cpu_id = Arg0 = Processor ID = Local APIC ID

     * cpu_on = Local0 = CPON flag for this cpu

     */

    method = aml_method(CPU_STATUS_METHOD, 1, AML_NOTSERIALIZED);

    aml_append(method,

        aml_store(aml_derefof(aml_index(cpus_map, cpu_id)), cpu_on));

    if_ctx = aml_if(cpu_on);

    {

        aml_append(if_ctx, aml_return(aml_int(0xF)));

    }

    aml_append(method, if_ctx);

    else_ctx = aml_else();

    {

        aml_append(else_ctx, aml_return(zero));

    }

    aml_append(method, else_ctx);

    aml_append(sb_scope, method);

    method = aml_method(CPU_EJECT_METHOD, 2, AML_NOTSERIALIZED);

    aml_append(method, aml_sleep(200));

    aml_append(sb_scope, method);

    method = aml_method(CPU_SCAN_METHOD, 0, AML_NOTSERIALIZED);

    {

        Aml *while_ctx, *if_ctx2, *else_ctx2;

        Aml *bus_check_evt = aml_int(1);

        Aml *remove_evt = aml_int(3);

        Aml *status_map = aml_local(5); /* Local5 = active cpu bitmap */

        Aml *byte = aml_local(2); /* Local2 = last read byte from bitmap */

        Aml *idx = aml_local(0); /* Processor ID / APIC ID iterator */

        Aml *is_cpu_on = aml_local(1); /* Local1 = CPON flag for cpu */

        Aml *status = aml_local(3); /* Local3 = active state for cpu */

        aml_append(method, aml_store(aml_name(CPU_STATUS_MAP), status_map));

        aml_append(method, aml_store(zero, byte));

        aml_append(method, aml_store(zero, idx));

        /* While (idx < SizeOf(CPON)) */

        while_ctx = aml_while(aml_lless(idx, aml_sizeof(cpus_map)));

        aml_append(while_ctx,

            aml_store(aml_derefof(aml_index(cpus_map, idx)), is_cpu_on));

        if_ctx = aml_if(aml_and(idx, aml_int(0x07), NULL));

        {

            /* Shift down previously read bitmap byte */

            aml_append(if_ctx, aml_shiftright(byte, one, byte));

        }

        aml_append(while_ctx, if_ctx);

        else_ctx = aml_else();

        {

            /* Read next byte from cpu bitmap */

            aml_append(else_ctx, aml_store(aml_derefof(aml_index(status_map,

                       aml_shiftright(idx, aml_int(3), NULL))), byte));

        }

        aml_append(while_ctx, else_ctx);

        aml_append(while_ctx, aml_store(aml_and(byte, one, NULL), status));

        if_ctx = aml_if(aml_lnot(aml_equal(is_cpu_on, status)));

        {

            /* State change - update CPON with new state */

            aml_append(if_ctx, aml_store(status, aml_index(cpus_map, idx)));

            if_ctx2 = aml_if(aml_equal(status, one));

            {

                aml_append(if_ctx2,

                    aml_call2(AML_NOTIFY_METHOD, idx, bus_check_evt));

            }

            aml_append(if_ctx, if_ctx2);

            else_ctx2 = aml_else();

            {

                aml_append(else_ctx2,

                    aml_call2(AML_NOTIFY_METHOD, idx, remove_evt));

            }

        }

        aml_append(if_ctx, else_ctx2);

        aml_append(while_ctx, if_ctx);

        aml_append(while_ctx, aml_increment(idx)); /* go to next cpu */

        aml_append(method, while_ctx);

    }

    aml_append(sb_scope, method);

    /* The current AML generator can cover the APIC ID range [0..255],

     * inclusive, for VCPU hotplug. */

    QEMU_BUILD_BUG_ON(ACPI_CPU_HOTPLUG_ID_LIMIT > 256);

    g_assert(pcms->apic_id_limit <= ACPI_CPU_HOTPLUG_ID_LIMIT);

    /* create PCI0.PRES device and its _CRS to reserve CPU hotplug MMIO */

    dev = aml_device("PCI0." stringify(CPU_HOTPLUG_RESOURCE_DEVICE));

    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A06")));

    aml_append(dev,

        aml_name_decl("_UID", aml_string("CPU Hotplug resources"))

    );

    /* device present, functioning, decoding, not shown in UI */

    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

    crs = aml_resource_template();

    aml_append(crs,

        aml_io(AML_DECODE16, io_base, io_base, 1, io_len)

    );

    aml_append(dev, aml_name_decl("_CRS", crs));

    aml_append(sb_scope, dev);

    /* declare CPU hotplug MMIO region and PRS field to access it */

    aml_append(sb_scope, aml_operation_region(

        "PRST", AML_SYSTEM_IO, aml_int(io_base), io_len));

    field = aml_field("PRST", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);

    aml_append(field, aml_named_field("PRS", 256));

    aml_append(sb_scope, field);

    /* build Processor object for each processor */

    for (i = 0; i < apic_ids->len; i++) {

        int apic_id = apic_ids->cpus[i].arch_id;

        assert(apic_id < ACPI_CPU_HOTPLUG_ID_LIMIT);

        dev = aml_processor(apic_id, 0, 0, "CP%.02X", apic_id);

        method = aml_method("_MAT", 0, AML_NOTSERIALIZED);

        aml_append(method,

            aml_return(aml_call1(CPU_MAT_METHOD, aml_int(apic_id))));

        aml_append(dev, method);

        method = aml_method("_STA", 0, AML_NOTSERIALIZED);

        aml_append(method,

            aml_return(aml_call1(CPU_STATUS_METHOD, aml_int(apic_id))));

        aml_append(dev, method);

        method = aml_method("_EJ0", 1, AML_NOTSERIALIZED);

        aml_append(method,

            aml_return(aml_call2(CPU_EJECT_METHOD, aml_int(apic_id),

                aml_arg(0)))

        );

        aml_append(dev, method);

        aml_append(sb_scope, dev);

    }

    /* build this code:

     *   Method(NTFY, 2) {If (LEqual(Arg0, 0x00)) {Notify(CP00, Arg1)} ...}

     */

    /* Arg0 = Processor ID = APIC ID */

    method = aml_method(AML_NOTIFY_METHOD, 2, AML_NOTSERIALIZED);

    for (i = 0; i < apic_ids->len; i++) {

        int apic_id = apic_ids->cpus[i].arch_id;

        if_ctx = aml_if(aml_equal(aml_arg(0), aml_int(apic_id)));

        aml_append(if_ctx,

            aml_notify(aml_name("CP%.02X", apic_id), aml_arg(1))

        );

        aml_append(method, if_ctx);

    }

    aml_append(sb_scope, method);

    /* build "Name(CPON, Package() { One, One, ..., Zero, Zero, ... })"

     *

     * Note: The ability to create variable-sized packages was first

     * introduced in ACPI 2.0. ACPI 1.0 only allowed fixed-size packages

     * ith up to 255 elements. Windows guests up to win2k8 fail when

     * VarPackageOp is used.

     */

    pkg = pcms->apic_id_limit <= 255 ? aml_package(pcms->apic_id_limit) :

                                       aml_varpackage(pcms->apic_id_limit);

    for (i = 0, apic_idx = 0; i < apic_ids->len; i++) {

        int apic_id = apic_ids->cpus[i].arch_id;

        for (; apic_idx < apic_id; apic_idx++) {

            aml_append(pkg, aml_int(0));

        }

        aml_append(pkg, aml_int(apic_ids->cpus[i].cpu ? 1 : 0));

        apic_idx = apic_id + 1;

    }

    aml_append(sb_scope, aml_name_decl(CPU_ON_BITMAP, pkg));

    g_free(apic_ids);

    aml_append(ctx, sb_scope);

    method = aml_method("\\_GPE._E02", 0, AML_NOTSERIALIZED);

    aml_append(method, aml_call0("\\_SB." CPU_SCAN_METHOD));

    aml_append(ctx, method);

}


static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop)

{

    cirrus_fill_t rop_func;

    if (blit_is_unsafe(s, true)) {

        return 0;

    }

    rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];

    rop_func(s, s->vga.vram_ptr + s->cirrus_blt_dstaddr,

             s->cirrus_blt_dstpitch,

             s->cirrus_blt_width, s->cirrus_blt_height);

    cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,

			     s->cirrus_blt_dstpitch, s->cirrus_blt_width,

			     s->cirrus_blt_height);

    cirrus_bitblt_reset(s);

    return 1;

}


void OPPROTO op_addw_EDI_T0(void)

{

    EDI = (EDI & ~0xffff) | ((EDI + T0) & 0xffff);

}


uint64_t helper_fdiv (uint64_t arg1, uint64_t arg2)

{

    CPU_DoubleU farg1, farg2;

    farg1.ll = arg1;

    farg2.ll = arg2;

#if USE_PRECISE_EMULATION

    if (unlikely(float64_is_signaling_nan(farg1.d) ||

                 float64_is_signaling_nan(farg2.d))) {

        /* sNaN division */

        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);

    } else if (unlikely(float64_is_infinity(farg1.d) && float64_is_infinity(farg2.d))) {

        /* Division of infinity by infinity */

        farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXIDI);

    } else if (unlikely(!float64_is_nan(farg1.d) && float64_is_zero(farg2.d))) {

        if (float64_is_zero(farg1.d)) {

            /* Division of zero by zero */

            farg1.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXZDZ);

        } else {

            /* Division by zero */

            farg1.ll = float_zero_divide_excp(farg1.d, farg2.d);

        }

    } else {

        farg1.d = float64_div(farg1.d, farg2.d, &env->fp_status);

    }

#else

    farg1.d = float64_div(farg1.d, farg2.d, &env->fp_status);

#endif

    return farg1.ll;

}


void gen_intermediate_code(CPUARMState *env, TranslationBlock *tb)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    DisasContext dc1, *dc = &dc1;

    target_ulong pc_start;

    target_ulong next_page_start;

    int num_insns;

    int max_insns;

    bool end_of_page;

    /* generate intermediate code */

    /* The A64 decoder has its own top level loop, because it doesn't need

     * the A32/T32 complexity to do with conditional execution/IT blocks/etc.

     */

    if (ARM_TBFLAG_AARCH64_STATE(tb->flags)) {

        gen_intermediate_code_a64(cpu, tb);

        return;

    }

    pc_start = tb->pc;

    dc->tb = tb;

    dc->is_jmp = DISAS_NEXT;

    dc->pc = pc_start;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->condjmp = 0;

    dc->aarch64 = 0;

    /* If we are coming from secure EL0 in a system with a 32-bit EL3, then

     * there is no secure EL1, so we route exceptions to EL3.

     */

    dc->secure_routed_to_el3 = arm_feature(env, ARM_FEATURE_EL3) &&

                               !arm_el_is_aa64(env, 3);

    dc->thumb = ARM_TBFLAG_THUMB(tb->flags);

    dc->sctlr_b = ARM_TBFLAG_SCTLR_B(tb->flags);

    dc->be_data = ARM_TBFLAG_BE_DATA(tb->flags) ? MO_BE : MO_LE;

    dc->condexec_mask = (ARM_TBFLAG_CONDEXEC(tb->flags) & 0xf) << 1;

    dc->condexec_cond = ARM_TBFLAG_CONDEXEC(tb->flags) >> 4;

    dc->mmu_idx = ARM_TBFLAG_MMUIDX(tb->flags);

    dc->current_el = arm_mmu_idx_to_el(dc->mmu_idx);

#if !defined(CONFIG_USER_ONLY)

    dc->user = (dc->current_el == 0);

#endif

    dc->ns = ARM_TBFLAG_NS(tb->flags);

    dc->fp_excp_el = ARM_TBFLAG_FPEXC_EL(tb->flags);

    dc->vfp_enabled = ARM_TBFLAG_VFPEN(tb->flags);

    dc->vec_len = ARM_TBFLAG_VECLEN(tb->flags);

    dc->vec_stride = ARM_TBFLAG_VECSTRIDE(tb->flags);

    dc->c15_cpar = ARM_TBFLAG_XSCALE_CPAR(tb->flags);

    dc->cp_regs = cpu->cp_regs;

    dc->features = env->features;

    /* Single step state. The code-generation logic here is:

     *  SS_ACTIVE == 0:

     *   generate code with no special handling for single-stepping (except

     *   that anything that can make us go to SS_ACTIVE == 1 must end the TB;

     *   this happens anyway because those changes are all system register or

     *   PSTATE writes).

     *  SS_ACTIVE == 1, PSTATE.SS == 1: (active-not-pending)

     *   emit code for one insn

     *   emit code to clear PSTATE.SS

     *   emit code to generate software step exception for completed step

     *   end TB (as usual for having generated an exception)

     *  SS_ACTIVE == 1, PSTATE.SS == 0: (active-pending)

     *   emit code to generate a software step exception

     *   end the TB

     */

    dc->ss_active = ARM_TBFLAG_SS_ACTIVE(tb->flags);

    dc->pstate_ss = ARM_TBFLAG_PSTATE_SS(tb->flags);

    dc->is_ldex = false;

    dc->ss_same_el = false; /* Can't be true since EL_d must be AArch64 */

    cpu_F0s = tcg_temp_new_i32();

    cpu_F1s = tcg_temp_new_i32();

    cpu_F0d = tcg_temp_new_i64();

    cpu_F1d = tcg_temp_new_i64();

    cpu_V0 = cpu_F0d;

    cpu_V1 = cpu_F1d;

    /* FIXME: cpu_M0 can probably be the same as cpu_V0.  */

    cpu_M0 = tcg_temp_new_i64();

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    if (max_insns > TCG_MAX_INSNS) {

        max_insns = TCG_MAX_INSNS;

    }

    gen_tb_start(tb);

    tcg_clear_temp_count();

    /* A note on handling of the condexec (IT) bits:

     *

     * We want to avoid the overhead of having to write the updated condexec

     * bits back to the CPUARMState for every instruction in an IT block. So:

     * (1) if the condexec bits are not already zero then we write

     * zero back into the CPUARMState now. This avoids complications trying

     * to do it at the end of the block. (For example if we don't do this

     * it's hard to identify whether we can safely skip writing condexec

     * at the end of the TB, which we definitely want to do for the case

     * where a TB doesn't do anything with the IT state at all.)

     * (2) if we are going to leave the TB then we call gen_set_condexec()

     * which will write the correct value into CPUARMState if zero is wrong.

     * This is done both for leaving the TB at the end, and for leaving

     * it because of an exception we know will happen, which is done in

     * gen_exception_insn(). The latter is necessary because we need to

     * leave the TB with the PC/IT state just prior to execution of the

     * instruction which caused the exception.

     * (3) if we leave the TB unexpectedly (eg a data abort on a load)

     * then the CPUARMState will be wrong and we need to reset it.

     * This is handled in the same way as restoration of the

     * PC in these situations; we save the value of the condexec bits

     * for each PC via tcg_gen_insn_start(), and restore_state_to_opc()

     * then uses this to restore them after an exception.

     *

     * Note that there are no instructions which can read the condexec

     * bits, and none which can write non-static values to them, so

     * we don't need to care about whether CPUARMState is correct in the

     * middle of a TB.

     */

    /* Reset the conditional execution bits immediately. This avoids

       complications trying to do it at the end of the block.  */

    if (dc->condexec_mask || dc->condexec_cond)

      {

        TCGv_i32 tmp = tcg_temp_new_i32();

        tcg_gen_movi_i32(tmp, 0);

        store_cpu_field(tmp, condexec_bits);

      }

    do {

        dc->insn_start_idx = tcg_op_buf_count();

        tcg_gen_insn_start(dc->pc,

                           (dc->condexec_cond << 4) | (dc->condexec_mask >> 1),

                           0);

        num_insns++;

#ifdef CONFIG_USER_ONLY

        /* Intercept jump to the magic kernel page.  */

        if (dc->pc >= 0xffff0000) {

            /* We always get here via a jump, so know we are not in a

               conditional execution block.  */

            gen_exception_internal(EXCP_KERNEL_TRAP);

            dc->is_jmp = DISAS_EXC;

            break;

        }

#else

        if (arm_dc_feature(dc, ARM_FEATURE_M)) {

            /* Branches to the magic exception-return addresses should

             * already have been caught via the arm_v7m_unassigned_access hook,

             * and never get here.

             */

            assert(dc->pc < 0xfffffff0);

        }

#endif

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

            CPUBreakpoint *bp;

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

                if (bp->pc == dc->pc) {

                    if (bp->flags & BP_CPU) {

                        gen_set_condexec(dc);

                        gen_set_pc_im(dc, dc->pc);

                        gen_helper_check_breakpoints(cpu_env);

                        /* End the TB early; it's likely not going to be executed */

                        dc->is_jmp = DISAS_UPDATE;

                    } else {

                        gen_exception_internal_insn(dc, 0, EXCP_DEBUG);

                        /* The address covered by the breakpoint must be

                           included in [tb->pc, tb->pc + tb->size) in order

                           to for it to be properly cleared -- thus we

                           increment the PC here so that the logic setting

                           tb->size below does the right thing.  */

                        /* TODO: Advance PC by correct instruction length to

                         * avoid disassembler error messages */

                        dc->pc += 2;

                        goto done_generating;

                    }

                    break;

                }

            }

        }

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

            gen_io_start();

        }

        if (dc->ss_active && !dc->pstate_ss) {

            /* Singlestep state is Active-pending.

             * If we're in this state at the start of a TB then either

             *  a) we just took an exception to an EL which is being debugged

             *     and this is the first insn in the exception handler

             *  b) debug exceptions were masked and we just unmasked them

             *     without changing EL (eg by clearing PSTATE.D)

             * In either case we're going to take a swstep exception in the

             * "did not step an insn" case, and so the syndrome ISV and EX

             * bits should be zero.

             */

            assert(num_insns == 1);

            gen_exception(EXCP_UDEF, syn_swstep(dc->ss_same_el, 0, 0),

                          default_exception_el(dc));

            goto done_generating;

        }

        if (dc->thumb) {

            disas_thumb_insn(env, dc);

            if (dc->condexec_mask) {

                dc->condexec_cond = (dc->condexec_cond & 0xe)

                                   | ((dc->condexec_mask >> 4) & 1);

                dc->condexec_mask = (dc->condexec_mask << 1) & 0x1f;

                if (dc->condexec_mask == 0) {

                    dc->condexec_cond = 0;

                }

            }

        } else {

            unsigned int insn = arm_ldl_code(env, dc->pc, dc->sctlr_b);

            dc->pc += 4;

            disas_arm_insn(dc, insn);

        }

        if (dc->condjmp && !dc->is_jmp) {

            gen_set_label(dc->condlabel);

            dc->condjmp = 0;

        }

        if (tcg_check_temp_count()) {

            fprintf(stderr, "TCG temporary leak before "TARGET_FMT_lx"\n",

                    dc->pc);

        }

        /* Translation stops when a conditional branch is encountered.

         * Otherwise the subsequent code could get translated several times.

         * Also stop translation when a page boundary is reached.  This

         * ensures prefetch aborts occur at the right place.  */

        /* We want to stop the TB if the next insn starts in a new page,

         * or if it spans between this page and the next. This means that

         * if we're looking at the last halfword in the page we need to

         * see if it's a 16-bit Thumb insn (which will fit in this TB)

         * or a 32-bit Thumb insn (which won't).

         * This is to avoid generating a silly TB with a single 16-bit insn

         * in it at the end of this page (which would execute correctly

         * but isn't very efficient).

         */

        end_of_page = (dc->pc >= next_page_start) ||

            ((dc->pc >= next_page_start - 3) && insn_crosses_page(env, dc));

    } while (!dc->is_jmp && !tcg_op_buf_full() &&

             !is_singlestepping(dc) &&

             !singlestep &&

             !end_of_page &&

             num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        if (dc->condjmp) {

            /* FIXME:  This can theoretically happen with self-modifying

               code.  */

            cpu_abort(cs, "IO on conditional branch instruction");

        }

        gen_io_end();

    }

    /* At this stage dc->condjmp will only be set when the skipped

       instruction was a conditional branch or trap, and the PC has

       already been written.  */

    gen_set_condexec(dc);

    if (unlikely(is_singlestepping(dc))) {

        /* Unconditional and "condition passed" instruction codepath. */

        switch (dc->is_jmp) {

        case DISAS_SWI:

            gen_ss_advance(dc);

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

            break;

        case DISAS_HVC:

            gen_ss_advance(dc);

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            break;

        case DISAS_SMC:

            gen_ss_advance(dc);

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            break;

        case DISAS_NEXT:

        case DISAS_UPDATE:

            gen_set_pc_im(dc, dc->pc);

            /* fall through */

        default:

            /* FIXME: Single stepping a WFI insn will not halt the CPU. */

            gen_singlestep_exception(dc);

        }

    } else {

        /* While branches must always occur at the end of an IT block,

           there are a few other things that can cause us to terminate

           the TB in the middle of an IT block:

            - Exception generating instructions (bkpt, swi, undefined).

            - Page boundaries.

            - Hardware watchpoints.

           Hardware breakpoints have already been handled and skip this code.

         */

        switch(dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, dc->pc);

            break;

        case DISAS_UPDATE:

            gen_set_pc_im(dc, dc->pc);

            /* fall through */

        case DISAS_JUMP:

        default:

            /* indicate that the hash table must be used to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        case DISAS_WFI:

            gen_helper_wfi(cpu_env);

            /* The helper doesn't necessarily throw an exception, but we

             * must go back to the main loop to check for interrupts anyway.

             */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_WFE:

            gen_helper_wfe(cpu_env);

            break;

        case DISAS_YIELD:

            gen_helper_yield(cpu_env);

            break;

        case DISAS_SWI:

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

            break;

        case DISAS_HVC:

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            break;

        case DISAS_SMC:

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            break;

        }

    }

    if (dc->condjmp) {

        /* "Condition failed" instruction codepath for the branch/trap insn */

        gen_set_label(dc->condlabel);

        gen_set_condexec(dc);

        if (unlikely(is_singlestepping(dc))) {

            gen_set_pc_im(dc, dc->pc);

            gen_singlestep_exception(dc);

        } else {

            gen_goto_tb(dc, 1, dc->pc);

        }

    }

done_generating:

    gen_tb_end(tb, num_insns);

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM) &&

        qemu_log_in_addr_range(pc_start)) {

        qemu_log_lock();

        qemu_log("----------------\n");

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(cs, pc_start, dc->pc - pc_start,

                         dc->thumb | (dc->sctlr_b << 1));

        qemu_log("\n");

        qemu_log_unlock();

    }

#endif

    tb->size = dc->pc - pc_start;

    tb->icount = num_insns;

}


NEON_TYPE4(s8, int8_t)
NEON_TYPE4(u8, uint8_t)
NEON_TYPE2(s16, int16_t)
NEON_TYPE2(u16, uint16_t)
NEON_TYPE1(s32, int32_t)
NEON_TYPE1(u32, uint32_t)
#undef NEON_TYPE4
#undef NEON_TYPE2
#undef NEON_TYPE1
/* Copy from a uint32_t to a vector structure type.  */
#define NEON_UNPACK(vtype, dest, val) do { \
    union { \
        vtype v; \
        uint32_t i; \
    } conv_u; \
    conv_u.i = (val); \
    dest = conv_u.v; \
    } while(0)
/* Copy from a vector structure type to a uint32_t.  */
#define NEON_PACK(vtype, dest, val) do { \
    union { \
        vtype v; \
        uint32_t i; \
    } conv_u; \
    conv_u.v = (val); \
    dest = conv_u.i; \
    } while(0)
#define NEON_DO1 \
    NEON_FN(vdest.v1, vsrc1.v1, vsrc2.v1);
#define NEON_DO2 \
    NEON_FN(vdest.v1, vsrc1.v1, vsrc2.v1); \
    NEON_FN(vdest.v2, vsrc1.v2, vsrc2.v2);
#define NEON_DO4 \
    NEON_FN(vdest.v1, vsrc1.v1, vsrc2.v1); \
    NEON_FN(vdest.v2, vsrc1.v2, vsrc2.v2); \
    NEON_FN(vdest.v3, vsrc1.v3, vsrc2.v3); \
    NEON_FN(vdest.v4, vsrc1.v4, vsrc2.v4);
#define NEON_VOP_BODY(vtype, n) \
{ \
    uint32_t res; \
    vtype vsrc1; \
    vtype vsrc2; \
    vtype vdest; \
    NEON_UNPACK(vtype, vsrc1, arg1); \
    NEON_UNPACK(vtype, vsrc2, arg2); \
    NEON_DO##n; \
    NEON_PACK(vtype, res, vdest); \
    return res; \
#define NEON_VOP(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(uint32_t arg1, uint32_t arg2) \
NEON_VOP_BODY(vtype, n)
#define NEON_VOP_ENV(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(CPUState *env, uint32_t arg1, uint32_t arg2) \
NEON_VOP_BODY(vtype, n)
/* Pairwise operations.  */
/* For 32-bit elements each segment only contains a single element, so
   the elementwise and pairwise operations are the same.  */
#define NEON_PDO2 \
    NEON_FN(vdest.v1, vsrc1.v1, vsrc1.v2); \
    NEON_FN(vdest.v2, vsrc2.v1, vsrc2.v2);
#define NEON_PDO4 \
    NEON_FN(vdest.v1, vsrc1.v1, vsrc1.v2); \
    NEON_FN(vdest.v2, vsrc1.v3, vsrc1.v4); \
    NEON_FN(vdest.v3, vsrc2.v1, vsrc2.v2); \
    NEON_FN(vdest.v4, vsrc2.v3, vsrc2.v4); \
#define NEON_POP(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(uint32_t arg1, uint32_t arg2) \
{ \
    uint32_t res; \
    vtype vsrc1; \
    vtype vsrc2; \
    vtype vdest; \
    NEON_UNPACK(vtype, vsrc1, arg1); \
    NEON_UNPACK(vtype, vsrc2, arg2); \
    NEON_PDO##n; \
    NEON_PACK(vtype, res, vdest); \
    return res; \
/* Unary operators.  */
#define NEON_VOP1(name, vtype, n) \
uint32_t HELPER(glue(neon_,name))(uint32_t arg) \
{ \
    vtype vsrc1; \
    vtype vdest; \
    NEON_UNPACK(vtype, vsrc1, arg); \
    NEON_DO##n; \
    NEON_PACK(vtype, arg, vdest); \
    return arg; \
#define NEON_USAT(dest, src1, src2, type) do { \
    uint32_t tmp = (uint32_t)src1 + (uint32_t)src2; \
    if (tmp != (type)tmp) { \
        SET_QC(); \
        dest = ~0; \
    } else { \
        dest = tmp; \
    }} while(0)
#define NEON_FN(dest, src1, src2) NEON_USAT(dest, src1, src2, uint8_t)
NEON_VOP_ENV(qadd_u8, neon_u8, 4)
#undef NEON_FN
#define NEON_FN(dest, src1, src2) NEON_USAT(dest, src1, src2, uint16_t)
NEON_VOP_ENV(qadd_u16, neon_u16, 2)
#undef NEON_FN
#undef NEON_USAT


static int vmdk_create_extent(const char *filename, int64_t filesize,

                              bool flat, bool compress, bool zeroed_grain,

                              Error **errp)

{

    int ret, i;

    BlockDriverState *bs = NULL;

    VMDK4Header header;

    Error *local_err;

    uint32_t tmp, magic, grains, gd_sectors, gt_size, gt_count;

    uint32_t *gd_buf = NULL;

    int gd_buf_size;

    ret = bdrv_create_file(filename, NULL, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

    ret = bdrv_file_open(&bs, filename, NULL, NULL, BDRV_O_RDWR, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

    if (flat) {

        ret = bdrv_truncate(bs, filesize);

        if (ret < 0) {

            error_setg(errp, "Could not truncate file");

        }

        goto exit;

    }

    magic = cpu_to_be32(VMDK4_MAGIC);

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

    header.version = zeroed_grain ? 2 : 1;

    header.flags = VMDK4_FLAG_RGD | VMDK4_FLAG_NL_DETECT

                   | (compress ? VMDK4_FLAG_COMPRESS | VMDK4_FLAG_MARKER : 0)

                   | (zeroed_grain ? VMDK4_FLAG_ZERO_GRAIN : 0);

    header.compressAlgorithm = compress ? VMDK4_COMPRESSION_DEFLATE : 0;

    header.capacity = filesize / BDRV_SECTOR_SIZE;

    header.granularity = 128;

    header.num_gtes_per_gt = BDRV_SECTOR_SIZE;

    grains = DIV_ROUND_UP(filesize / BDRV_SECTOR_SIZE, header.granularity);

    gt_size = DIV_ROUND_UP(header.num_gtes_per_gt * sizeof(uint32_t),

                           BDRV_SECTOR_SIZE);

    gt_count = DIV_ROUND_UP(grains, header.num_gtes_per_gt);

    gd_sectors = DIV_ROUND_UP(gt_count * sizeof(uint32_t), BDRV_SECTOR_SIZE);

    header.desc_offset = 1;

    header.desc_size = 20;

    header.rgd_offset = header.desc_offset + header.desc_size;

    header.gd_offset = header.rgd_offset + gd_sectors + (gt_size * gt_count);

    header.grain_offset =

        ROUND_UP(header.gd_offset + gd_sectors + (gt_size * gt_count),

                 header.granularity);

    /* swap endianness for all header fields */

    header.version = cpu_to_le32(header.version);

    header.flags = cpu_to_le32(header.flags);

    header.capacity = cpu_to_le64(header.capacity);

    header.granularity = cpu_to_le64(header.granularity);

    header.num_gtes_per_gt = cpu_to_le32(header.num_gtes_per_gt);

    header.desc_offset = cpu_to_le64(header.desc_offset);

    header.desc_size = cpu_to_le64(header.desc_size);

    header.rgd_offset = cpu_to_le64(header.rgd_offset);

    header.gd_offset = cpu_to_le64(header.gd_offset);

    header.grain_offset = cpu_to_le64(header.grain_offset);

    header.compressAlgorithm = cpu_to_le16(header.compressAlgorithm);

    header.check_bytes[0] = 0xa;

    header.check_bytes[1] = 0x20;

    header.check_bytes[2] = 0xd;

    header.check_bytes[3] = 0xa;

    /* write all the data */

    ret = bdrv_pwrite(bs, 0, &magic, sizeof(magic));

    if (ret < 0) {

        error_set(errp, QERR_IO_ERROR);

        goto exit;

    }

    ret = bdrv_pwrite(bs, sizeof(magic), &header, sizeof(header));

    if (ret < 0) {

        error_set(errp, QERR_IO_ERROR);

        goto exit;

    }

    ret = bdrv_truncate(bs, le64_to_cpu(header.grain_offset) << 9);

    if (ret < 0) {

        error_setg(errp, "Could not truncate file");

        goto exit;

    }

    /* write grain directory */

    gd_buf_size = gd_sectors * BDRV_SECTOR_SIZE;

    gd_buf = g_malloc0(gd_buf_size);

    for (i = 0, tmp = le64_to_cpu(header.rgd_offset) + gd_sectors;

         i < gt_count; i++, tmp += gt_size) {

        gd_buf[i] = cpu_to_le32(tmp);

    }

    ret = bdrv_pwrite(bs, le64_to_cpu(header.rgd_offset) * BDRV_SECTOR_SIZE,

                      gd_buf, gd_buf_size);

    if (ret < 0) {

        error_set(errp, QERR_IO_ERROR);

        goto exit;

    }

    /* write backup grain directory */

    for (i = 0, tmp = le64_to_cpu(header.gd_offset) + gd_sectors;

         i < gt_count; i++, tmp += gt_size) {

        gd_buf[i] = cpu_to_le32(tmp);

    }

    ret = bdrv_pwrite(bs, le64_to_cpu(header.gd_offset) * BDRV_SECTOR_SIZE,

                      gd_buf, gd_buf_size);

    if (ret < 0) {

        error_set(errp, QERR_IO_ERROR);

        goto exit;

    }

    ret = 0;

exit:

    if (bs) {

        bdrv_unref(bs);

    }

    g_free(gd_buf);

    return ret;

}


static void ppc_prep_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    const char *boot_device = args->boot_order;

    MemoryRegion *sysmem = get_system_memory();

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    nvram_t nvram;

    M48t59State *m48t59;

    PortioList *port_list = g_new(PortioList, 1);

#if 0

    MemoryRegion *xcsr = g_new(MemoryRegion, 1);

#endif

    int linux_boot, i, nb_nics1;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *vga = g_new(MemoryRegion, 1);

    uint32_t kernel_base, initrd_base;

    long kernel_size, initrd_size;

    DeviceState *dev;

    PCIHostState *pcihost;

    PCIBus *pci_bus;

    PCIDevice *pci;

    ISABus *isa_bus;

    ISADevice *isa;

    qemu_irq *cpu_exit_irq;

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    sysctrl = g_malloc0(sizeof(sysctrl_t));

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

        cpu_model = "602";

    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;

        if (env->flags & POWERPC_FLAG_RTC_CLK) {

            /* POWER / PowerPC 601 RTC clock frequency is 7.8125 MHz */

            cpu_ppc_tb_init(env, 7812500UL);

        } else {

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

            cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

        }

        qemu_register_reset(ppc_prep_reset, cpu);

    }

    /* allocate RAM */

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

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(sysmem, 0, ram);

    if (linux_boot) {

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        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 = INITRD_LOAD_ADDR;

            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);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* For now, OHW cannot boot from the network. */

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

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

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

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

            exit(1);

        }

    }

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

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

    }

    dev = qdev_create(NULL, "raven-pcihost");

    if (bios_name == NULL) {

        bios_name = BIOS_FILENAME;

    }

    qdev_prop_set_string(dev, "bios-name", bios_name);

    qdev_prop_set_uint32(dev, "elf-machine", ELF_MACHINE);

    pcihost = PCI_HOST_BRIDGE(dev);

    object_property_add_child(qdev_get_machine(), "raven", OBJECT(dev), NULL);

    qdev_init_nofail(dev);

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");

    if (pci_bus == NULL) {

        fprintf(stderr, "Couldn't create PCI host controller.\n");

        exit(1);

    }

    sysctrl->contiguous_map_irq = qdev_get_gpio_in(dev, 0);

    /* PCI -> ISA bridge */

    pci = pci_create_simple(pci_bus, PCI_DEVFN(1, 0), "i82378");

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    cpu = POWERPC_CPU(first_cpu);

    qdev_connect_gpio_out(&pci->qdev, 0,

                          cpu->env.irq_inputs[PPC6xx_INPUT_INT]);

    qdev_connect_gpio_out(&pci->qdev, 1, *cpu_exit_irq);

    sysbus_connect_irq(&pcihost->busdev, 0, qdev_get_gpio_in(&pci->qdev, 9));

    sysbus_connect_irq(&pcihost->busdev, 1, qdev_get_gpio_in(&pci->qdev, 11));

    sysbus_connect_irq(&pcihost->busdev, 2, qdev_get_gpio_in(&pci->qdev, 9));

    sysbus_connect_irq(&pcihost->busdev, 3, qdev_get_gpio_in(&pci->qdev, 11));

    isa_bus = ISA_BUS(qdev_get_child_bus(DEVICE(pci), "isa.0"));

    /* Super I/O (parallel + serial ports) */

    isa = isa_create(isa_bus, TYPE_PC87312);

    dev = DEVICE(isa);

    qdev_prop_set_uint8(dev, "config", 13); /* fdc, ser0, ser1, par0 */

    qdev_init_nofail(dev);

    /* init basic PC hardware */

    pci_vga_init(pci_bus);

    /* Open Hack'Ware hack: PCI BAR#0 is programmed to 0xf0000000.

     * While bios will access framebuffer at 0xf0000000, real physical

     * address is 0xf0000000 + 0xc0000000 (PCI memory base).

     * Alias the wrong memory accesses to the right place.

     */

    memory_region_init_alias(vga, NULL, "vga-alias", pci_address_space(pci),

                             0xf0000000, 0x1000000);

    memory_region_add_subregion_overlap(sysmem, 0xf0000000, vga, 10);

    nb_nics1 = nb_nics;

    if (nb_nics1 > NE2000_NB_MAX)

        nb_nics1 = NE2000_NB_MAX;

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

        if (nd_table[i].model == NULL) {

	    nd_table[i].model = g_strdup("ne2k_isa");

        }

        if (strcmp(nd_table[i].model, "ne2k_isa") == 0) {

            isa_ne2000_init(isa_bus, ne2000_io[i], ne2000_irq[i],

                            &nd_table[i]);

        } else {

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

        }

    }

    ide_drive_get(hd, MAX_IDE_BUS);

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

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

                     hd[2 * i],

		     hd[2 * i + 1]);

    }

    isa_create_simple(isa_bus, "i8042");

    cpu = POWERPC_CPU(first_cpu);

    sysctrl->reset_irq = cpu->env.irq_inputs[PPC6xx_INPUT_HRESET];

    portio_list_init(port_list, NULL, prep_portio_list, sysctrl, "prep");

    portio_list_add(port_list, isa_address_space_io(isa), 0x0);

    /* PowerPC control and status register group */

#if 0

    memory_region_init_io(xcsr, NULL, &PPC_XCSR_ops, NULL, "ppc-xcsr", 0x1000);

    memory_region_add_subregion(sysmem, 0xFEFF0000, xcsr);

#endif

    if (usb_enabled(false)) {

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

    }

    m48t59 = m48t59_init_isa(isa_bus, 0x0074, NVRAM_SIZE, 59);

    if (m48t59 == NULL)

        return;

    sysctrl->nvram = m48t59;

    /* Initialise NVRAM */

    nvram.opaque = m48t59;

    nvram.read_fn = &m48t59_read;

    nvram.write_fn = &m48t59_write;

    PPC_NVRAM_set_params(&nvram, NVRAM_SIZE, "PREP", ram_size, ppc_boot_device,

                         kernel_base, kernel_size,

                         kernel_cmdline,

                         initrd_base, initrd_size,

                         /* XXX: need an option to load a NVRAM image */

                         0,

                         graphic_width, graphic_height, graphic_depth);

}


int boot_sector_init(char *fname)

{

    int fd, ret;

    size_t len = sizeof boot_sector;

    fd = mkstemp(fname);

    if (fd < 0) {

        fprintf(stderr, "Couldn't open \"%s\": %s", fname, strerror(errno));

        return 1;

    }

    /* For Open Firmware based system, we can use a Forth script instead */

    if (strcmp(qtest_get_arch(), "ppc64") == 0) {

        len = sprintf((char *)boot_sector, "\\ Bootscript\n%x %x c! %x %x c!\n",

                LOW(SIGNATURE), BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET,

                HIGH(SIGNATURE), BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1);

    }

    ret = write(fd, boot_sector, len);

    close(fd);

    if (ret != len) {

        fprintf(stderr, "Could not write \"%s\"", fname);

        return 1;

    }

    return 0;

}


static int usbnet_can_receive(VLANClientState *nc)

{

    USBNetState *s = DO_UPCAST(NICState, nc, nc)->opaque;

    if (is_rndis(s) && !s->rndis_state == RNDIS_DATA_INITIALIZED) {

        return 1;

    }

    return !s->in_len;

}


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

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);

    Error *err = NULL;

    /* Devices should either use vmsd or the load/save methods */

    assert(!vdc->vmsd || !vdc->load);

    if (vdc->realize != NULL) {

        vdc->realize(dev, &err);

        if (err != NULL) {

            error_propagate(errp, err);

            return;

        }

    }

    virtio_bus_device_plugged(vdev, &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

    vdev->listener.commit = virtio_memory_listener_commit;

    memory_listener_register(&vdev->listener, vdev->dma_as);

}


int ff_rtp_get_payload_type(AVFormatContext *fmt,

                            AVCodecContext *codec, int idx)

{

    int i;

    AVOutputFormat *ofmt = fmt ? fmt->oformat : NULL;

    /* Was the payload type already specified for the RTP muxer? */

    if (ofmt && ofmt->priv_class && fmt->priv_data) {

        int64_t payload_type;

        if (av_opt_get_int(fmt->priv_data, "payload_type", 0, &payload_type) >= 0 &&

            payload_type >= 0)

            return (int)payload_type;

    }

    /* static payload type */

    for (i = 0; rtp_payload_types[i].pt >= 0; ++i)

        if (rtp_payload_types[i].codec_id == codec->codec_id) {

            if (codec->codec_id == AV_CODEC_ID_H263 && (!fmt ||

                !fmt->oformat->priv_class ||

                !av_opt_flag_is_set(fmt->priv_data, "rtpflags", "rfc2190")))

                continue;

            /* G722 has 8000 as nominal rate even if the sample rate is 16000,

             * see section 4.5.2 in RFC 3551. */

            if (codec->codec_id == AV_CODEC_ID_ADPCM_G722 &&

                codec->sample_rate == 16000 && codec->channels == 1)

                return rtp_payload_types[i].pt;

            if (codec->codec_type == AVMEDIA_TYPE_AUDIO &&

                ((rtp_payload_types[i].clock_rate > 0 &&

                  codec->sample_rate != rtp_payload_types[i].clock_rate) ||

                 (rtp_payload_types[i].audio_channels > 0 &&

                  codec->channels != rtp_payload_types[i].audio_channels)))

                continue;

            return rtp_payload_types[i].pt;

        }

    if (idx < 0)

        idx = codec->codec_type == AVMEDIA_TYPE_AUDIO;

    /* dynamic payload type */

    return RTP_PT_PRIVATE + idx;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = pit_common_realize;

    dc->vmsd = &vmstate_pit_common;

    dc->no_user = 1;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *in)

{

    AVFilterContext *ctx = inlink->dst;

    AVFilterLink *outlink = ctx->outputs[0];

    QPContext *s = ctx->priv;

    AVBufferRef *out_qp_table_buf;

    AVFrame *out;

    const int8_t *in_qp_table;

    int type, stride, ret;

    if (!s->qp_expr_str || ctx->is_disabled)

        return ff_filter_frame(outlink, in);

    out_qp_table_buf = av_buffer_alloc(s->h * s->qstride);

    if (!out_qp_table_buf) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    out = av_frame_clone(in);

    if (!out) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    in_qp_table = av_frame_get_qp_table(in, &stride, &type);

    av_frame_set_qp_table(out, out_qp_table_buf, s->qstride, type);

    if (in_qp_table) {

        int y, x;

        for (y = 0; y < s->h; y++)

            for (x = 0; x < s->qstride; x++)

                out_qp_table_buf->data[x + s->qstride * y] = s->lut[129 +

                    ((int8_t)in_qp_table[x + stride * y])];

    } else {

        int y, x, qp = s->lut[0];

        for (y = 0; y < s->h; y++)

            for (x = 0; x < s->qstride; x++)

                out_qp_table_buf->data[x + s->qstride * y] = qp;

    }

    ret = ff_filter_frame(outlink, out);

fail:

    av_frame_free(&in);

    return ret;

}


static int oss_init_out (HWVoiceOut *hw, struct audsettings *as)

{

    OSSVoiceOut *oss = (OSSVoiceOut *) hw;

    struct oss_params req, obt;

    int endianness;

    int err;

    int fd;

    audfmt_e effective_fmt;

    struct audsettings obt_as;

    oss->fd = -1;

    req.fmt = aud_to_ossfmt (as->fmt, as->endianness);

    req.freq = as->freq;

    req.nchannels = as->nchannels;

    req.fragsize = conf.fragsize;

    req.nfrags = conf.nfrags;

    if (oss_open (0, &req, &obt, &fd)) {

        return -1;

    }

    err = oss_to_audfmt (obt.fmt, &effective_fmt, &endianness);

    if (err) {

        oss_anal_close (&fd);

        return -1;

    }

    obt_as.freq = obt.freq;

    obt_as.nchannels = obt.nchannels;

    obt_as.fmt = effective_fmt;

    obt_as.endianness = endianness;

    audio_pcm_init_info (&hw->info, &obt_as);

    oss->nfrags = obt.nfrags;

    oss->fragsize = obt.fragsize;

    if (obt.nfrags * obt.fragsize & hw->info.align) {

        dolog ("warning: Misaligned DAC buffer, size %d, alignment %d\n",

               obt.nfrags * obt.fragsize, hw->info.align + 1);

    }

    hw->samples = (obt.nfrags * obt.fragsize) >> hw->info.shift;

    oss->mmapped = 0;

    if (conf.try_mmap) {

        oss->pcm_buf = mmap (

            NULL,

            hw->samples << hw->info.shift,

            PROT_READ | PROT_WRITE,

            MAP_SHARED,

            fd,

            0

            );

        if (oss->pcm_buf == MAP_FAILED) {

            oss_logerr (errno, "Failed to map %d bytes of DAC\n",

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

        }

        else {

            int err;

            int trig = 0;

            if (ioctl (fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {

                oss_logerr (errno, "SNDCTL_DSP_SETTRIGGER 0 failed\n");

            }

            else {

                trig = PCM_ENABLE_OUTPUT;

                if (ioctl (fd, SNDCTL_DSP_SETTRIGGER, &trig) < 0) {

                    oss_logerr (

                        errno,

                        "SNDCTL_DSP_SETTRIGGER PCM_ENABLE_OUTPUT failed\n"

                        );

                }

                else {

                    oss->mmapped = 1;

                }

            }

            if (!oss->mmapped) {

                err = munmap (oss->pcm_buf, hw->samples << hw->info.shift);

                if (err) {

                    oss_logerr (errno, "Failed to unmap buffer %p size %d\n",

                                oss->pcm_buf, hw->samples << hw->info.shift);

                }

            }

        }

    }

    if (!oss->mmapped) {

        oss->pcm_buf = audio_calloc (

            AUDIO_FUNC,

            hw->samples,

            1 << hw->info.shift

            );

        if (!oss->pcm_buf) {

            dolog (

                "Could not allocate DAC buffer (%d samples, each %d bytes)\n",

                hw->samples,

                1 << hw->info.shift

                );

            oss_anal_close (&fd);

            return -1;

        }

    }

    oss->fd = fd;

    return 0;

}


static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name){

    int64_t pos = avio_tell(pb);

    avio_wb32(pb, 0);                              /* size */

    ffio_wfourcc(pb, "name");                      /* Data format */

    avio_wb16(pb, strlen(reel_name));              /* string size */

    avio_wb16(pb, track->language);                /* langcode */

    avio_write(pb, reel_name, strlen(reel_name));  /* reel name */

    return update_size(pb,pos);

}


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

{

    const int mb_x= s->mb_x;

    const int mb_y= s->mb_y;

    int i;

#if 0

        if (s->interlaced_dct) {

            dct_linesize = s->linesize * 2;

            dct_offset = s->linesize;

        } else {

            dct_linesize = s->linesize;

            dct_offset = s->linesize * 8;

        }

#endif

    if (s->mb_intra) {

        UINT8 *ptr;

        int wrap;

        wrap = s->linesize;

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

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

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

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

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

        wrap >>=1;

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

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

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

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

    }else{

        op_pixels_func *op_pix;

        qpel_mc_func *op_qpix;

        UINT8 *dest_y, *dest_cb, *dest_cr;

        UINT8 *ptr;

        int wrap;

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

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

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

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

            op_pix = put_pixels_tab;

            op_qpix= qpel_mc_rnd_tab;

        }else{

            op_pix = put_no_rnd_pixels_tab;

            op_qpix= qpel_mc_no_rnd_tab;

        }

        if (s->mv_dir & MV_DIR_FORWARD) {

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

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

                op_pix = avg_pixels_tab;

            else

                op_pix = avg_no_rnd_pixels_tab;

        }

        if (s->mv_dir & MV_DIR_BACKWARD) {

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

        }

        wrap = s->linesize;

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

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

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

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

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

        wrap >>=1;

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

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

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

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

    }

#if 0

            {

                float adap_parm;

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

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

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

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

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

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

            }

#endif

    /* DCT & quantize */

    if (s->h263_pred && s->msmpeg4_version!=2) {

        h263_dc_scale(s);

    } else if (s->h263_aic) {

        s->y_dc_scale = 2*s->qscale;

        s->c_dc_scale = 2*s->qscale;

    } else {

        /* default quantization values */

        s->y_dc_scale = 8;

        s->c_dc_scale = 8;

    }

    if(s->out_format==FMT_MJPEG){

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

            int overflow;

            s->block_last_index[i] = dct_quantize(s, s->block[i], i, 8, &overflow);

            if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);

        }

    }else{

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

            int overflow;

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

            // FIXME we could decide to change to quantizer instead of clipping

            // JS: I don't think that would be a good idea it could lower quality instead

            //     of improve it. Just INTRADC clipping deserves changes in quantizer

            if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);

        }

    }

    /* huffman encode */

    switch(s->out_format) {

    case FMT_MPEG1:

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

        break;

    case FMT_H263:

        if (s->h263_msmpeg4)

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

        else if(s->h263_pred)

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

        else

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

        break;

    case FMT_MJPEG:

        mjpeg_encode_mb(s, s->block);

        break;

    }

}


static int decode_subframe_fixed(FLACContext *s, int channel, int pred_order)

{

    const int blocksize = s->blocksize;

    int32_t *decoded = s->decoded[channel];

    int a, b, c, d, i;

    /* warm up samples */

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

        decoded[i] = get_sbits(&s->gb, s->curr_bps);

    }

    if (decode_residuals(s, channel, pred_order) < 0)

        return -1;

    if (pred_order > 0)

        a = decoded[pred_order-1];

    if (pred_order > 1)

        b = a - decoded[pred_order-2];

    if (pred_order > 2)

        c = b - decoded[pred_order-2] + decoded[pred_order-3];

    if (pred_order > 3)

        d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4];

    switch (pred_order) {

    case 0:

        break;

    case 1:

        for (i = pred_order; i < blocksize; i++)

            decoded[i] = a += decoded[i];

        break;

    case 2:

        for (i = pred_order; i < blocksize; i++)

            decoded[i] = a += b += decoded[i];

        break;

    case 3:

        for (i = pred_order; i < blocksize; i++)

            decoded[i] = a += b += c += decoded[i];

        break;

    case 4:

        for (i = pred_order; i < blocksize; i++)

            decoded[i] = a += b += c += d += decoded[i];

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order);

        return -1;

    }

    return 0;

}