int attribute_align_arg sws_scale(struct SwsContext *c,

                                  const uint8_t * const srcSlice[],

                                  const int srcStride[], int srcSliceY,

                                  int srcSliceH, uint8_t *const dst[],

                                  const int dstStride[])

{

    int i, ret;

    const uint8_t *src2[4] = { srcSlice[0], srcSlice[1], srcSlice[2], srcSlice[3] };

    uint8_t *dst2[4] = { dst[0], dst[1], dst[2], dst[3] };

    uint8_t *rgb0_tmp = NULL;

    // do not mess up sliceDir if we have a "trailing" 0-size slice

    if (srcSliceH == 0)

        return 0;

    if (!check_image_pointers(srcSlice, c->srcFormat, srcStride)) {

        av_log(c, AV_LOG_ERROR, "bad src image pointers\n");

        return 0;

    }

    if (!check_image_pointers((const uint8_t* const*)dst, c->dstFormat, dstStride)) {

        av_log(c, AV_LOG_ERROR, "bad dst image pointers\n");

        return 0;

    }

    if (c->sliceDir == 0 && srcSliceY != 0 && srcSliceY + srcSliceH != c->srcH) {

        av_log(c, AV_LOG_ERROR, "Slices start in the middle!\n");

        return 0;

    }

    if (c->sliceDir == 0) {

        if (srcSliceY == 0) c->sliceDir = 1; else c->sliceDir = -1;

    }

    if (usePal(c->srcFormat)) {

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

            int p, r, g, b, y, u, v, a = 0xff;

            if (c->srcFormat == AV_PIX_FMT_PAL8) {

                p = ((const uint32_t *)(srcSlice[1]))[i];

                a = (p >> 24) & 0xFF;

                r = (p >> 16) & 0xFF;

                g = (p >>  8) & 0xFF;

                b =  p        & 0xFF;

            } else if (c->srcFormat == AV_PIX_FMT_RGB8) {

                r = ( i >> 5     ) * 36;

                g = ((i >> 2) & 7) * 36;

                b = ( i       & 3) * 85;

            } else if (c->srcFormat == AV_PIX_FMT_BGR8) {

                b = ( i >> 6     ) * 85;

                g = ((i >> 3) & 7) * 36;

                r = ( i       & 7) * 36;

            } else if (c->srcFormat == AV_PIX_FMT_RGB4_BYTE) {

                r = ( i >> 3     ) * 255;

                g = ((i >> 1) & 3) * 85;

                b = ( i       & 1) * 255;

            } else if (c->srcFormat == AV_PIX_FMT_GRAY8 || c->srcFormat == AV_PIX_FMT_GRAY8A) {

                r = g = b = i;

            } else {

                av_assert1(c->srcFormat == AV_PIX_FMT_BGR4_BYTE);

                b = ( i >> 3     ) * 255;

                g = ((i >> 1) & 3) * 85;

                r = ( i       & 1) * 255;

            }

#define RGB2YUV_SHIFT 15

#define BY ( (int) (0.114 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define BV (-(int) (0.081 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define BU ( (int) (0.500 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define GY ( (int) (0.587 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define GV (-(int) (0.419 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define GU (-(int) (0.331 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define RY ( (int) (0.299 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define RV ( (int) (0.500 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

#define RU (-(int) (0.169 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5))

            y = av_clip_uint8((RY * r + GY * g + BY * b + ( 33 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);

            u = av_clip_uint8((RU * r + GU * g + BU * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);

            v = av_clip_uint8((RV * r + GV * g + BV * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT);

            c->pal_yuv[i]= y + (u<<8) + (v<<16) + ((unsigned)a<<24);

            switch (c->dstFormat) {

            case AV_PIX_FMT_BGR32:

#if !HAVE_BIGENDIAN

            case AV_PIX_FMT_RGB24:

#endif

                c->pal_rgb[i]=  r + (g<<8) + (b<<16) + ((unsigned)a<<24);

                break;

            case AV_PIX_FMT_BGR32_1:

#if HAVE_BIGENDIAN

            case AV_PIX_FMT_BGR24:

#endif

                c->pal_rgb[i]= a + (r<<8) + (g<<16) + ((unsigned)b<<24);

                break;

            case AV_PIX_FMT_RGB32_1:

#if HAVE_BIGENDIAN

            case AV_PIX_FMT_RGB24:

#endif

                c->pal_rgb[i]= a + (b<<8) + (g<<16) + ((unsigned)r<<24);

                break;

            case AV_PIX_FMT_RGB32:

#if !HAVE_BIGENDIAN

            case AV_PIX_FMT_BGR24:

#endif

            default:

                c->pal_rgb[i]=  b + (g<<8) + (r<<16) + ((unsigned)a<<24);

            }

        }

    }

    if (c->src0Alpha && !c->dst0Alpha && isALPHA(c->dstFormat)) {

        uint8_t *base;

        int x,y;

        rgb0_tmp = av_malloc(FFABS(srcStride[0]) * srcSliceH + 32);

        base = srcStride[0] < 0 ? rgb0_tmp - srcStride[0] * (srcSliceH-1) : rgb0_tmp;

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

            memcpy(base + srcStride[0]*y, src2[0] + srcStride[0]*y, 4*c->srcW);

            for (x=c->src0Alpha-1; x<4*c->srcW; x+=4) {

                base[ srcStride[0]*y + x] = 0xFF;

            }

        }

        src2[0] = base;

    }

    // copy strides, so they can safely be modified

    if (c->sliceDir == 1) {

        // slices go from top to bottom

        int srcStride2[4] = { srcStride[0], srcStride[1], srcStride[2],

                              srcStride[3] };

        int dstStride2[4] = { dstStride[0], dstStride[1], dstStride[2],

                              dstStride[3] };

        reset_ptr(src2, c->srcFormat);

        reset_ptr((void*)dst2, c->dstFormat);

        /* reset slice direction at end of frame */

        if (srcSliceY + srcSliceH == c->srcH)

            c->sliceDir = 0;

        ret = c->swScale(c, src2, srcStride2, srcSliceY, srcSliceH, dst2,

                          dstStride2);

    } else {

        // slices go from bottom to top => we flip the image internally

        int srcStride2[4] = { -srcStride[0], -srcStride[1], -srcStride[2],

                              -srcStride[3] };

        int dstStride2[4] = { -dstStride[0], -dstStride[1], -dstStride[2],

                              -dstStride[3] };

        src2[0] += (srcSliceH - 1) * srcStride[0];

        if (!usePal(c->srcFormat))

            src2[1] += ((srcSliceH >> c->chrSrcVSubSample) - 1) * srcStride[1];

        src2[2] += ((srcSliceH >> c->chrSrcVSubSample) - 1) * srcStride[2];

        src2[3] += (srcSliceH - 1) * srcStride[3];

        dst2[0] += ( c->dstH                         - 1) * dstStride[0];

        dst2[1] += ((c->dstH >> c->chrDstVSubSample) - 1) * dstStride[1];

        dst2[2] += ((c->dstH >> c->chrDstVSubSample) - 1) * dstStride[2];

        dst2[3] += ( c->dstH                         - 1) * dstStride[3];

        reset_ptr(src2, c->srcFormat);

        reset_ptr((void*)dst2, c->dstFormat);

        /* reset slice direction at end of frame */

        if (!srcSliceY)

            c->sliceDir = 0;

        ret = c->swScale(c, src2, srcStride2, c->srcH-srcSliceY-srcSliceH,

                          srcSliceH, dst2, dstStride2);

    }

    av_free(rgb0_tmp);

    return ret;

}


static inline uint32_t vmsvga_fifo_read_raw(struct vmsvga_state_s *s)

{

    uint32_t cmd = s->fifo[CMD(stop) >> 2];

    s->cmd->stop = cpu_to_le32(CMD(stop) + 4);

    if (CMD(stop) >= CMD(max)) {

        s->cmd->stop = s->cmd->min;

    }

    return cmd;

}


static void do_rematrixing(AC3DecodeContext *s)

{

    int bnd, i;

    int end, bndend;

    int tmp0, tmp1;

    end = FFMIN(s->end_freq[1], s->end_freq[2]);

    for(bnd=0; bnd<s->num_rematrixing_bands; bnd++) {

        if(s->rematrixing_flags[bnd]) {

            bndend = FFMIN(end, ff_ac3_rematrix_band_tab[bnd+1]);

            for(i=ff_ac3_rematrix_band_tab[bnd]; i<bndend; i++) {

                tmp0 = s->fixed_coeffs[1][i];

                tmp1 = s->fixed_coeffs[2][i];

                s->fixed_coeffs[1][i] = tmp0 + tmp1;

                s->fixed_coeffs[2][i] = tmp0 - tmp1;

            }

        }

    }

}


static void dead_tmp(TCGv tmp)

{

    tcg_temp_free(tmp);

    num_temps--;

}


int bdrv_has_zero_init(BlockDriverState *bs)

{

    assert(bs->drv);

    if (bs->drv->bdrv_has_zero_init) {

        return bs->drv->bdrv_has_zero_init(bs);

    }

    return 1;

}


static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)

{

    CharDriverState *chr;

    MuxDriver *d;

    chr = qemu_chr_alloc();

    d = g_malloc0(sizeof(MuxDriver));

    chr->opaque = d;

    d->drv = drv;

    d->focus = -1;

    chr->chr_write = mux_chr_write;

    chr->chr_update_read_handler = mux_chr_update_read_handler;

    chr->chr_accept_input = mux_chr_accept_input;

    /* Frontend guest-open / -close notification is not support with muxes */

    chr->chr_set_fe_open = NULL;

    if (drv->chr_add_watch) {

        chr->chr_add_watch = mux_chr_add_watch;

    }

    /* only default to opened state if we've realized the initial

     * set of muxes

     */

    chr->explicit_be_open = muxes_realized ? 0 : 1;

    chr->is_mux = 1;

    return chr;

}


static int scan_file(AVFormatContext *avctx, AVStream *vst, AVStream *ast, int file)

{

    MlvContext *mlv = avctx->priv_data;

    AVIOContext *pb = mlv->pb[file];

    int ret;

    while (!avio_feof(pb)) {

        int type;

        unsigned int size;

        type = avio_rl32(pb);

        size = avio_rl32(pb);

        avio_skip(pb, 8); //timestamp

        if (size < 16)

            break;

        size -= 16;

        if (vst && type == MKTAG('R','A','W','I') && size >= 164) {

            vst->codec->width  = avio_rl16(pb);

            vst->codec->height = avio_rl16(pb);

            if (avio_rl32(pb) != 1)

                avpriv_request_sample(avctx, "raw api version");

            avio_skip(pb, 20); // pointer, width, height, pitch, frame_size

            vst->codec->bits_per_coded_sample = avio_rl32(pb);

            avio_skip(pb, 8 + 16 + 24); // black_level, white_level, xywh, active_area, exposure_bias

            if (avio_rl32(pb) != 0x2010100) /* RGGB */

                avpriv_request_sample(avctx, "cfa_pattern");

            avio_skip(pb, 80); // calibration_illuminant1, color_matrix1, dynamic_range

            vst->codec->pix_fmt  = AV_PIX_FMT_BAYER_RGGB16LE;

            vst->codec->codec_tag = MKTAG('B', 'I', 'T', 16);

            size -= 164;

        } else if (ast && type == MKTAG('W', 'A', 'V', 'I') && size >= 16) {

            ret = ff_get_wav_header(avctx, pb, ast->codec, 16, 0);

            size -= 16;

        } else if (type == MKTAG('I','N','F','O')) {

            if (size > 0)

                read_string(avctx, pb, "info", size);

            continue;

        } else if (type == MKTAG('I','D','N','T') && size >= 36) {

            read_string(avctx, pb, "cameraName", 32);

            read_uint32(avctx, pb, "cameraModel", "0x%"PRIx32);

            size -= 36;

            if (size >= 32) {

                read_string(avctx, pb, "cameraSerial", 32);

                size -= 32;

        } else if (type == MKTAG('L','E','N','S') && size >= 48) {

            read_uint16(avctx, pb, "focalLength", "%i");

            read_uint16(avctx, pb, "focalDist", "%i");

            read_uint16(avctx, pb, "aperture", "%i");

            read_uint8(avctx, pb, "stabilizerMode", "%i");

            read_uint8(avctx, pb, "autofocusMode", "%i");

            read_uint32(avctx, pb, "flags", "0x%"PRIx32);

            read_uint32(avctx, pb, "lensID", "%"PRIi32);

            read_string(avctx, pb, "lensName", 32);

            size -= 48;

            if (size >= 32) {

                read_string(avctx, pb, "lensSerial", 32);

                size -= 32;

        } else if (vst && type == MKTAG('V', 'I', 'D', 'F') && size >= 4) {

            uint64_t pts = avio_rl32(pb);

            ff_add_index_entry(&vst->index_entries, &vst->nb_index_entries, &vst->index_entries_allocated_size,

                               avio_tell(pb) - 20, pts, file, 0, AVINDEX_KEYFRAME);

            size -= 4;

        } else if (ast && type == MKTAG('A', 'U', 'D', 'F') && size >= 4) {

            uint64_t pts = avio_rl32(pb);

            ff_add_index_entry(&ast->index_entries, &ast->nb_index_entries, &ast->index_entries_allocated_size,

                               avio_tell(pb) - 20, pts, file, 0, AVINDEX_KEYFRAME);

            size -= 4;

        } else if (vst && type == MKTAG('W','B','A','L') && size >= 28) {

            read_uint32(avctx, pb, "wb_mode", "%"PRIi32);

            read_uint32(avctx, pb, "kelvin", "%"PRIi32);

            read_uint32(avctx, pb, "wbgain_r", "%"PRIi32);

            read_uint32(avctx, pb, "wbgain_g", "%"PRIi32);

            read_uint32(avctx, pb, "wbgain_b", "%"PRIi32);

            read_uint32(avctx, pb, "wbs_gm", "%"PRIi32);

            read_uint32(avctx, pb, "wbs_ba", "%"PRIi32);

            size -= 28;

        } else if (type == MKTAG('R','T','C','I') && size >= 20) {

            char str[32];

            struct tm time = { 0 };

            time.tm_sec    = avio_rl16(pb);

            time.tm_min    = avio_rl16(pb);

            time.tm_hour   = avio_rl16(pb);

            time.tm_mday   = avio_rl16(pb);

            time.tm_mon    = avio_rl16(pb);

            time.tm_year   = avio_rl16(pb);

            time.tm_wday   = avio_rl16(pb);

            time.tm_yday   = avio_rl16(pb);

            time.tm_isdst  = avio_rl16(pb);

            avio_skip(pb, 2);

            if (strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &time))

                av_dict_set(&avctx->metadata, "time", str, 0);

            size -= 20;

        } else if (type == MKTAG('E','X','P','O') && size >= 16) {

            av_dict_set(&avctx->metadata, "isoMode", avio_rl32(pb) ? "auto" : "manual", 0);

            read_uint32(avctx, pb, "isoValue", "%"PRIi32);

            read_uint32(avctx, pb, "isoAnalog", "%"PRIi32);

            read_uint32(avctx, pb, "digitalGain", "%"PRIi32);

            size -= 16;

            if (size >= 8) {

                read_uint64(avctx, pb, "shutterValue", "%"PRIi64);

                size -= 8;

        } else if (type == MKTAG('S','T','Y','L') && size >= 36) {

            read_uint32(avctx, pb, "picStyleId", "%"PRIi32);

            read_uint32(avctx, pb, "contrast", "%"PRIi32);

            read_uint32(avctx, pb, "sharpness", "%"PRIi32);

            read_uint32(avctx, pb, "saturation", "%"PRIi32);

            read_uint32(avctx, pb, "colortone", "%"PRIi32);

            read_string(avctx, pb, "picStyleName", 16);

            size -= 36;

        } else if (type == MKTAG('M','A','R','K')) {

        } else if (type == MKTAG('N','U','L','L')) {

        } else if (type == MKTAG('M','L','V','I')) { /* occurs when MLV and Mnn files are concatenated */

        } else {

            av_log(avctx, AV_LOG_INFO, "unsupported tag %c%c%c%c, size %u\n", type&0xFF, (type>>8)&0xFF, (type>>16)&0xFF, (type>>24)&0xFF, size);

        avio_skip(pb, size);

    return 0;


static void qmp_query_auth(VncDisplay *vd, VncInfo2 *info)

{

    switch (vd->auth) {

    case VNC_AUTH_VNC:

        info->auth = VNC_PRIMARY_AUTH_VNC;

        break;

    case VNC_AUTH_RA2:

        info->auth = VNC_PRIMARY_AUTH_RA2;

        break;

    case VNC_AUTH_RA2NE:

        info->auth = VNC_PRIMARY_AUTH_RA2NE;

        break;

    case VNC_AUTH_TIGHT:

        info->auth = VNC_PRIMARY_AUTH_TIGHT;

        break;

    case VNC_AUTH_ULTRA:

        info->auth = VNC_PRIMARY_AUTH_ULTRA;

        break;

    case VNC_AUTH_TLS:

        info->auth = VNC_PRIMARY_AUTH_TLS;

        break;

    case VNC_AUTH_VENCRYPT:

        info->auth = VNC_PRIMARY_AUTH_VENCRYPT;

#ifdef CONFIG_VNC_TLS

        info->has_vencrypt = true;

        switch (vd->subauth) {

        case VNC_AUTH_VENCRYPT_PLAIN:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_PLAIN;

            break;

        case VNC_AUTH_VENCRYPT_TLSNONE:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_NONE;

            break;

        case VNC_AUTH_VENCRYPT_TLSVNC:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_VNC;

            break;

        case VNC_AUTH_VENCRYPT_TLSPLAIN:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_PLAIN;

            break;

        case VNC_AUTH_VENCRYPT_X509NONE:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_NONE;

            break;

        case VNC_AUTH_VENCRYPT_X509VNC:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_VNC;

            break;

        case VNC_AUTH_VENCRYPT_X509PLAIN:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_PLAIN;

            break;

        case VNC_AUTH_VENCRYPT_TLSSASL:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_TLS_SASL;

            break;

        case VNC_AUTH_VENCRYPT_X509SASL:

            info->vencrypt = VNC_VENCRYPT_SUB_AUTH_X509_SASL;

            break;

        default:

            info->has_vencrypt = false;

            break;

        }

#endif

        break;

    case VNC_AUTH_SASL:

        info->auth = VNC_PRIMARY_AUTH_SASL;

        break;

    case VNC_AUTH_NONE:

    default:

        info->auth = VNC_PRIMARY_AUTH_NONE;

        break;

    }

}


int hvf_vcpu_exec(CPUState *cpu)

{

    X86CPU *x86_cpu = X86_CPU(cpu);

    CPUX86State *env = &x86_cpu->env;

    int ret = 0;

    uint64_t rip = 0;

    cpu->halted = 0;

    if (hvf_process_events(cpu)) {

        return EXCP_HLT;

    }

    do {

        if (cpu->vcpu_dirty) {

            hvf_put_registers(cpu);

            cpu->vcpu_dirty = false;

        }

        env->hvf_emul->interruptable =

            !(rvmcs(cpu->hvf_fd, VMCS_GUEST_INTERRUPTIBILITY) &

             (VMCS_INTERRUPTIBILITY_STI_BLOCKING |

             VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING));

        hvf_inject_interrupts(cpu);

        vmx_update_tpr(cpu);

        qemu_mutex_unlock_iothread();

        if (!cpu_is_bsp(X86_CPU(cpu)) && cpu->halted) {

            qemu_mutex_lock_iothread();

            return EXCP_HLT;

        }

        hv_return_t r  = hv_vcpu_run(cpu->hvf_fd);

        assert_hvf_ok(r);

        /* handle VMEXIT */

        uint64_t exit_reason = rvmcs(cpu->hvf_fd, VMCS_EXIT_REASON);

        uint64_t exit_qual = rvmcs(cpu->hvf_fd, VMCS_EXIT_QUALIFICATION);

        uint32_t ins_len = (uint32_t)rvmcs(cpu->hvf_fd,

                                           VMCS_EXIT_INSTRUCTION_LENGTH);

        uint64_t idtvec_info = rvmcs(cpu->hvf_fd, VMCS_IDT_VECTORING_INFO);

        rip = rreg(cpu->hvf_fd, HV_X86_RIP);

        RFLAGS(env) = rreg(cpu->hvf_fd, HV_X86_RFLAGS);

        env->eflags = RFLAGS(env);

        qemu_mutex_lock_iothread();

        update_apic_tpr(cpu);

        current_cpu = cpu;

        ret = 0;

        switch (exit_reason) {

        case EXIT_REASON_HLT: {

            macvm_set_rip(cpu, rip + ins_len);

            if (!((cpu->interrupt_request & CPU_INTERRUPT_HARD) &&

                (EFLAGS(env) & IF_MASK))

                && !(cpu->interrupt_request & CPU_INTERRUPT_NMI) &&

                !(idtvec_info & VMCS_IDT_VEC_VALID)) {

                cpu->halted = 1;

                ret = EXCP_HLT;

            }

            ret = EXCP_INTERRUPT;

            break;

        }

        case EXIT_REASON_MWAIT: {

            ret = EXCP_INTERRUPT;

            break;

        }

            /* Need to check if MMIO or unmmaped fault */

        case EXIT_REASON_EPT_FAULT:

        {

            hvf_slot *slot;

            addr_t gpa = rvmcs(cpu->hvf_fd, VMCS_GUEST_PHYSICAL_ADDRESS);

            if (((idtvec_info & VMCS_IDT_VEC_VALID) == 0) &&

                ((exit_qual & EXIT_QUAL_NMIUDTI) != 0)) {

                vmx_set_nmi_blocking(cpu);

            }

            slot = hvf_find_overlap_slot(gpa, gpa);

            /* mmio */

            if (ept_emulation_fault(slot, gpa, exit_qual)) {

                struct x86_decode decode;

                load_regs(cpu);

                env->hvf_emul->fetch_rip = rip;

                decode_instruction(env, &decode);

                exec_instruction(env, &decode);

                store_regs(cpu);

                break;

            }

            break;

        }

        case EXIT_REASON_INOUT:

        {

            uint32_t in = (exit_qual & 8) != 0;

            uint32_t size =  (exit_qual & 7) + 1;

            uint32_t string =  (exit_qual & 16) != 0;

            uint32_t port =  exit_qual >> 16;

            /*uint32_t rep = (exit_qual & 0x20) != 0;*/

#if 1

            if (!string && in) {

                uint64_t val = 0;

                load_regs(cpu);

                hvf_handle_io(env, port, &val, 0, size, 1);

                if (size == 1) {

                    AL(env) = val;

                } else if (size == 2) {

                    AX(env) = val;

                } else if (size == 4) {

                    RAX(env) = (uint32_t)val;

                } else {

                    VM_PANIC("size");

                }

                RIP(env) += ins_len;

                store_regs(cpu);

                break;

            } else if (!string && !in) {

                RAX(env) = rreg(cpu->hvf_fd, HV_X86_RAX);

                hvf_handle_io(env, port, &RAX(env), 1, size, 1);

                macvm_set_rip(cpu, rip + ins_len);

                break;

            }

#endif

            struct x86_decode decode;

            load_regs(cpu);

            env->hvf_emul->fetch_rip = rip;

            decode_instruction(env, &decode);

            VM_PANIC_ON(ins_len != decode.len);

            exec_instruction(env, &decode);

            store_regs(cpu);

            break;

        }

        case EXIT_REASON_CPUID: {

            uint32_t rax = (uint32_t)rreg(cpu->hvf_fd, HV_X86_RAX);

            uint32_t rbx = (uint32_t)rreg(cpu->hvf_fd, HV_X86_RBX);

            uint32_t rcx = (uint32_t)rreg(cpu->hvf_fd, HV_X86_RCX);

            uint32_t rdx = (uint32_t)rreg(cpu->hvf_fd, HV_X86_RDX);

            cpu_x86_cpuid(env, rax, rcx, &rax, &rbx, &rcx, &rdx);

            wreg(cpu->hvf_fd, HV_X86_RAX, rax);

            wreg(cpu->hvf_fd, HV_X86_RBX, rbx);

            wreg(cpu->hvf_fd, HV_X86_RCX, rcx);

            wreg(cpu->hvf_fd, HV_X86_RDX, rdx);

            macvm_set_rip(cpu, rip + ins_len);

            break;

        }

        case EXIT_REASON_XSETBV: {

            X86CPU *x86_cpu = X86_CPU(cpu);

            CPUX86State *env = &x86_cpu->env;

            uint32_t eax = (uint32_t)rreg(cpu->hvf_fd, HV_X86_RAX);

            uint32_t ecx = (uint32_t)rreg(cpu->hvf_fd, HV_X86_RCX);

            uint32_t edx = (uint32_t)rreg(cpu->hvf_fd, HV_X86_RDX);

            if (ecx) {

                macvm_set_rip(cpu, rip + ins_len);

                break;

            }

            env->xcr0 = ((uint64_t)edx << 32) | eax;

            wreg(cpu->hvf_fd, HV_X86_XCR0, env->xcr0 | 1);

            macvm_set_rip(cpu, rip + ins_len);

            break;

        }

        case EXIT_REASON_INTR_WINDOW:

            vmx_clear_int_window_exiting(cpu);

            ret = EXCP_INTERRUPT;

            break;

        case EXIT_REASON_NMI_WINDOW:

            vmx_clear_nmi_window_exiting(cpu);

            ret = EXCP_INTERRUPT;

            break;

        case EXIT_REASON_EXT_INTR:

            /* force exit and allow io handling */

            ret = EXCP_INTERRUPT;

            break;

        case EXIT_REASON_RDMSR:

        case EXIT_REASON_WRMSR:

        {

            load_regs(cpu);

            if (exit_reason == EXIT_REASON_RDMSR) {

                simulate_rdmsr(cpu);

            } else {

                simulate_wrmsr(cpu);

            }

            RIP(env) += rvmcs(cpu->hvf_fd, VMCS_EXIT_INSTRUCTION_LENGTH);

            store_regs(cpu);

            break;

        }

        case EXIT_REASON_CR_ACCESS: {

            int cr;

            int reg;

            load_regs(cpu);

            cr = exit_qual & 15;

            reg = (exit_qual >> 8) & 15;

            switch (cr) {

            case 0x0: {

                macvm_set_cr0(cpu->hvf_fd, RRX(env, reg));

                break;

            }

            case 4: {

                macvm_set_cr4(cpu->hvf_fd, RRX(env, reg));

                break;

            }

            case 8: {

                X86CPU *x86_cpu = X86_CPU(cpu);

                if (exit_qual & 0x10) {

                    RRX(env, reg) = cpu_get_apic_tpr(x86_cpu->apic_state);

                } else {

                    int tpr = RRX(env, reg);

                    cpu_set_apic_tpr(x86_cpu->apic_state, tpr);

                    ret = EXCP_INTERRUPT;

                }

                break;

            }

            default:

                error_report("Unrecognized CR %d\n", cr);

                abort();

            }

            RIP(env) += ins_len;

            store_regs(cpu);

            break;

        }

        case EXIT_REASON_APIC_ACCESS: { /* TODO */

            struct x86_decode decode;

            load_regs(cpu);

            env->hvf_emul->fetch_rip = rip;

            decode_instruction(env, &decode);

            exec_instruction(env, &decode);

            store_regs(cpu);

            break;

        }

        case EXIT_REASON_TPR: {

            ret = 1;

            break;

        }

        case EXIT_REASON_TASK_SWITCH: {

            uint64_t vinfo = rvmcs(cpu->hvf_fd, VMCS_IDT_VECTORING_INFO);

            x68_segment_selector sel = {.sel = exit_qual & 0xffff};

            vmx_handle_task_switch(cpu, sel, (exit_qual >> 30) & 0x3,

             vinfo & VMCS_INTR_VALID, vinfo & VECTORING_INFO_VECTOR_MASK, vinfo

             & VMCS_INTR_T_MASK);

            break;

        }

        case EXIT_REASON_TRIPLE_FAULT: {

            qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);

            ret = EXCP_INTERRUPT;

            break;

        }

        case EXIT_REASON_RDPMC:

            wreg(cpu->hvf_fd, HV_X86_RAX, 0);

            wreg(cpu->hvf_fd, HV_X86_RDX, 0);

            macvm_set_rip(cpu, rip + ins_len);

            break;

        case VMX_REASON_VMCALL:

            /* TODO: inject #GP fault */

            break;

        default:

            error_report("%llx: unhandled exit %llx\n", rip, exit_reason);

        }

    } while (ret == 0);

    return ret;

}


static void dummy_event_handler(void *opaque)

{

}


void cpu_watchpoint_remove_by_ref(CPUState *env, CPUWatchpoint *watchpoint)

{

    TAILQ_REMOVE(&env->watchpoints, watchpoint, entry);

    tlb_flush_page(env, watchpoint->vaddr);

    qemu_free(watchpoint);

}


void armv7m_nvic_set_pending(void *opaque, int irq, bool secure)

{

    NVICState *s = (NVICState *)opaque;

    bool banked = exc_is_banked(irq);

    VecInfo *vec;

    assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);

    assert(!secure || banked);

    vec = (banked && secure) ? &s->sec_vectors[irq] : &s->vectors[irq];

    trace_nvic_set_pending(irq, secure, vec->enabled, vec->prio);

    if (irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV) {

        /* If a synchronous exception is pending then it may be

         * escalated to HardFault if:

         *  * it is equal or lower priority to current execution

         *  * it is disabled

         * (ie we need to take it immediately but we can't do so).

         * Asynchronous exceptions (and interrupts) simply remain pending.

         *

         * For QEMU, we don't have any imprecise (asynchronous) faults,

         * so we can assume that PREFETCH_ABORT and DATA_ABORT are always

         * synchronous.

         * Debug exceptions are awkward because only Debug exceptions

         * resulting from the BKPT instruction should be escalated,

         * but we don't currently implement any Debug exceptions other

         * than those that result from BKPT, so we treat all debug exceptions

         * as needing escalation.

         *

         * This all means we can identify whether to escalate based only on

         * the exception number and don't (yet) need the caller to explicitly

         * tell us whether this exception is synchronous or not.

         */

        int running = nvic_exec_prio(s);

        bool escalate = false;

        if (vec->prio >= running) {

            trace_nvic_escalate_prio(irq, vec->prio, running);

            escalate = true;

        } else if (!vec->enabled) {

            trace_nvic_escalate_disabled(irq);

            escalate = true;

        }

        if (escalate) {

            if (running < 0) {

                /* We want to escalate to HardFault but we can't take a

                 * synchronous HardFault at this point either. This is a

                 * Lockup condition due to a guest bug. We don't model

                 * Lockup, so report via cpu_abort() instead.

                 */

                cpu_abort(&s->cpu->parent_obj,

                          "Lockup: can't escalate %d to HardFault "

                          "(current priority %d)\n", irq, running);

            }

            /* We can do the escalation, so we take HardFault instead.

             * If BFHFNMINS is set then we escalate to the banked HF for

             * the target security state of the original exception; otherwise

             * we take a Secure HardFault.

             */

            irq = ARMV7M_EXCP_HARD;

            if (arm_feature(&s->cpu->env, ARM_FEATURE_M_SECURITY) &&

                (secure ||

                 !(s->cpu->env.v7m.aircr & R_V7M_AIRCR_BFHFNMINS_MASK))) {

                vec = &s->sec_vectors[irq];

            } else {

                vec = &s->vectors[irq];

            }

            /* HF may be banked but there is only one shared HFSR */

            s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;

        }

    }

    if (!vec->pending) {

        vec->pending = 1;

        nvic_irq_update(s);

    }

}


void portio_list_init(PortioList *piolist,

                      const MemoryRegionPortio *callbacks,

                      void *opaque, const char *name)

{

    unsigned n = 0;

    while (callbacks[n].size) {

        ++n;

    }

    piolist->ports = callbacks;

    piolist->nr = 0;

    piolist->regions = g_new0(MemoryRegion *, n);

    piolist->aliases = g_new0(MemoryRegion *, n);

    piolist->address_space = NULL;

    piolist->opaque = opaque;

    piolist->name = name;

}


static int mch_init(PCIDevice *d)

{

    int i;

    hwaddr pci_hole64_size;

    MCHPCIState *mch = MCH_PCI_DEVICE(d);

    /* Leave enough space for the biggest MCFG BAR */

    /* TODO: this matches current bios behaviour, but

     * it's not a power of two, which means an MTRR

     * can't cover it exactly.

     */

    mch->guest_info->pci_info.w32.begin = MCH_HOST_BRIDGE_PCIEXBAR_DEFAULT +

        MCH_HOST_BRIDGE_PCIEXBAR_MAX;

    /* setup pci memory regions */

    memory_region_init_alias(&mch->pci_hole, OBJECT(mch), "pci-hole",

                             mch->pci_address_space,

                             mch->below_4g_mem_size,

                             0x100000000ULL - mch->below_4g_mem_size);

    memory_region_add_subregion(mch->system_memory, mch->below_4g_mem_size,

                                &mch->pci_hole);

    pci_hole64_size = (sizeof(hwaddr) == 4 ? 0 :

                       ((uint64_t)1 << 62));

    memory_region_init_alias(&mch->pci_hole_64bit, OBJECT(mch), "pci-hole64",

                             mch->pci_address_space,

                             0x100000000ULL + mch->above_4g_mem_size,

                             pci_hole64_size);

    if (pci_hole64_size) {

        memory_region_add_subregion(mch->system_memory,

                                    0x100000000ULL + mch->above_4g_mem_size,

                                    &mch->pci_hole_64bit);

    }

    /* smram */

    cpu_smm_register(&mch_set_smm, mch);

    memory_region_init_alias(&mch->smram_region, OBJECT(mch), "smram-region",

                             mch->pci_address_space, 0xa0000, 0x20000);

    memory_region_add_subregion_overlap(mch->system_memory, 0xa0000,

                                        &mch->smram_region, 1);

    memory_region_set_enabled(&mch->smram_region, false);

    init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory, mch->pci_address_space,

             &mch->pam_regions[0], PAM_BIOS_BASE, PAM_BIOS_SIZE);

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

        init_pam(DEVICE(mch), mch->ram_memory, mch->system_memory, mch->pci_address_space,

                 &mch->pam_regions[i+1], PAM_EXPAN_BASE + i * PAM_EXPAN_SIZE,

                 PAM_EXPAN_SIZE);

    }

    return 0;

}


static void gen_mtsr(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    t0 = tcg_const_tl(SR(ctx->opcode));

    gen_helper_store_sr(cpu_env, t0, cpu_gpr[rS(ctx->opcode)]);

    tcg_temp_free(t0);

#endif

}


static int get_codec_data(ByteIOContext *pb, AVStream *vst,

                          AVStream *ast, int myth) {

    frametype_t frametype;

    if (!vst && !myth)

        return 1; // no codec data needed

    while (!url_feof(pb)) {

        int size, subtype;

        frametype = get_byte(pb);

        switch (frametype) {

            case NUV_EXTRADATA:

                subtype = get_byte(pb);

                url_fskip(pb, 6);

                size = PKTSIZE(get_le32(pb));

                if (subtype == 'R') {

                    vst->codec->extradata_size = size;

                    vst->codec->extradata = av_malloc(size);

                    get_buffer(pb, vst->codec->extradata, size);

                    size = 0;

                    if (!myth)

                        return 1;

                }

                break;

            case NUV_MYTHEXT:

                url_fskip(pb, 7);

                size = PKTSIZE(get_le32(pb));

                if (size != 128 * 4)

                    break;

                get_le32(pb); // version

                if (vst) {

                    vst->codec->codec_tag = get_le32(pb);

                    vst->codec->codec_id =

                        codec_get_id(codec_bmp_tags, vst->codec->codec_tag);

                } else

                    url_fskip(pb, 4);

                if (ast) {

                    ast->codec->codec_tag = get_le32(pb);

                    ast->codec->sample_rate = get_le32(pb);

                    ast->codec->bits_per_sample = get_le32(pb);

                    ast->codec->channels = get_le32(pb);

                    ast->codec->codec_id =

                        wav_codec_get_id(ast->codec->codec_tag,

                                         ast->codec->bits_per_sample);

                } else

                    url_fskip(pb, 4 * 4);

                size -= 6 * 4;

                url_fskip(pb, size);

                return 1;

            case NUV_SEEKP:

                size = 11;

                break;

            default:

                url_fskip(pb, 7);

                size = PKTSIZE(get_le32(pb));

                break;

        }

        url_fskip(pb, size);

    }

    return 0;

}


static inline void RENAME(rgb24to15)(const uint8_t *src, uint8_t *dst, unsigned src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

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

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

	    ::"m"(red_15mask),"m"(green_15mask));

	mm_end = end - 11;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

		"movd	3%1, %%mm3\n\t"

		"punpckldq 6%1, %%mm0\n\t"

		"punpckldq 9%1, %%mm3\n\t"

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

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

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

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

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

		"psrlq	$3, %%mm3\n\t"

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

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

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

		"psrlq	$6, %%mm4\n\t"

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

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

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

		"psrlq	$9, %%mm5\n\t"

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

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

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

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

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

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

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

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

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");

		d += 4;

		s += 12;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		const int b= *s++;

		const int g= *s++;

		const int r= *s++;

		*d++ = (b>>3) | ((g&0xF8)<<2) | ((r&0xF8)<<7);

	}

}


static int rsd_read_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    int i, ret, version, start = 0x800;

    AVCodecParameters *par;

    AVStream *st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avio_skip(pb, 3); // "RSD"

    version = avio_r8(pb) - '0';

    par = st->codecpar;

    par->codec_type = AVMEDIA_TYPE_AUDIO;

    par->codec_tag  = avio_rl32(pb);

    par->codec_id   = ff_codec_get_id(rsd_tags, par->codec_tag);

    if (!par->codec_id) {

        char tag_buf[32];

        av_get_codec_tag_string(tag_buf, sizeof(tag_buf), par->codec_tag);

        for (i=0; i < FF_ARRAY_ELEMS(rsd_unsupported_tags); i++) {

            if (par->codec_tag == rsd_unsupported_tags[i]) {

                avpriv_request_sample(s, "Codec tag: %s", tag_buf);

                return AVERROR_PATCHWELCOME;

            }

        }

        av_log(s, AV_LOG_ERROR, "Unknown codec tag: %s\n", tag_buf);

        return AVERROR_INVALIDDATA;

    }

    par->channels = avio_rl32(pb);

    if (!par->channels)

        return AVERROR_INVALIDDATA;

    avio_skip(pb, 4); // Bit depth

    par->sample_rate = avio_rl32(pb);

    if (!par->sample_rate)

        return AVERROR_INVALIDDATA;

    avio_skip(pb, 4); // Unknown

    switch (par->codec_id) {

    case AV_CODEC_ID_XMA2:

        par->block_align = 2048;

        ff_alloc_extradata(par, 34);

        if (!par->extradata)

            return AVERROR(ENOMEM);

        memset(par->extradata, 0, 34);

        break;

    case AV_CODEC_ID_ADPCM_PSX:

        par->block_align = 16 * par->channels;

        if (pb->seekable)

            st->duration = av_get_audio_frame_duration2(par, avio_size(pb) - start);

        break;

    case AV_CODEC_ID_ADPCM_IMA_RAD:

        par->block_align = 20 * par->channels;

        if (pb->seekable)

            st->duration = av_get_audio_frame_duration2(par, avio_size(pb) - start);

        break;

    case AV_CODEC_ID_ADPCM_IMA_WAV:

        if (version == 2)

            start = avio_rl32(pb);

        par->bits_per_coded_sample = 4;

        par->block_align = 36 * par->channels;

        if (pb->seekable)

            st->duration = av_get_audio_frame_duration2(par, avio_size(pb) - start);

        break;

    case AV_CODEC_ID_ADPCM_THP_LE:

        /* RSD3GADP is mono, so only alloc enough memory

           to store the coeff table for a single channel. */

        start = avio_rl32(pb);

        if ((ret = ff_get_extradata(s, par, s->pb, 32)) < 0)

            return ret;

        if (pb->seekable)

            st->duration = av_get_audio_frame_duration2(par, avio_size(pb) - start);

        break;

    case AV_CODEC_ID_ADPCM_THP:

        par->block_align = 8 * par->channels;

        avio_skip(s->pb, 0x1A4 - avio_tell(s->pb));

        if ((ret = ff_alloc_extradata(st->codecpar, 32 * par->channels)) < 0)

            return ret;

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

            avio_read(s->pb, st->codecpar->extradata + 32 * i, 32);

            avio_skip(s->pb, 8);

        }

        if (pb->seekable)

            st->duration = (avio_size(pb) - start) / (8 * par->channels) * 14;

        break;

    case AV_CODEC_ID_PCM_S16LE:

    case AV_CODEC_ID_PCM_S16BE:

        if (version != 4)

            start = avio_rl32(pb);

        if (pb->seekable)

            st->duration = (avio_size(pb) - start) / 2 / par->channels;

        break;

    }

    avio_skip(pb, start - avio_tell(pb));

    if (par->codec_id == AV_CODEC_ID_XMA2) {

        avio_skip(pb, avio_rb32(pb) + avio_rb32(pb));

        st->duration = avio_rb32(pb);

    }

    avpriv_set_pts_info(st, 64, 1, par->sample_rate);

    return 0;

}


static void device_initfn(Object *obj)

{

    DeviceState *dev = DEVICE(obj);

    ObjectClass *class;

    Property *prop;

    if (qdev_hotplug) {

        dev->hotplugged = 1;

        qdev_hot_added = true;

    }

    dev->instance_id_alias = -1;

    dev->realized = false;

    object_property_add_bool(obj, "realized",

                             device_get_realized, device_set_realized, NULL);

    object_property_add_bool(obj, "hotpluggable",

                             device_get_hotpluggable, NULL, NULL);

    object_property_add_bool(obj, "hotplugged",

                             device_get_hotplugged, device_set_hotplugged,

                             &error_abort);

    class = object_get_class(OBJECT(dev));

    do {

        for (prop = DEVICE_CLASS(class)->props; prop && prop->name; prop++) {

            qdev_property_add_legacy(dev, prop, &error_abort);

            qdev_property_add_static(dev, prop, &error_abort);

        }

        class = object_class_get_parent(class);

    } while (class != object_class_by_name(TYPE_DEVICE));

    object_property_add_link(OBJECT(dev), "parent_bus", TYPE_BUS,

                             (Object **)&dev->parent_bus, NULL, 0,

                             &error_abort);

    QLIST_INIT(&dev->gpios);

}


static int http_prepare_data(HTTPContext *c)

{

    int i, len, ret;

    AVFormatContext *ctx;

    switch(c->state) {

    case HTTPSTATE_SEND_DATA_HEADER:

        memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));

        pstrcpy(c->fmt_ctx.author, sizeof(c->fmt_ctx.author),

                c->stream->author);

        pstrcpy(c->fmt_ctx.comment, sizeof(c->fmt_ctx.comment),

                c->stream->comment);

        pstrcpy(c->fmt_ctx.copyright, sizeof(c->fmt_ctx.copyright),

                c->stream->copyright);

        pstrcpy(c->fmt_ctx.title, sizeof(c->fmt_ctx.title),

                c->stream->title);

        /* open output stream by using specified codecs */

        c->fmt_ctx.oformat = c->stream->fmt;

        c->fmt_ctx.nb_streams = c->stream->nb_streams;

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

            AVStream *st;

            st = av_mallocz(sizeof(AVStream));

            c->fmt_ctx.streams[i] = st;

            /* if file or feed, then just take streams from FFStream struct */

            if (!c->stream->feed ||

                c->stream->feed == c->stream)

                memcpy(st, c->stream->streams[i], sizeof(AVStream));

            else

                memcpy(st, c->stream->feed->streams[c->stream->feed_streams[i]],

                           sizeof(AVStream));

            st->codec.frame_number = 0; /* XXX: should be done in

                                           AVStream, not in codec */

        }

        c->got_key_frame = 0;

        /* prepare header and save header data in a stream */

        if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {

            /* XXX: potential leak */

            return -1;

        }

        c->fmt_ctx.pb.is_streamed = 1;

        av_write_header(&c->fmt_ctx);

        len = url_close_dyn_buf(&c->fmt_ctx.pb, &c->pb_buffer);

        c->buffer_ptr = c->pb_buffer;

        c->buffer_end = c->pb_buffer + len;

        c->state = HTTPSTATE_SEND_DATA;

        c->last_packet_sent = 0;

        break;

    case HTTPSTATE_SEND_DATA:

        /* find a new packet */

        {

            AVPacket pkt;

            /* read a packet from the input stream */

            if (c->stream->feed) {

                ffm_set_write_index(c->fmt_in,

                                    c->stream->feed->feed_write_index,

                                    c->stream->feed->feed_size);

            }

            if (c->stream->max_time &&

                c->stream->max_time + c->start_time - cur_time < 0) {

                /* We have timed out */

                c->state = HTTPSTATE_SEND_DATA_TRAILER;

            } else {

                if (c->is_packetized) {

                    if (compute_send_delay(c) > 0) {

                        c->state = HTTPSTATE_WAIT;

                        return 1; /* state changed */

                    }

                }

                if (av_read_frame(c->fmt_in, &pkt) < 0) {

                    if (c->stream->feed && c->stream->feed->feed_opened) {

                        /* if coming from feed, it means we reached the end of the

                           ffm file, so must wait for more data */

                        c->state = HTTPSTATE_WAIT_FEED;

                        return 1; /* state changed */

                    } else {

                        /* must send trailer now because eof or error */

                        c->state = HTTPSTATE_SEND_DATA_TRAILER;

                    }

                } else {

                    /* update first pts if needed */

                    if (c->first_pts == AV_NOPTS_VALUE)

                        c->first_pts = pkt.pts;

                    /* send it to the appropriate stream */

                    if (c->stream->feed) {

                        /* if coming from a feed, select the right stream */

                        if (c->switch_pending) {

                            c->switch_pending = 0;

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

                                if (c->switch_feed_streams[i] == pkt.stream_index) {

                                    if (pkt.flags & PKT_FLAG_KEY) {

                                        do_switch_stream(c, i);

                                    }

                                }

                                if (c->switch_feed_streams[i] >= 0) {

                                    c->switch_pending = 1;

                                }

                            }

                        }

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

                            if (c->feed_streams[i] == pkt.stream_index) {

                                pkt.stream_index = i;

                                if (pkt.flags & PKT_FLAG_KEY) {

                                    c->got_key_frame |= 1 << i;

                                }

                                /* See if we have all the key frames, then

                                 * we start to send. This logic is not quite

                                 * right, but it works for the case of a

                                 * single video stream with one or more

                                 * audio streams (for which every frame is

                                 * typically a key frame).

                                 */

                                if (!c->stream->send_on_key ||

                                    ((c->got_key_frame + 1) >> c->stream->nb_streams)) {

                                    goto send_it;

                                }

                            }

                        }

                    } else {

                        AVCodecContext *codec;

                    send_it:

                        /* specific handling for RTP: we use several

                           output stream (one for each RTP

                           connection). XXX: need more abstract handling */

                        if (c->is_packetized) {

                            c->packet_stream_index = pkt.stream_index;

                            ctx = c->rtp_ctx[c->packet_stream_index];

                            codec = &ctx->streams[0]->codec;

                        } else {

                            ctx = &c->fmt_ctx;

                            /* Fudge here */

                            codec = &ctx->streams[pkt.stream_index]->codec;

                        }

                        codec->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);

#ifdef PJSG

                        if (codec->codec_type == CODEC_TYPE_AUDIO) {

                            codec->frame_size = (codec->sample_rate * pkt.duration + 500000) / 1000000;

                            /* printf("Calculated size %d, from sr %d, duration %d\n", codec->frame_size, codec->sample_rate, pkt.duration); */

                        }

#endif

                        if (c->is_packetized) {

                            ret = url_open_dyn_packet_buf(&ctx->pb,

                                                          url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]));

                            c->packet_byte_count = 0;

                            c->packet_start_time_us = av_gettime();

                        } else {

                            ret = url_open_dyn_buf(&ctx->pb);

                        }

                        if (ret < 0) {

                            /* XXX: potential leak */

                            return -1;

                        }

                        if (av_write_packet(ctx, &pkt, pkt.pts)) {

                            c->state = HTTPSTATE_SEND_DATA_TRAILER;

                        }

                        len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);

                        c->buffer_ptr = c->pb_buffer;

                        c->buffer_end = c->pb_buffer + len;

                        codec->frame_number++;

                    }

#ifndef AV_READ_FRAME

                    av_free_packet(&pkt);

#endif

                }

            }

        }

        break;

    default:

    case HTTPSTATE_SEND_DATA_TRAILER:

        /* last packet test ? */

        if (c->last_packet_sent || c->is_packetized)

            return -1;

        ctx = &c->fmt_ctx;

        /* prepare header */

        if (url_open_dyn_buf(&ctx->pb) < 0) {

            /* XXX: potential leak */

            return -1;

        }

        av_write_trailer(ctx);

        len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);

        c->buffer_ptr = c->pb_buffer;

        c->buffer_end = c->pb_buffer + len;

        c->last_packet_sent = 1;

        break;

    }

    return 0;

}


static inline void cris_update_result(DisasContext *dc, TCGv res)

{

	if (dc->update_cc) {

		if (dc->cc_size == 4 &&

		    (dc->cc_op == CC_OP_SUB

		     || dc->cc_op == CC_OP_ADD))

			return;

		tcg_gen_mov_tl(cc_result, res);

	}

}


static inline TranslationBlock *tb_find_fast(CPUState *cpu,

                                             TranslationBlock *last_tb,

                                             int tb_exit)

{

    CPUArchState *env = (CPUArchState *)cpu->env_ptr;

    TranslationBlock *tb;

    target_ulong cs_base, pc;

    uint32_t flags;

    /* we record a subset of the CPU state. It will

       always be the same before a given translated block

       is executed. */

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

    tb_lock();

    tb = atomic_rcu_read(&cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)]);

    if (unlikely(!tb || tb->pc != pc || tb->cs_base != cs_base ||

                 tb->flags != flags)) {

        tb = tb_find_slow(cpu, pc, cs_base, flags);

    }

#ifndef CONFIG_USER_ONLY

    /* We don't take care of direct jumps when address mapping changes in

     * system emulation. So it's not safe to make a direct jump to a TB

     * spanning two pages because the mapping for the second page can change.

     */

    if (tb->page_addr[1] != -1) {

        last_tb = NULL;

    }

#endif

    /* See if we can patch the calling TB. */

    if (last_tb && !qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) {

        /* Check if translation buffer has been flushed */

        if (cpu->tb_flushed) {

            cpu->tb_flushed = false;

        } else {

            tb_add_jump(last_tb, tb_exit, tb);

        }

    }

    tb_unlock();

    return tb;

}


static int proxy_init(FsContext *ctx)

{

    V9fsProxy *proxy = g_malloc(sizeof(V9fsProxy));

    int sock_id;

    if (ctx->export_flags & V9FS_PROXY_SOCK_NAME) {

        sock_id = connect_namedsocket(ctx->fs_root);

    } else {

        sock_id = atoi(ctx->fs_root);

        if (sock_id < 0) {

            fprintf(stderr, "socket descriptor not initialized\n");

            return -1;

        }

    }

    g_free(ctx->fs_root);

    proxy->in_iovec.iov_base  = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);

    proxy->in_iovec.iov_len   = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;

    proxy->out_iovec.iov_base = g_malloc(PROXY_MAX_IO_SZ + PROXY_HDR_SZ);

    proxy->out_iovec.iov_len  = PROXY_MAX_IO_SZ + PROXY_HDR_SZ;

    ctx->private = proxy;

    proxy->sockfd = sock_id;

    qemu_mutex_init(&proxy->mutex);

    ctx->export_flags |= V9FS_PATHNAME_FSCONTEXT;

    ctx->exops.get_st_gen = proxy_ioc_getversion;

    return 0;

}


int kvm_arch_init(MachineState *ms, KVMState *s)

{

    MachineClass *mc = MACHINE_GET_CLASS(ms);

    mc->default_cpu_type = S390_CPU_TYPE_NAME("host");

    cap_sync_regs = kvm_check_extension(s, KVM_CAP_SYNC_REGS);

    cap_async_pf = kvm_check_extension(s, KVM_CAP_ASYNC_PF);

    cap_mem_op = kvm_check_extension(s, KVM_CAP_S390_MEM_OP);

    cap_s390_irq = kvm_check_extension(s, KVM_CAP_S390_INJECT_IRQ);

    if (!kvm_check_extension(s, KVM_CAP_S390_GMAP)

        || !kvm_check_extension(s, KVM_CAP_S390_COW)) {

        phys_mem_set_alloc(legacy_s390_alloc);

    }

    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_SIGP, 0);

    kvm_vm_enable_cap(s, KVM_CAP_S390_VECTOR_REGISTERS, 0);

    kvm_vm_enable_cap(s, KVM_CAP_S390_USER_STSI, 0);

    if (ri_allowed()) {

        if (kvm_vm_enable_cap(s, KVM_CAP_S390_RI, 0) == 0) {

            cap_ri = 1;

        }

    }

    if (gs_allowed()) {

        if (kvm_vm_enable_cap(s, KVM_CAP_S390_GS, 0) == 0) {

            cap_gs = 1;

        }

    }

    /*

     * The migration interface for ais was introduced with kernel 4.13

     * but the capability itself had been active since 4.12. As migration

     * support is considered necessary let's disable ais in the 2.10

     * machine.

     */

    /* kvm_vm_enable_cap(s, KVM_CAP_S390_AIS, 0); */

    return 0;

}


static void decode_fixed_sparse(AMRFixed *fixed_sparse, const uint16_t *pulses,

                                const enum Mode mode, const int subframe)

{

    av_assert1(MODE_4k75 <= mode && mode <= MODE_12k2);

    if (mode == MODE_12k2) {

        ff_decode_10_pulses_35bits(pulses, fixed_sparse, gray_decode, 5, 3);

    } else if (mode == MODE_10k2) {

        decode_8_pulses_31bits(pulses, fixed_sparse);

    } else {

        int *pulse_position = fixed_sparse->x;

        int i, pulse_subset;

        const int fixed_index = pulses[0];

        if (mode <= MODE_5k15) {

            pulse_subset      = ((fixed_index >> 3) & 8)     + (subframe << 1);

            pulse_position[0] = ( fixed_index       & 7) * 5 + track_position[pulse_subset];

            pulse_position[1] = ((fixed_index >> 3) & 7) * 5 + track_position[pulse_subset + 1];

            fixed_sparse->n = 2;

        } else if (mode == MODE_5k9) {

            pulse_subset      = ((fixed_index & 1) << 1) + 1;

            pulse_position[0] = ((fixed_index >> 1) & 7) * 5 + pulse_subset;

            pulse_subset      = (fixed_index  >> 4) & 3;

            pulse_position[1] = ((fixed_index >> 6) & 7) * 5 + pulse_subset + (pulse_subset == 3 ? 1 : 0);

            fixed_sparse->n = pulse_position[0] == pulse_position[1] ? 1 : 2;

        } else if (mode == MODE_6k7) {

            pulse_position[0] = (fixed_index        & 7) * 5;

            pulse_subset      = (fixed_index  >> 2) & 2;

            pulse_position[1] = ((fixed_index >> 4) & 7) * 5 + pulse_subset + 1;

            pulse_subset      = (fixed_index  >> 6) & 2;

            pulse_position[2] = ((fixed_index >> 8) & 7) * 5 + pulse_subset + 2;

            fixed_sparse->n = 3;

        } else { // mode <= MODE_7k95

            pulse_position[0] = gray_decode[ fixed_index        & 7];

            pulse_position[1] = gray_decode[(fixed_index >> 3)  & 7] + 1;

            pulse_position[2] = gray_decode[(fixed_index >> 6)  & 7] + 2;

            pulse_subset      = (fixed_index >> 9) & 1;

            pulse_position[3] = gray_decode[(fixed_index >> 10) & 7] + pulse_subset + 3;

            fixed_sparse->n = 4;

        }

        for (i = 0; i < fixed_sparse->n; i++)

            fixed_sparse->y[i] = (pulses[1] >> i) & 1 ? 1.0 : -1.0;

    }

}


static void cg3_reg_write(void *opaque, hwaddr addr, uint64_t val,

                          unsigned size)

{

    CG3State *s = opaque;

    uint8_t regval;

    int i;

    DPRINTF("write %" PRIx64 " to reg %" HWADDR_PRIx " size %d\n",

            val, addr, size);

    switch (addr) {

    case CG3_REG_BT458_ADDR:

        s->dac_index = val;

        s->dac_state = 0;

        break;

    case CG3_REG_BT458_COLMAP:

        /* This register can be written to as either a long word or a byte */

        if (size == 1) {

            val <<= 24;

        }

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

            regval = val >> 24;

            switch (s->dac_state) {

            case 0:

                s->r[s->dac_index] = regval;

                s->dac_state++;

                break;

            case 1:

                s->g[s->dac_index] = regval;

                s->dac_state++;

                break;

            case 2:

                s->b[s->dac_index] = regval;

                /* Index autoincrement */

                s->dac_index = (s->dac_index + 1) & 0xff;

            default:

                s->dac_state = 0;

                break;

            }

            val <<= 8;

        }

        s->full_update = 1;

        break;

    case CG3_REG_FBC_CTRL:

        s->regs[0] = val;

        break;

    case CG3_REG_FBC_STATUS:

        if (s->regs[1] & CG3_SR_PENDING_INT) {

            /* clear interrupt */

            s->regs[1] &= ~CG3_SR_PENDING_INT;

            qemu_irq_lower(s->irq);

        }

        break;

    case CG3_REG_FBC_CURSTART ... CG3_REG_SIZE:

        s->regs[addr - 0x10] = val;

        break;

    default:

        qemu_log_mask(LOG_UNIMP,

                  "cg3: Unimplemented register write "

                  "reg 0x%" HWADDR_PRIx " size 0x%x value 0x%" PRIx64 "\n",

                  addr, size, val);

        break;

    }

}


static void qxl_dirty_surfaces(PCIQXLDevice *qxl)

{

    intptr_t vram_start;

    int i;

    if (qxl->mode != QXL_MODE_NATIVE && qxl->mode != QXL_MODE_COMPAT) {

        return;

    }

    /* dirty the primary surface */

    qxl_set_dirty(&qxl->vga.vram, qxl->shadow_rom.draw_area_offset,

                  qxl->shadow_rom.surface0_area_size);

    vram_start =  (intptr_t)memory_region_get_ram_ptr(&qxl->vram_bar);

    /* dirty the off-screen surfaces */

    for (i = 0; i < qxl->ssd.num_surfaces; i++) {

        QXLSurfaceCmd *cmd;

        intptr_t surface_offset;

        int surface_size;

        if (qxl->guest_surfaces.cmds[i] == 0) {

            continue;

        }

        cmd = qxl_phys2virt(qxl, qxl->guest_surfaces.cmds[i],

                            MEMSLOT_GROUP_GUEST);

        assert(cmd);

        assert(cmd->type == QXL_SURFACE_CMD_CREATE);

        surface_offset = (intptr_t)qxl_phys2virt(qxl,

                                                 cmd->u.surface_create.data,

                                                 MEMSLOT_GROUP_GUEST);

        assert(surface_offset);

        surface_offset -= vram_start;

        surface_size = cmd->u.surface_create.height *

                       abs(cmd->u.surface_create.stride);

        trace_qxl_surfaces_dirty(qxl->id, i, (int)surface_offset, surface_size);

        qxl_set_dirty(&qxl->vram_bar, surface_offset, surface_size);

    }

}


VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)

{

    VirtIOBlock *s;

    static int virtio_blk_id;

    if (!blk->conf.bs) {

        error_report("drive property not set");

        return NULL;

    }

    if (!bdrv_is_inserted(blk->conf.bs)) {

        error_report("Device needs media, but drive is empty");

        return NULL;

    }

    blkconf_serial(&blk->conf, &blk->serial);

    if (blkconf_geometry(&blk->conf, NULL, 65535, 255, 255) < 0) {

        return NULL;

    }

    s = (VirtIOBlock *)virtio_common_init("virtio-blk", VIRTIO_ID_BLOCK,

                                          sizeof(struct virtio_blk_config),

                                          sizeof(VirtIOBlock));

    s->vdev.get_config = virtio_blk_update_config;

    s->vdev.set_config = virtio_blk_set_config;

    s->vdev.get_features = virtio_blk_get_features;

    s->vdev.set_status = virtio_blk_set_status;

    s->vdev.reset = virtio_blk_reset;

    s->bs = blk->conf.bs;

    s->conf = &blk->conf;

    s->blk = blk;

    s->rq = NULL;

    s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;

    s->vq = virtio_add_queue(&s->vdev, 128, virtio_blk_handle_output);

#ifdef CONFIG_VIRTIO_BLK_DATA_PLANE

    if (!virtio_blk_data_plane_create(&s->vdev, blk, &s->dataplane)) {

        virtio_cleanup(&s->vdev);

        return NULL;

    }

#endif

    qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);

    s->qdev = dev;

    register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,

                    virtio_blk_save, virtio_blk_load, s);

    bdrv_set_dev_ops(s->bs, &virtio_block_ops, s);

    bdrv_set_buffer_alignment(s->bs, s->conf->logical_block_size);

    bdrv_iostatus_enable(s->bs);

    add_boot_device_path(s->conf->bootindex, dev, "/disk@0,0");

    return &s->vdev;

}