static const uint8_t *read_huffman_tables(FourXContext *f,

                                          const uint8_t * const buf)

{

    int frequency[512] = { 0 };

    uint8_t flag[512];

    int up[512];

    uint8_t len_tab[257];

    int bits_tab[257];

    int start, end;

    const uint8_t *ptr = buf;

    int j;

    memset(up, -1, sizeof(up));

    start = *ptr++;

    end   = *ptr++;

    for (;;) {

        int i;

        for (i = start; i <= end; i++)

            frequency[i] = *ptr++;

        start = *ptr++;

        if (start == 0)

            break;

        end = *ptr++;

    }

    frequency[256] = 1;

    while ((ptr - buf) & 3)

        ptr++; // 4byte align

    for (j = 257; j < 512; j++) {

        int min_freq[2] = { 256 * 256, 256 * 256 };

        int smallest[2] = { 0, 0 };

        int i;

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

            if (frequency[i] == 0)

                continue;

            if (frequency[i] < min_freq[1]) {

                if (frequency[i] < min_freq[0]) {

                    min_freq[1] = min_freq[0];

                    smallest[1] = smallest[0];

                    min_freq[0] = frequency[i];

                    smallest[0] = i;

                } else {

                    min_freq[1] = frequency[i];

                    smallest[1] = i;

                }

            }

        }

        if (min_freq[1] == 256 * 256)

            break;

        frequency[j]           = min_freq[0] + min_freq[1];

        flag[smallest[0]]      = 0;

        flag[smallest[1]]      = 1;

        up[smallest[0]]        =

        up[smallest[1]]        = j;

        frequency[smallest[0]] = frequency[smallest[1]] = 0;

    }

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

        int node, len = 0, bits = 0;

        for (node = j; up[node] != -1; node = up[node]) {

            bits += flag[node] << len;

            len++;

            if (len > 31)

                // can this happen at all ?

                av_log(f->avctx, AV_LOG_ERROR,

                       "vlc length overflow\n");

        }

        bits_tab[j] = bits;

        len_tab[j]  = len;

    }

    if (init_vlc(&f->pre_vlc, ACDC_VLC_BITS, 257, len_tab, 1, 1,

                 bits_tab, 4, 4, 0))

        return NULL;

    return ptr;

}


void hmp_info_tlb(Monitor *mon, const QDict *qdict)

{

    CPUArchState *env1 = mon_get_cpu_env();

    dump_mmu((FILE*)mon, (fprintf_function)monitor_printf, env1);


int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                          AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    MJpegDecodeContext *s = avctx->priv_data;

    const uint8_t *buf_end, *buf_ptr;

    const uint8_t *unescaped_buf_ptr;

    int unescaped_buf_size;

    int start_code;

    int i, index;

    int ret = 0;

    AVFrame *picture = data;

    s->got_picture = 0; // picture from previous image can not be reused

    buf_ptr = buf;

    buf_end = buf + buf_size;

    while (buf_ptr < buf_end) {

        /* find start next marker */

        start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,

                                          &unescaped_buf_ptr,

                                          &unescaped_buf_size);

        /* EOF */

        if (start_code < 0) {

            goto the_end;

        } else if (unescaped_buf_size > (1U<<29)) {

            av_log(avctx, AV_LOG_ERROR, "MJPEG packet 0x%x too big (0x%x/0x%x), corrupt data?\n",

                   start_code, unescaped_buf_size, buf_size);

            return AVERROR_INVALIDDATA;

        } else {

            av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",

                   start_code, buf_end - buf_ptr);

            init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size * 8);

            s->start_code = start_code;

            if (s->avctx->debug & FF_DEBUG_STARTCODE)

                av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);

            /* process markers */

            if (start_code >= 0xd0 && start_code <= 0xd7)

                av_log(avctx, AV_LOG_DEBUG,

                       "restart marker: %d\n", start_code & 0x0f);

                /* APP fields */

            else if (start_code >= APP0 && start_code <= APP15)

                mjpeg_decode_app(s);

                /* Comment */

            else if (start_code == COM)

                mjpeg_decode_com(s);

            switch (start_code) {

            case SOI:

                s->restart_interval = 0;

                s->restart_count    = 0;

                /* nothing to do on SOI */

                break;

            case DQT:

                ff_mjpeg_decode_dqt(s);

                break;

            case DHT:

                if ((ret = ff_mjpeg_decode_dht(s)) < 0) {

                    av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");

                    return ret;

                }

                break;

            case SOF0:

            case SOF1:

                s->lossless    = 0;

                s->ls          = 0;

                s->progressive = 0;

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

                    return ret;

                break;

            case SOF2:

                s->lossless    = 0;

                s->ls          = 0;

                s->progressive = 1;

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

                    return ret;

                break;

            case SOF3:

                s->lossless    = 1;

                s->ls          = 0;

                s->progressive = 0;

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

                    return ret;

                break;

            case SOF48:

                s->lossless    = 1;

                s->ls          = 1;

                s->progressive = 0;

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

                    return ret;

                break;

            case LSE:

                if (!CONFIG_JPEGLS_DECODER ||

                    (ret = ff_jpegls_decode_lse(s)) < 0)

                    return ret;

                break;

            case EOI:

eoi_parser:

                s->cur_scan = 0;

                if (!s->got_picture) {

                    av_log(avctx, AV_LOG_WARNING,

                           "Found EOI before any SOF, ignoring\n");

                    break;

                }

                if (s->interlaced) {

                    s->bottom_field ^= 1;

                    /* if not bottom field, do not output image yet */

                    if (s->bottom_field == !s->interlace_polarity)

                        break;

                }

                    *picture   = *s->picture_ptr;

                    *data_size = sizeof(AVFrame);

                    if (!s->lossless) {

                        picture->quality      = FFMAX3(s->qscale[0],

                                                       s->qscale[1],

                                                       s->qscale[2]);

                        picture->qstride      = 0;

                        picture->qscale_table = s->qscale_table;

                        memset(picture->qscale_table, picture->quality,

                               (s->width + 15) / 16);

                        if (avctx->debug & FF_DEBUG_QP)

                            av_log(avctx, AV_LOG_DEBUG,

                                   "QP: %d\n", picture->quality);

                        picture->quality *= FF_QP2LAMBDA;

                    }

                goto the_end;

            case SOS:

                if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&

                    (avctx->err_recognition & AV_EF_EXPLODE))

                    return ret;

                break;

            case DRI:

                mjpeg_decode_dri(s);

                break;

            case SOF5:

            case SOF6:

            case SOF7:

            case SOF9:

            case SOF10:

            case SOF11:

            case SOF13:

            case SOF14:

            case SOF15:

            case JPG:

                av_log(avctx, AV_LOG_ERROR,

                       "mjpeg: unsupported coding type (%x)\n", start_code);

                break;

            }

            /* eof process start code */

            buf_ptr += (get_bits_count(&s->gb) + 7) / 8;

            av_log(avctx, AV_LOG_DEBUG,

                   "marker parser used %d bytes (%d bits)\n",

                   (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));

        }

    }

    if (s->got_picture) {

        av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");

        goto eoi_parser;

    }

    av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");

    return AVERROR_INVALIDDATA;

the_end:

    if (s->upscale_h) {

        uint8_t *line = s->picture_ptr->data[s->upscale_h];

        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV440P);

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

            for (index = s->width - 1; index; index--)

                line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;

            line += s->linesize[s->upscale_h];

        }

    }

    if (s->upscale_v) {

        uint8_t *dst = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(s->height - 1) * s->linesize[s->upscale_v]];

        av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV444P  ||

                   avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||

                   avctx->pix_fmt == AV_PIX_FMT_YUV422P);

        for (i = s->height - 1; i; i--) {

            uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[i / 2 * s->linesize[s->upscale_v]];

            uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[s->upscale_v])[(i + 1) / 2 * s->linesize[s->upscale_v]];

            if (src1 == src2) {

                memcpy(dst, src1, s->width);

            } else {

                for (index = 0; index < s->width; index++)

                    dst[index] = (src1[index] + src2[index]) >> 1;

            }

            dst -= s->linesize[s->upscale_v];

        }

    }

    if (s->flipped && (s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {

        int hshift, vshift, j;

        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);

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

            uint8_t *dst = s->picture_ptr->data[index];

            int w = s->width;

            int h = s->height;

            if(index && index<3){

                w = -((-w) >> hshift);

                h = -((-h) >> vshift);

            }

            if(dst){

                uint8_t *dst2 = dst + s->linesize[index]*(h-1);

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

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

                        FFSWAP(int, dst[j], dst2[j]);

                    dst  += s->linesize[index];

                    dst2 -= s->linesize[index];

                }

            }

        }

    }

    av_log(avctx, AV_LOG_DEBUG, "decode frame unused %td bytes\n",

           buf_end - buf_ptr);

//  return buf_end - buf_ptr;

    return buf_ptr - buf;

}


GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)

{

    GuestMemoryBlockList *head, **link;

    Error *local_err = NULL;

    struct dirent *de;

    DIR *dp;

    head = NULL;

    link = &head;

    dp = opendir("/sys/devices/system/memory/");

    if (!dp) {

        error_setg_errno(errp, errno, "Can't open directory"

                         "\"/sys/devices/system/memory/\"\n");

        return NULL;

    }

    /* Note: the phys_index of memory block may be discontinuous,

     * this is because a memblk is the unit of the Sparse Memory design, which

     * allows discontinuous memory ranges (ex. NUMA), so here we should

     * traverse the memory block directory.

     */

    while ((de = readdir(dp)) != NULL) {

        GuestMemoryBlock *mem_blk;

        GuestMemoryBlockList *entry;

        if ((strncmp(de->d_name, "memory", 6) != 0) ||

            !(de->d_type & DT_DIR)) {

            continue;

        }

        mem_blk = g_malloc0(sizeof *mem_blk);

        /* The d_name is "memoryXXX",  phys_index is block id, same as XXX */

        mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);

        mem_blk->has_can_offline = true; /* lolspeak ftw */

        transfer_memory_block(mem_blk, true, NULL, &local_err);

        entry = g_malloc0(sizeof *entry);

        entry->value = mem_blk;

        *link = entry;

        link = &entry->next;

    }

    closedir(dp);

    if (local_err == NULL) {

        /* there's no guest with zero memory blocks */

        if (head == NULL) {

            error_setg(errp, "guest reported zero memory blocks!");

        }

        return head;

    }

    qapi_free_GuestMemoryBlockList(head);

    error_propagate(errp, local_err);

    return NULL;

}


int qcrypto_cipher_decrypt(QCryptoCipher *cipher,
                           const void *in,
                           void *out,
                           size_t len,
                           Error **errp)
{
    QCryptoCipherBuiltin *ctxt = cipher->opaque;
    return ctxt->decrypt(cipher, in, out, len, errp);


static int get_blocksize(BlockDriverState *bdrv)

{

    uint8_t cmd[10];

    uint8_t buf[8];

    uint8_t sensebuf[8];

    sg_io_hdr_t io_header;

    int ret;

    memset(cmd, 0, sizeof(cmd));

    memset(buf, 0, sizeof(buf));

    cmd[0] = READ_CAPACITY;

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

    io_header.interface_id = 'S';

    io_header.dxfer_direction = SG_DXFER_FROM_DEV;

    io_header.dxfer_len = sizeof(buf);

    io_header.dxferp = buf;

    io_header.cmdp = cmd;

    io_header.cmd_len = sizeof(cmd);

    io_header.mx_sb_len = sizeof(sensebuf);

    io_header.sbp = sensebuf;

    io_header.timeout = 6000; /* XXX */

    ret = bdrv_ioctl(bdrv, SG_IO, &io_header);

    if (ret < 0)

        return -1;

    return (buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7];

}


static int svq1_decode_block_non_intra(GetBitContext *bitbuf, uint8_t *pixels,

                                       ptrdiff_t pitch)

{

    uint32_t bit_cache;

    uint8_t *list[63];

    uint32_t *dst;

    const uint32_t *codebook;

    int entries[6];

    int i, j, m, n;

    int stages;

    unsigned mean;

    int x, y, width, height, level;

    uint32_t n1, n2, n3, n4;

    /* initialize list for breadth first processing of vectors */

    list[0] = pixels;

    /* recursively process vector */

    for (i = 0, m = 1, n = 1, level = 5; i < n; i++) {

        SVQ1_PROCESS_VECTOR();

        /* destination address and vector size */

        dst    = (uint32_t *)list[i];

        width  = 1 << ((4 + level) / 2);

        height = 1 << ((3 + level) / 2);

        /* get number of stages (-1 skips vector, 0 for mean only) */

        stages = get_vlc2(bitbuf, svq1_inter_multistage[level].table, 3, 2) - 1;

        if (stages == -1)

            continue;           /* skip vector */

        if ((stages > 0 && level >= 4)) {

            ff_dlog(NULL,

                    "Error (svq1_decode_block_non_intra): invalid vector: stages=%i level=%i\n",

                    stages, level);

            return AVERROR_INVALIDDATA;  /* invalid vector */

        }

        av_assert0(stages >= 0);

        mean = get_vlc2(bitbuf, svq1_inter_mean.table, 9, 3) - 256;

        SVQ1_CALC_CODEBOOK_ENTRIES(ff_svq1_inter_codebooks);

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

            for (x = 0; x < width / 4; x++, codebook++) {

                n3 = dst[x];

                /* add mean value to vector */

                n1 = n4 + ((n3 & 0xFF00FF00) >> 8);

                n2 = n4 +  (n3 & 0x00FF00FF);

                SVQ1_ADD_CODEBOOK()

                /* store result */

                dst[x] = n1 << 8 | n2;

            }

            dst += pitch / 4;

        }

    }

    return 0;

}


void do_interrupt (CPUState *env)

{

#if !defined(CONFIG_USER_ONLY)

    target_ulong offset;

    int cause = -1;

    const char *name;

    if (qemu_log_enabled() && env->exception_index != EXCP_EXT_INTERRUPT) {

        if (env->exception_index < 0 || env->exception_index > EXCP_LAST)

            name = "unknown";

        else

            name = excp_names[env->exception_index];

        qemu_log("%s enter: PC " TARGET_FMT_lx " EPC " TARGET_FMT_lx " %s exception\n",

                 __func__, env->active_tc.PC, env->CP0_EPC, name);

    }

    if (env->exception_index == EXCP_EXT_INTERRUPT &&

        (env->hflags & MIPS_HFLAG_DM))

        env->exception_index = EXCP_DINT;

    offset = 0x180;

    switch (env->exception_index) {

    case EXCP_DSS:

        env->CP0_Debug |= 1 << CP0DB_DSS;

        /* Debug single step cannot be raised inside a delay slot and

           resume will always occur on the next instruction

           (but we assume the pc has always been updated during

           code translation). */

        env->CP0_DEPC = env->active_tc.PC | !!(env->hflags & MIPS_HFLAG_M16);

        goto enter_debug_mode;

    case EXCP_DINT:

        env->CP0_Debug |= 1 << CP0DB_DINT;

        goto set_DEPC;

    case EXCP_DIB:

        env->CP0_Debug |= 1 << CP0DB_DIB;

        goto set_DEPC;

    case EXCP_DBp:

        env->CP0_Debug |= 1 << CP0DB_DBp;

        goto set_DEPC;

    case EXCP_DDBS:

        env->CP0_Debug |= 1 << CP0DB_DDBS;

        goto set_DEPC;

    case EXCP_DDBL:

        env->CP0_Debug |= 1 << CP0DB_DDBL;

    set_DEPC:

        env->CP0_DEPC = exception_resume_pc(env);

        env->hflags &= ~MIPS_HFLAG_BMASK;

 enter_debug_mode:

        env->hflags |= MIPS_HFLAG_DM | MIPS_HFLAG_64 | MIPS_HFLAG_CP0;

        env->hflags &= ~(MIPS_HFLAG_KSU);

        /* EJTAG probe trap enable is not implemented... */

        if (!(env->CP0_Status & (1 << CP0St_EXL)))

            env->CP0_Cause &= ~(1 << CP0Ca_BD);

        env->active_tc.PC = (int32_t)0xBFC00480;

        set_hflags_for_handler(env);

        break;

    case EXCP_RESET:

        cpu_reset(env);

        break;

    case EXCP_SRESET:

        env->CP0_Status |= (1 << CP0St_SR);

        memset(env->CP0_WatchLo, 0, sizeof(*env->CP0_WatchLo));

        goto set_error_EPC;

    case EXCP_NMI:

        env->CP0_Status |= (1 << CP0St_NMI);

 set_error_EPC:

        env->CP0_ErrorEPC = exception_resume_pc(env);

        env->hflags &= ~MIPS_HFLAG_BMASK;

        env->CP0_Status |= (1 << CP0St_ERL) | (1 << CP0St_BEV);

        env->hflags |= MIPS_HFLAG_64 | MIPS_HFLAG_CP0;

        env->hflags &= ~(MIPS_HFLAG_KSU);

        if (!(env->CP0_Status & (1 << CP0St_EXL)))

            env->CP0_Cause &= ~(1 << CP0Ca_BD);

        env->active_tc.PC = (int32_t)0xBFC00000;

        set_hflags_for_handler(env);

        break;

    case EXCP_EXT_INTERRUPT:

        cause = 0;

        if (env->CP0_Cause & (1 << CP0Ca_IV))

            offset = 0x200;

        if (env->CP0_Config3 & ((1 << CP0C3_VInt) | (1 << CP0C3_VEIC))) {

            /* Vectored Interrupts.  */

            unsigned int spacing;

            unsigned int vector;

            unsigned int pending = (env->CP0_Cause & CP0Ca_IP_mask) >> 8;

            pending &= env->CP0_Status >> 8;

            /* Compute the Vector Spacing.  */

            spacing = (env->CP0_IntCtl >> CP0IntCtl_VS) & ((1 << 6) - 1);

            spacing <<= 5;

            if (env->CP0_Config3 & (1 << CP0C3_VInt)) {

                /* For VInt mode, the MIPS computes the vector internally.  */

                for (vector = 7; vector > 0; vector--) {

                    if (pending & (1 << vector)) {

                        /* Found it.  */

                        break;

                    }

                }

            } else {

                /* For VEIC mode, the external interrupt controller feeds the

                   vector throught the CP0Cause IP lines.  */

                vector = pending;

            }

            offset = 0x200 + vector * spacing;

        }

        goto set_EPC;

    case EXCP_LTLBL:

        cause = 1;

        goto set_EPC;

    case EXCP_TLBL:

        cause = 2;

        if (env->error_code == 1 && !(env->CP0_Status & (1 << CP0St_EXL))) {

#if defined(TARGET_MIPS64)

            int R = env->CP0_BadVAddr >> 62;

            int UX = (env->CP0_Status & (1 << CP0St_UX)) != 0;

            int SX = (env->CP0_Status & (1 << CP0St_SX)) != 0;

            int KX = (env->CP0_Status & (1 << CP0St_KX)) != 0;

            if (((R == 0 && UX) || (R == 1 && SX) || (R == 3 && KX)) &&

                (!(env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F))))

                offset = 0x080;

            else

#endif

                offset = 0x000;

        }

        goto set_EPC;

    case EXCP_TLBS:

        cause = 3;

        if (env->error_code == 1 && !(env->CP0_Status & (1 << CP0St_EXL))) {

#if defined(TARGET_MIPS64)

            int R = env->CP0_BadVAddr >> 62;

            int UX = (env->CP0_Status & (1 << CP0St_UX)) != 0;

            int SX = (env->CP0_Status & (1 << CP0St_SX)) != 0;

            int KX = (env->CP0_Status & (1 << CP0St_KX)) != 0;

            if (((R == 0 && UX) || (R == 1 && SX) || (R == 3 && KX)) &&

                (!(env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F))))

                offset = 0x080;

            else

#endif

                offset = 0x000;

        }

        goto set_EPC;

    case EXCP_AdEL:

        cause = 4;

        goto set_EPC;

    case EXCP_AdES:

        cause = 5;

        goto set_EPC;

    case EXCP_IBE:

        cause = 6;

        goto set_EPC;

    case EXCP_DBE:

        cause = 7;

        goto set_EPC;

    case EXCP_SYSCALL:

        cause = 8;

        goto set_EPC;

    case EXCP_BREAK:

        cause = 9;

        goto set_EPC;

    case EXCP_RI:

        cause = 10;

        goto set_EPC;

    case EXCP_CpU:

        cause = 11;

        env->CP0_Cause = (env->CP0_Cause & ~(0x3 << CP0Ca_CE)) |

                         (env->error_code << CP0Ca_CE);

        goto set_EPC;

    case EXCP_OVERFLOW:

        cause = 12;

        goto set_EPC;

    case EXCP_TRAP:

        cause = 13;

        goto set_EPC;

    case EXCP_FPE:

        cause = 15;

        goto set_EPC;

    case EXCP_C2E:

        cause = 18;

        goto set_EPC;

    case EXCP_MDMX:

        cause = 22;

        goto set_EPC;

    case EXCP_DWATCH:

        cause = 23;

        /* XXX: TODO: manage defered watch exceptions */

        goto set_EPC;

    case EXCP_MCHECK:

        cause = 24;

        goto set_EPC;

    case EXCP_THREAD:

        cause = 25;

        goto set_EPC;

    case EXCP_CACHE:

        cause = 30;

        if (env->CP0_Status & (1 << CP0St_BEV)) {

            offset = 0x100;

        } else {

            offset = 0x20000100;

        }

 set_EPC:

        if (!(env->CP0_Status & (1 << CP0St_EXL))) {

            env->CP0_EPC = exception_resume_pc(env);

            if (env->hflags & MIPS_HFLAG_BMASK) {

                env->CP0_Cause |= (1 << CP0Ca_BD);

            } else {

                env->CP0_Cause &= ~(1 << CP0Ca_BD);

            }

            env->CP0_Status |= (1 << CP0St_EXL);

            env->hflags |= MIPS_HFLAG_64 | MIPS_HFLAG_CP0;

            env->hflags &= ~(MIPS_HFLAG_KSU);

        }

        env->hflags &= ~MIPS_HFLAG_BMASK;

        if (env->CP0_Status & (1 << CP0St_BEV)) {

            env->active_tc.PC = (int32_t)0xBFC00200;

        } else {

            env->active_tc.PC = (int32_t)(env->CP0_EBase & ~0x3ff);

        }

        env->active_tc.PC += offset;

        set_hflags_for_handler(env);

        env->CP0_Cause = (env->CP0_Cause & ~(0x1f << CP0Ca_EC)) | (cause << CP0Ca_EC);

        break;

    default:

        qemu_log("Invalid MIPS exception %d. Exiting\n", env->exception_index);

        printf("Invalid MIPS exception %d. Exiting\n", env->exception_index);

        exit(1);

    }

    if (qemu_log_enabled() && env->exception_index != EXCP_EXT_INTERRUPT) {

        qemu_log("%s: PC " TARGET_FMT_lx " EPC " TARGET_FMT_lx " cause %d\n"

                "    S %08x C %08x A " TARGET_FMT_lx " D " TARGET_FMT_lx "\n",

                __func__, env->active_tc.PC, env->CP0_EPC, cause,

                env->CP0_Status, env->CP0_Cause, env->CP0_BadVAddr,

                env->CP0_DEPC);

    }

#endif

    env->exception_index = EXCP_NONE;

}


static int dxva2_h264_decode_slice(AVCodecContext *avctx,

                                   const uint8_t *buffer,

                                   uint32_t size)

{

    const H264Context *h = avctx->priv_data;

    struct dxva_context *ctx = avctx->hwaccel_context;

    const Picture *current_picture = h->cur_pic_ptr;

    struct dxva2_picture_context *ctx_pic = current_picture->hwaccel_picture_private;

    unsigned position;

    if (ctx_pic->slice_count >= MAX_SLICES)

        return -1;

    if (!ctx_pic->bitstream)

        ctx_pic->bitstream = buffer;

    ctx_pic->bitstream_size += size;

    position = buffer - ctx_pic->bitstream;

    if (is_slice_short(ctx))

        fill_slice_short(&ctx_pic->slice_short[ctx_pic->slice_count],

                         position, size);

    else

        fill_slice_long(avctx, &ctx_pic->slice_long[ctx_pic->slice_count],

                        position, size);

    ctx_pic->slice_count++;

    if (h->slice_type != AV_PICTURE_TYPE_I && h->slice_type != AV_PICTURE_TYPE_SI)

        ctx_pic->pp.wBitFields &= ~(1 << 15); /* Set IntraPicFlag to 0 */

    return 0;

}


static int wavpack_encode_block(WavPackEncodeContext *s,

                                int32_t *samples_l, int32_t *samples_r,

                                uint8_t *out, int out_size)

{

    int block_size, start, end, data_size, tcount, temp, m = 0;

    int i, j, ret = 0, got_extra = 0, nb_samples = s->block_samples;

    uint32_t crc = 0xffffffffu;

    struct Decorr *dpp;

    PutByteContext pb;

    if (!(s->flags & WV_MONO) && s->optimize_mono) {

        int32_t lor = 0, diff = 0;

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

            lor  |= samples_l[i] | samples_r[i];

            diff |= samples_l[i] - samples_r[i];

            if (lor && diff)

                break;

        }

        if (i == nb_samples && lor && !diff) {

            s->flags &= ~(WV_JOINT_STEREO | WV_CROSS_DECORR);

            s->flags |= WV_FALSE_STEREO;

            if (!s->false_stereo) {

                s->false_stereo = 1;

                s->num_terms = 0;

                CLEAR(s->w);

            }

        } else if (s->false_stereo) {

            s->false_stereo = 0;

            s->num_terms = 0;

            CLEAR(s->w);

        }

    }

    if (s->flags & SHIFT_MASK) {

        int shift = (s->flags & SHIFT_MASK) >> SHIFT_LSB;

        int mag = (s->flags & MAG_MASK) >> MAG_LSB;

        if (s->flags & WV_MONO_DATA)

            shift_mono(samples_l, nb_samples, shift);

        else

            shift_stereo(samples_l, samples_r, nb_samples, shift);

        if ((mag -= shift) < 0)

            s->flags &= ~MAG_MASK;

        else

            s->flags -= (1 << MAG_LSB) * shift;

    }

    if ((s->flags & WV_FLOAT_DATA) || (s->flags & MAG_MASK) >> MAG_LSB >= 24) {

        av_fast_padded_malloc(&s->orig_l, &s->orig_l_size, sizeof(int32_t) * nb_samples);

        memcpy(s->orig_l, samples_l, sizeof(int32_t) * nb_samples);

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

            av_fast_padded_malloc(&s->orig_r, &s->orig_r_size, sizeof(int32_t) * nb_samples);

            memcpy(s->orig_r, samples_r, sizeof(int32_t) * nb_samples);

        }

        if (s->flags & WV_FLOAT_DATA)

            got_extra = scan_float(s, samples_l, samples_r, nb_samples);

        else

            got_extra = scan_int32(s, samples_l, samples_r, nb_samples);

        s->num_terms = 0;

    } else {

        scan_int23(s, samples_l, samples_r, nb_samples);

        if (s->shift != s->int32_zeros + s->int32_ones + s->int32_dups) {

            s->shift = s->int32_zeros + s->int32_ones + s->int32_dups;

            s->num_terms = 0;

        }

    }

    if (!s->num_passes && !s->num_terms) {

        s->num_passes = 1;

        if (s->flags & WV_MONO_DATA)

            ret = wv_mono(s, samples_l, 1, 0);

        else

            ret = wv_stereo(s, samples_l, samples_r, 1, 0);

        s->num_passes = 0;

    }

    if (s->flags & WV_MONO_DATA) {

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

            crc += (crc << 1) + samples_l[i];

        if (s->num_passes)

            ret = wv_mono(s, samples_l, !s->num_terms, 1);

    } else {

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

            crc += (crc << 3) + (samples_l[i] << 1) + samples_l[i] + samples_r[i];

        if (s->num_passes)

            ret = wv_stereo(s, samples_l, samples_r, !s->num_terms, 1);

    }

    if (ret < 0)

        return ret;

    if (!s->ch_offset)

        s->flags |= WV_INITIAL_BLOCK;

    s->ch_offset += 1 + !(s->flags & WV_MONO);

    if (s->ch_offset == s->avctx->channels)

        s->flags |= WV_FINAL_BLOCK;

    bytestream2_init_writer(&pb, out, out_size);

    bytestream2_put_le32(&pb, MKTAG('w', 'v', 'p', 'k'));

    bytestream2_put_le32(&pb, 0);

    bytestream2_put_le16(&pb, 0x410);

    bytestream2_put_le16(&pb, 0);

    bytestream2_put_le32(&pb, 0);

    bytestream2_put_le32(&pb, s->sample_index);

    bytestream2_put_le32(&pb, nb_samples);

    bytestream2_put_le32(&pb, s->flags);

    bytestream2_put_le32(&pb, crc);

    if (s->flags & WV_INITIAL_BLOCK &&

        s->avctx->channel_layout != AV_CH_LAYOUT_MONO &&

        s->avctx->channel_layout != AV_CH_LAYOUT_STEREO) {

        put_metadata_block(&pb, WP_ID_CHANINFO, 5);

        bytestream2_put_byte(&pb, s->avctx->channels);

        bytestream2_put_le32(&pb, s->avctx->channel_layout);

        bytestream2_put_byte(&pb, 0);

    }

    if ((s->flags & SRATE_MASK) == SRATE_MASK) {

        put_metadata_block(&pb, WP_ID_SAMPLE_RATE, 3);

        bytestream2_put_le24(&pb, s->avctx->sample_rate);

        bytestream2_put_byte(&pb, 0);

    }

    put_metadata_block(&pb, WP_ID_DECTERMS, s->num_terms);

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

        struct Decorr *dpp = &s->decorr_passes[i];

        bytestream2_put_byte(&pb, ((dpp->value + 5) & 0x1f) | ((dpp->delta << 5) & 0xe0));

    }

    if (s->num_terms & 1)

        bytestream2_put_byte(&pb, 0);

#define WRITE_DECWEIGHT(type) do {            \

        temp = store_weight(type);    \

        bytestream2_put_byte(&pb, temp);      \

        type = restore_weight(temp);  \

    } while (0)

    bytestream2_put_byte(&pb, WP_ID_DECWEIGHTS);

    bytestream2_put_byte(&pb, 0);

    start = bytestream2_tell_p(&pb);

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

        struct Decorr *dpp = &s->decorr_passes[i];

        if (store_weight(dpp->weightA) ||

            (!(s->flags & WV_MONO_DATA) && store_weight(dpp->weightB)))

                break;

    }

    tcount = i + 1;

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

        struct Decorr *dpp = &s->decorr_passes[i];

        if (i < tcount) {

            WRITE_DECWEIGHT(dpp->weightA);

            if (!(s->flags & WV_MONO_DATA))

                WRITE_DECWEIGHT(dpp->weightB);

        } else {

            dpp->weightA = dpp->weightB = 0;

        }

    }

    end = bytestream2_tell_p(&pb);

    out[start - 2] = WP_ID_DECWEIGHTS | (((end - start) & 1) ? WP_IDF_ODD: 0);

    out[start - 1] = (end - start + 1) >> 1;

    if ((end - start) & 1)

        bytestream2_put_byte(&pb, 0);

#define WRITE_DECSAMPLE(type) do {        \

        temp = log2s(type);               \

        type = wp_exp2(temp);             \

        bytestream2_put_le16(&pb, temp);  \

    } while (0)

    bytestream2_put_byte(&pb, WP_ID_DECSAMPLES);

    bytestream2_put_byte(&pb, 0);

    start = bytestream2_tell_p(&pb);

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

        struct Decorr *dpp = &s->decorr_passes[i];

        if (i == 0) {

            if (dpp->value > MAX_TERM) {

                WRITE_DECSAMPLE(dpp->samplesA[0]);

                WRITE_DECSAMPLE(dpp->samplesA[1]);

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

                    WRITE_DECSAMPLE(dpp->samplesB[0]);

                    WRITE_DECSAMPLE(dpp->samplesB[1]);

                }

            } else if (dpp->value < 0) {

                WRITE_DECSAMPLE(dpp->samplesA[0]);

                WRITE_DECSAMPLE(dpp->samplesB[0]);

            } else {

                for (j = 0; j < dpp->value; j++) {

                    WRITE_DECSAMPLE(dpp->samplesA[j]);

                    if (!(s->flags & WV_MONO_DATA))

                        WRITE_DECSAMPLE(dpp->samplesB[j]);

                }

            }

        } else {

            CLEAR(dpp->samplesA);

            CLEAR(dpp->samplesB);

        }

    }

    end = bytestream2_tell_p(&pb);

    out[start - 1] = (end - start) >> 1;

#define WRITE_CHAN_ENTROPY(chan) do {               \

        for (i = 0; i < 3; i++) {                   \

            temp = wp_log2(s->w.c[chan].median[i]); \

            bytestream2_put_le16(&pb, temp);        \

            s->w.c[chan].median[i] = wp_exp2(temp); \

        }                                           \

    } while (0)

    put_metadata_block(&pb, WP_ID_ENTROPY, 6 * (1 + (!(s->flags & WV_MONO_DATA))));

    WRITE_CHAN_ENTROPY(0);

    if (!(s->flags & WV_MONO_DATA))

        WRITE_CHAN_ENTROPY(1);

    if (s->flags & WV_FLOAT_DATA) {

        put_metadata_block(&pb, WP_ID_FLOATINFO, 4);

        bytestream2_put_byte(&pb, s->float_flags);

        bytestream2_put_byte(&pb, s->float_shift);

        bytestream2_put_byte(&pb, s->float_max_exp);

        bytestream2_put_byte(&pb, 127);

    }

    if (s->flags & WV_INT32_DATA) {

        put_metadata_block(&pb, WP_ID_INT32INFO, 4);

        bytestream2_put_byte(&pb, s->int32_sent_bits);

        bytestream2_put_byte(&pb, s->int32_zeros);

        bytestream2_put_byte(&pb, s->int32_ones);

        bytestream2_put_byte(&pb, s->int32_dups);

    }

    if (s->flags & WV_MONO_DATA && !s->num_passes) {

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

            int32_t code = samples_l[i];

            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++) {

                int32_t sam;

                if (dpp->value > MAX_TERM) {

                    if (dpp->value & 1)

                        sam = 2 * dpp->samplesA[0] - dpp->samplesA[1];

                    else

                        sam = (3 * dpp->samplesA[0] - dpp->samplesA[1]) >> 1;

                    dpp->samplesA[1] = dpp->samplesA[0];

                    dpp->samplesA[0] = code;

                } else {

                    sam = dpp->samplesA[m];

                    dpp->samplesA[(m + dpp->value) & (MAX_TERM - 1)] = code;

                }

                code -= APPLY_WEIGHT(dpp->weightA, sam);

                UPDATE_WEIGHT(dpp->weightA, dpp->delta, sam, code);

            }

            m = (m + 1) & (MAX_TERM - 1);

            samples_l[i] = code;

        }

        if (m) {

            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++)

                if (dpp->value > 0 && dpp->value <= MAX_TERM) {

                int32_t temp_A[MAX_TERM], temp_B[MAX_TERM];

                int k;

                memcpy(temp_A, dpp->samplesA, sizeof(dpp->samplesA));

                memcpy(temp_B, dpp->samplesB, sizeof(dpp->samplesB));

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

                    dpp->samplesA[k] = temp_A[m];

                    dpp->samplesB[k] = temp_B[m];

                    m = (m + 1) & (MAX_TERM - 1);

                }

            }

        }

    } else if (!s->num_passes) {

        if (s->flags & WV_JOINT_STEREO) {

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

                samples_r[i] += ((samples_l[i] -= samples_r[i]) >> 1);

        }

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

            struct Decorr *dpp = &s->decorr_passes[i];

            if (((s->flags & MAG_MASK) >> MAG_LSB) >= 16 || dpp->delta != 2)

                decorr_stereo_pass2(dpp, samples_l, samples_r, nb_samples);

            else

                decorr_stereo_pass_id2(dpp, samples_l, samples_r, nb_samples);

        }

    }

    bytestream2_put_byte(&pb, WP_ID_DATA | WP_IDF_LONG);

    init_put_bits(&s->pb, pb.buffer + 3, bytestream2_get_bytes_left_p(&pb));

    if (s->flags & WV_MONO_DATA) {

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

            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);

    } else {

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

            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);

            wavpack_encode_sample(s, &s->w.c[1], s->samples[1][i]);

        }

    }

    encode_flush(s);

    flush_put_bits(&s->pb);

    data_size = put_bits_count(&s->pb) >> 3;

    bytestream2_put_le24(&pb, (data_size + 1) >> 1);

    bytestream2_skip_p(&pb, data_size);

    if (data_size & 1)

        bytestream2_put_byte(&pb, 0);

    if (got_extra) {

        bytestream2_put_byte(&pb, WP_ID_EXTRABITS | WP_IDF_LONG);

        init_put_bits(&s->pb, pb.buffer + 7, bytestream2_get_bytes_left_p(&pb));

        if (s->flags & WV_FLOAT_DATA)

            pack_float(s, s->orig_l, s->orig_r, nb_samples);

        else

            pack_int32(s, s->orig_l, s->orig_r, nb_samples);

        flush_put_bits(&s->pb);

        data_size = put_bits_count(&s->pb) >> 3;

        bytestream2_put_le24(&pb, (data_size + 5) >> 1);

        bytestream2_put_le32(&pb, s->crc_x);

        bytestream2_skip_p(&pb, data_size);

        if (data_size & 1)

            bytestream2_put_byte(&pb, 0);

    }

    block_size = bytestream2_tell_p(&pb);

    AV_WL32(out + 4, block_size - 8);

    av_assert0(put_bits_left(&s->pb) > 0);

    return block_size;

}


static int mpegts_probe(AVProbeData *p)

{

    const int size = p->buf_size;

    int score, fec_score, dvhs_score;

    int check_count = size / TS_FEC_PACKET_SIZE;

#define CHECK_COUNT 10

    if (check_count < CHECK_COUNT)

        return AVERROR_INVALIDDATA;

    score = analyze(p->buf, TS_PACKET_SIZE * check_count,

                    TS_PACKET_SIZE, NULL) * CHECK_COUNT / check_count;

    dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE * check_count,

                         TS_DVHS_PACKET_SIZE, NULL) * CHECK_COUNT / check_count;

    fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE * check_count,

                        TS_FEC_PACKET_SIZE, NULL) * CHECK_COUNT / check_count;

    av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",

            score, dvhs_score, fec_score);

    /* we need a clear definition for the returned score otherwise

     * things will become messy sooner or later */

    if (score > fec_score && score > dvhs_score && score > 6)

        return AVPROBE_SCORE_MAX + score - CHECK_COUNT;

    else if (dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6)

        return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;

    else if (fec_score > 6)

        return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;

    else

        return AVERROR_INVALIDDATA;

}


static inline int l1_unscale(int n, int mant, int scale_factor)

{

    int shift, mod;

    int64_t val;

    shift   = scale_factor_modshift[scale_factor];

    mod     = shift & 3;

    shift >>= 2;

    val     = MUL64(mant + (-1 << n) + 1, scale_factor_mult[n-1][mod]);

    shift  += n;

    /* NOTE: at this point, 1 <= shift >= 21 + 15 */

    return (int)((val + (1LL << (shift - 1))) >> shift);

}


static int read_low_coeffs(AVCodecContext *avctx, int16_t *dst, int size, int width, ptrdiff_t stride)

{

    PixletContext *ctx = avctx->priv_data;

    GetBitContext *b = &ctx->gbit;

    unsigned cnt1, nbits, k, j = 0, i = 0;

    int64_t value, state = 3;

    int rlen, escape, flag = 0;

    while (i < size) {

        nbits = FFMIN(ff_clz((state >> 8) + 3) ^ 0x1F, 14);

        cnt1 = get_unary(b, 0, 8);

        if (cnt1 < 8) {

            value = show_bits(b, nbits);

            if (value <= 1) {

                skip_bits(b, nbits - 1);

                escape = ((1 << nbits) - 1) * cnt1;

            } else {

                skip_bits(b, nbits);

                escape = value + ((1 << nbits) - 1) * cnt1 - 1;

            }

        } else {

            escape = get_bits(b, 16);

        }

        value = -((escape + flag) & 1) | 1;

        dst[j++] = value * ((escape + flag + 1) >> 1);

        i++;

        if (j == width) {

            j = 0;

            dst += stride;

        }

        state = 120 * (escape + flag) + state - (120 * state >> 8);

        flag = 0;

        if (state * 4 > 0xFF || i >= size)

            continue;

        nbits = ((state + 8) >> 5) + (state ? ff_clz(state) : 32) - 24;

        escape = av_mod_uintp2(16383, nbits);

        cnt1 = get_unary(b, 0, 8);

        if (cnt1 > 7) {

            rlen = get_bits(b, 16);

        } else {

            value = show_bits(b, nbits);

            if (value > 1) {

                skip_bits(b, nbits);

                rlen = value + escape * cnt1 - 1;

            } else {

                skip_bits(b, nbits - 1);

                rlen = escape * cnt1;

            }

        }

        if (rlen > size - i)

            return AVERROR_INVALIDDATA;

        i += rlen;

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

            dst[j++] = 0;

            if (j == width) {

                j = 0;

                dst += stride;

            }

        }

        state = 0;

        flag = rlen < 0xFFFF ? 1 : 0;

    }

    align_get_bits(b);

    return get_bits_count(b) >> 3;

}


static void fdctrl_raise_irq(FDCtrl *fdctrl, uint8_t status0)

{

    /* Sparc mutation */

    if (fdctrl->sun4m && (fdctrl->msr & FD_MSR_CMDBUSY)) {

        /* XXX: not sure */

        fdctrl->msr &= ~FD_MSR_CMDBUSY;

        fdctrl->msr |= FD_MSR_RQM | FD_MSR_DIO;

        fdctrl->status0 = status0;

        return;

    }

    if (!(fdctrl->sra & FD_SRA_INTPEND)) {

        qemu_set_irq(fdctrl->irq, 1);

        fdctrl->sra |= FD_SRA_INTPEND;

    }

    if (status0 & FD_SR0_SEEK) {

        FDrive *cur_drv;

        /* A seek clears the disk change line (if a disk is inserted) */

        cur_drv = get_cur_drv(fdctrl);

        if (cur_drv->max_track) {

            cur_drv->media_changed = 0;

        }

    }

    fdctrl->reset_sensei = 0;

    fdctrl->status0 = status0;

    FLOPPY_DPRINTF("Set interrupt status to 0x%02x\n", fdctrl->status0);

}


static void qemu_net_queue_append_iov(NetQueue *queue,

                                      NetClientState *sender,

                                      unsigned flags,

                                      const struct iovec *iov,

                                      int iovcnt,

                                      NetPacketSent *sent_cb)

{

    NetPacket *packet;

    size_t max_len = 0;

    int i;

    if (queue->nq_count >= queue->nq_maxlen && !sent_cb) {

        return; /* drop if queue full and no callback */

    }

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

        max_len += iov[i].iov_len;

    }

    packet = g_malloc(sizeof(NetPacket) + max_len);

    packet->sender = sender;

    packet->sent_cb = sent_cb;

    packet->flags = flags;

    packet->size = 0;

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

        size_t len = iov[i].iov_len;

        memcpy(packet->data + packet->size, iov[i].iov_base, len);

        packet->size += len;

    }

    QTAILQ_INSERT_TAIL(&queue->packets, packet, entry);

}


static int ivr_read_header(AVFormatContext *s)

{

    unsigned tag, type, len, tlen, value;

    int i, j, n, count, nb_streams, ret;

    uint8_t key[256], val[256];

    AVIOContext *pb = s->pb;

    AVStream *st;

    int64_t pos, offset, temp;

    pos = avio_tell(pb);

    tag = avio_rl32(pb);

    if (tag == MKTAG('.','R','1','M')) {

        if (avio_rb16(pb) != 1)

            return AVERROR_INVALIDDATA;

        if (avio_r8(pb) != 1)

            return AVERROR_INVALIDDATA;

        len = avio_rb32(pb);

        avio_skip(pb, len);

        avio_skip(pb, 5);

        temp = avio_rb64(pb);

        while (!avio_feof(pb) && temp) {

            offset = temp;

            temp = avio_rb64(pb);

        }

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

        if (avio_r8(pb) != 1)

            return AVERROR_INVALIDDATA;

        len = avio_rb32(pb);

        avio_skip(pb, len);

        if (avio_r8(pb) != 2)

            return AVERROR_INVALIDDATA;

        avio_skip(pb, 16);

        pos = avio_tell(pb);

        tag = avio_rl32(pb);

    }

    if (tag != MKTAG('.','R','E','C'))

        return AVERROR_INVALIDDATA;

    if (avio_r8(pb) != 0)

        return AVERROR_INVALIDDATA;

    count = avio_rb32(pb);

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

        if (avio_feof(pb))

            return AVERROR_INVALIDDATA;

        type = avio_r8(pb);

        tlen = avio_rb32(pb);

        avio_get_str(pb, tlen, key, sizeof(key));

        len = avio_rb32(pb);

        if (type == 5) {

            avio_get_str(pb, len, val, sizeof(val));

            av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);

        } else if (type == 4) {

            av_log(s, AV_LOG_DEBUG, "%s = '0x", key);

            for (j = 0; j < len; j++)

                av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));

            av_log(s, AV_LOG_DEBUG, "'\n");

        } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) {

            nb_streams = value = avio_rb32(pb);

        } else if (len == 4 && type == 3) {

            value = avio_rb32(pb);

            av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);

        } else {

            av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);

            avio_skip(pb, len);

        }

    }

    for (n = 0; n < nb_streams; n++) {

        st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        st->priv_data = ff_rm_alloc_rmstream();

        if (!st->priv_data)

            return AVERROR(ENOMEM);

        if (avio_r8(pb) != 1)

            return AVERROR_INVALIDDATA;

        count = avio_rb32(pb);

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

            if (avio_feof(pb))

                return AVERROR_INVALIDDATA;

            type = avio_r8(pb);

            tlen  = avio_rb32(pb);

            avio_get_str(pb, tlen, key, sizeof(key));

            len  = avio_rb32(pb);

            if (type == 5) {

                avio_get_str(pb, len, val, sizeof(val));

                av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);

            } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) {

                ret = ffio_ensure_seekback(pb, 4);

                if (ret < 0)

                    return ret;

                if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) {

                    ret = rm_read_multi(s, pb, st, NULL);

                } else {

                    avio_seek(pb, -4, SEEK_CUR);

                    ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL);

                }

                if (ret < 0)

                    return ret;

            } else if (type == 4) {

                int j;

                av_log(s, AV_LOG_DEBUG, "%s = '0x", key);

                for (j = 0; j < len; j++)

                    av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));

                av_log(s, AV_LOG_DEBUG, "'\n");

            } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) {

                st->duration = avio_rb32(pb);

            } else if (len == 4 && type == 3) {

                value = avio_rb32(pb);

                av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);

            } else {

                av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);

                avio_skip(pb, len);

            }

        }

    }

    if (avio_r8(pb) != 6)

        return AVERROR_INVALIDDATA;

    avio_skip(pb, 12);

    avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb));

    if (avio_r8(pb) != 8)

        return AVERROR_INVALIDDATA;

    avio_skip(pb, 8);

    return 0;

}


static int parse_filter(const char *spec, struct USBAutoFilter *f)

{

    enum { BUS, DEV, VID, PID, DONE };

    const char *p = spec;

    int i;

    f->bus_num    = -1;

    f->addr       = -1;

    f->vendor_id  = -1;

    f->product_id = -1;

    for (i = BUS; i < DONE; i++) {

    	p = strpbrk(p, ":.");

    	if (!p) break;

        p++;

    	if (*p == '*')

            continue;

        switch(i) {

        case BUS: f->bus_num = strtol(p, NULL, 10);    break;

        case DEV: f->addr    = strtol(p, NULL, 10);    break;

        case VID: f->vendor_id  = strtol(p, NULL, 16); break;

        case PID: f->product_id = strtol(p, NULL, 16); break;

        }

    }

    if (i < DEV) {

        fprintf(stderr, "husb: invalid auto filter spec %s\n", spec);

        return -1;

    }

    return 0;

}


static void inline xan_wc3_build_palette(XanContext *s,

    unsigned int *palette_data)

{

    int i;

    unsigned char r, g, b;

    unsigned short *palette16;

    unsigned int *palette32;

    unsigned int pal_elem;

    /* transform the palette passed through the palette control structure

     * into the necessary internal format depending on colorspace */

    switch (s->avctx->pix_fmt) {

    case PIX_FMT_RGB555:

        palette16 = (unsigned short *)s->palette;

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

            pal_elem = palette_data[i];

            r = (pal_elem >> 16) & 0xff;

            g = (pal_elem >> 8) & 0xff;

            b = pal_elem & 0xff;

            palette16[i] =

                ((r >> 3) << 10) |

                ((g >> 3) <<  5) |

                ((b >> 3) <<  0);

        }

        break;

    case PIX_FMT_RGB565:

        palette16 = (unsigned short *)s->palette;

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

            pal_elem = palette_data[i];

            r = (pal_elem >> 16) & 0xff;

            g = (pal_elem >> 8) & 0xff;

            b = pal_elem & 0xff;

            palette16[i] =

                ((r >> 3) << 11) |

                ((g >> 2) <<  5) |

                ((b >> 3) <<  0);

        }

        break;

    case PIX_FMT_RGB24:

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

            pal_elem = palette_data[i];

            r = (pal_elem >> 16) & 0xff;

            g = (pal_elem >> 8) & 0xff;

            b = pal_elem & 0xff;

            s->palette[i * 4 + 0] = r;

            s->palette[i * 4 + 1] = g;

            s->palette[i * 4 + 2] = b;

        }

        break;

    case PIX_FMT_BGR24:

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

            pal_elem = palette_data[i];

            r = (pal_elem >> 16) & 0xff;

            g = (pal_elem >> 8) & 0xff;

            b = pal_elem & 0xff;

            s->palette[i * 4 + 0] = b;

            s->palette[i * 4 + 1] = g;

            s->palette[i * 4 + 2] = r;

        }

        break;

    case PIX_FMT_PAL8:

    case PIX_FMT_RGBA32:

        palette32 = (unsigned int *)s->palette;

        memcpy (palette32, palette_data, PALETTE_COUNT * sizeof(unsigned int));

        break;

    case PIX_FMT_YUV444P:

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

            pal_elem = palette_data[i];

            r = (pal_elem >> 16) & 0xff;

            g = (pal_elem >> 8) & 0xff;

            b = pal_elem & 0xff;

            s->palette[i * 4 + 0] = COMPUTE_Y(r, g, b);

            s->palette[i * 4 + 1] = COMPUTE_U(r, g, b);

            s->palette[i * 4 + 2] = COMPUTE_V(r, g, b);

        }

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, " Xan WC3: Unhandled colorspace\n");

        break;

    }

}


int MPV_common_init(MpegEncContext *s)

{

    int c_size, i;

    UINT8 *pict;

    s->dct_unquantize_h263 = dct_unquantize_h263_c;

    s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;

    s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;

#ifdef HAVE_MMX

    MPV_common_init_mmx(s);

#endif

    //setup default unquantizers (mpeg4 might change it later)

    if(s->out_format == FMT_H263)

        s->dct_unquantize = s->dct_unquantize_h263;

    else

        s->dct_unquantize = s->dct_unquantize_mpeg1;

    s->mb_width = (s->width + 15) / 16;

    s->mb_height = (s->height + 15) / 16;

    s->mb_num = s->mb_width * s->mb_height;

    s->linesize = s->mb_width * 16 + 2 * EDGE_WIDTH;

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

        int w, h, shift, pict_start;

        w = s->linesize;

        h = s->mb_height * 16 + 2 * EDGE_WIDTH;

        shift = (i == 0) ? 0 : 1;

        c_size = (w >> shift) * (h >> shift);

        pict_start = (w >> shift) * (EDGE_WIDTH >> shift) + (EDGE_WIDTH >> shift);

        pict = av_mallocz(c_size);

        if (pict == NULL)

            goto fail;

        s->last_picture_base[i] = pict;

        s->last_picture[i] = pict + pict_start;

        pict = av_mallocz(c_size);

        if (pict == NULL)

            goto fail;

        s->next_picture_base[i] = pict;

        s->next_picture[i] = pict + pict_start;

        if (s->has_b_frames || s->codec_id==CODEC_ID_MPEG4) {

        /* Note the MPEG4 stuff is here cuz of buggy encoders which dont set the low_delay flag but

           do low-delay encoding, so we cant allways distinguish b-frame containing streams from low_delay streams */

            pict = av_mallocz(c_size);

            if (pict == NULL)

                goto fail;

            s->aux_picture_base[i] = pict;

            s->aux_picture[i] = pict + pict_start;

        }

    }

    if (s->encoding) {

        int j;

        int mv_table_size= (s->mb_width+2)*(s->mb_height+2);

        /* Allocate MB type table */

        s->mb_type = av_mallocz(s->mb_num * sizeof(char));

        if (s->mb_type == NULL) {

            perror("malloc");

            goto fail;

        }

        s->mb_var = av_mallocz(s->mb_num * sizeof(INT16));

        if (s->mb_var == NULL) {

            perror("malloc");

            goto fail;

        }

        /* Allocate MV tables */

        s->p_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->p_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->last_p_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->last_p_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->b_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->b_forw_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->b_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->b_back_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->b_bidir_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->b_bidir_forw_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->b_bidir_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->b_bidir_back_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->b_direct_forw_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->b_direct_forw_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->b_direct_back_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->b_direct_back_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->b_direct_mv_table = av_mallocz(mv_table_size * 2 * sizeof(INT16));

        if (s->b_direct_mv_table == NULL) {

            perror("malloc");

            goto fail;

        }

        s->me_scratchpad = av_mallocz( s->linesize*16*3*sizeof(uint8_t));

        if (s->me_scratchpad == NULL) {

            perror("malloc");

            goto fail;

        }

        if(s->max_b_frames){

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

                int i;

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

                    int w, h, shift;

                    w = s->linesize;

                    h = s->mb_height * 16;

                    shift = (i == 0) ? 0 : 1;

                    c_size = (w >> shift) * (h >> shift);

                    pict = av_mallocz(c_size);

                    if (pict == NULL)

                        goto fail;

                    s->picture_buffer[j][i] = pict;

                }

            }

        }

    }

    if (s->out_format == FMT_H263 || s->encoding) {

        int size;

        /* MV prediction */

        size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);

        s->motion_val = av_malloc(size * 2 * sizeof(INT16));

        if (s->motion_val == NULL)

            goto fail;

        memset(s->motion_val, 0, size * 2 * sizeof(INT16));

    }

    if (s->h263_pred || s->h263_plus) {

        int y_size, c_size, i, size;

        /* dc values */

        y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);

        c_size = (s->mb_width + 2) * (s->mb_height + 2);

        size = y_size + 2 * c_size;

        s->dc_val[0] = av_malloc(size * sizeof(INT16));

        if (s->dc_val[0] == NULL)

            goto fail;

        s->dc_val[1] = s->dc_val[0] + y_size;

        s->dc_val[2] = s->dc_val[1] + c_size;

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

            s->dc_val[0][i] = 1024;

        /* ac values */

        s->ac_val[0] = av_mallocz(size * sizeof(INT16) * 16);

        if (s->ac_val[0] == NULL)

            goto fail;

        s->ac_val[1] = s->ac_val[0] + y_size;

        s->ac_val[2] = s->ac_val[1] + c_size;

        /* cbp values */

        s->coded_block = av_mallocz(y_size);

        if (!s->coded_block)

            goto fail;

        /* which mb is a intra block */

        s->mbintra_table = av_mallocz(s->mb_num);

        if (!s->mbintra_table)

            goto fail;

        memset(s->mbintra_table, 1, s->mb_num);

        /* divx501 bitstream reorder buffer */

        s->bitstream_buffer= av_mallocz(BITSTREAM_BUFFER_SIZE);

        if (!s->bitstream_buffer)

            goto fail;

    }

    /* default structure is frame */

    s->picture_structure = PICT_FRAME;

    /* init macroblock skip table */

    s->mbskip_table = av_mallocz(s->mb_num);

    if (!s->mbskip_table)

        goto fail;

    s->block= s->blocks[0];

    s->context_initialized = 1;

    return 0;

 fail:

    MPV_common_end(s);

    return -1;

}


void spapr_drc_reset(sPAPRDRConnector *drc)

{

    sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    trace_spapr_drc_reset(spapr_drc_index(drc));

    g_free(drc->ccs);

    drc->ccs = NULL;

    /* immediately upon reset we can safely assume DRCs whose devices

     * are pending removal can be safely removed.

     */

    if (drc->unplug_requested) {

        spapr_drc_release(drc);

    }

    if (drc->dev) {

        /* A device present at reset is ready to go, same as coldplugged */

        drc->state = drck->ready_state;

    } else {

        drc->state = drck->empty_state;

    }

}


static void v9fs_read(void *opaque)

{

    int32_t fid;

    uint64_t off;

    ssize_t err = 0;

    int32_t count = 0;

    size_t offset = 7;

    uint32_t max_count;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);

    trace_v9fs_read(pdu->tag, pdu->id, fid, off, max_count);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    if (fidp->fid_type == P9_FID_DIR) {

        if (off == 0) {

            v9fs_co_rewinddir(pdu, fidp);

        }

        count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);

        if (count < 0) {

            err = count;

            goto out;

        }

        err = offset;

        err += pdu_marshal(pdu, offset, "d", count);

        err += count;

    } else if (fidp->fid_type == P9_FID_FILE) {

        QEMUIOVector qiov_full;

        QEMUIOVector qiov;

        int32_t len;

        v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset + 4, max_count, false);

        qemu_iovec_init(&qiov, qiov_full.niov);

        do {

            qemu_iovec_reset(&qiov);

            qemu_iovec_copy(&qiov, &qiov_full, count, qiov_full.size - count);

            if (0) {

                print_sg(qiov.iov, qiov.niov);

            }

            /* Loop in case of EINTR */

            do {

                len = v9fs_co_preadv(pdu, fidp, qiov.iov, qiov.niov, off);

                if (len >= 0) {

                    off   += len;

                    count += len;

                }

            } while (len == -EINTR && !pdu->cancelled);

            if (len < 0) {

                /* IO error return the error */

                err = len;

                goto out;

            }

        } while (count < max_count && len > 0);

        err = offset;

        err += pdu_marshal(pdu, offset, "d", count);

        err += count;

        qemu_iovec_destroy(&qiov);

        qemu_iovec_destroy(&qiov_full);

    } else if (fidp->fid_type == P9_FID_XATTR) {

        err = v9fs_xattr_read(s, pdu, fidp, off, max_count);

    } else {

        err = -EINVAL;

    }

    trace_v9fs_read_return(pdu->tag, pdu->id, count, err);

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}


static inline void gen_intermediate_code_internal(CPUState *env,

                                                  TranslationBlock *tb,

                                                  int search_pc)

{

    DisasContext ctx, *ctxp = &ctx;

    opc_handler_t **table, *handler;

    target_ulong pc_start;

    uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int j, lj = -1;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    ctx.nip = pc_start;

    ctx.tb = tb;

    ctx.exception = POWERPC_EXCP_NONE;

    ctx.spr_cb = env->spr_cb;

    ctx.mem_idx = env->mmu_idx;

    ctx.access_type = -1;

    ctx.le_mode = env->hflags & (1 << MSR_LE) ? 1 : 0;

#if defined(TARGET_PPC64)

    ctx.sf_mode = msr_sf;

#endif

    ctx.fpu_enabled = msr_fp;

    if ((env->flags & POWERPC_FLAG_SPE) && msr_spe)

        ctx.spe_enabled = msr_spe;

    else

        ctx.spe_enabled = 0;

    if ((env->flags & POWERPC_FLAG_VRE) && msr_vr)

        ctx.altivec_enabled = msr_vr;

    else

        ctx.altivec_enabled = 0;

    if ((env->flags & POWERPC_FLAG_SE) && msr_se)

        ctx.singlestep_enabled = CPU_SINGLE_STEP;

    else

        ctx.singlestep_enabled = 0;

    if ((env->flags & POWERPC_FLAG_BE) && msr_be)

        ctx.singlestep_enabled |= CPU_BRANCH_STEP;

    if (unlikely(env->singlestep_enabled))

        ctx.singlestep_enabled |= GDBSTUB_SINGLE_STEP;

#if defined (DO_SINGLE_STEP) && 0

    /* Single step trace mode */

    msr_se = 1;

#endif

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_icount_start();

    /* Set env in case of segfault during code fetch */

    while (ctx.exception == POWERPC_EXCP_NONE && gen_opc_ptr < gen_opc_end) {

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

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

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

                    gen_debug_exception(ctxp);

                    break;

                }

            }

        }

        if (unlikely(search_pc)) {

            j = gen_opc_ptr - gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    gen_opc_instr_start[lj++] = 0;

            }

            gen_opc_pc[lj] = ctx.nip;

            gen_opc_instr_start[lj] = 1;

            gen_opc_icount[lj] = num_insns;

        }

        LOG_DISAS("----------------\n");

        LOG_DISAS("nip=" TARGET_FMT_lx " super=%d ir=%d\n",

                  ctx.nip, ctx.mem_idx, (int)msr_ir);

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

            gen_io_start();

        if (unlikely(ctx.le_mode)) {

            ctx.opcode = bswap32(ldl_code(ctx.nip));

        } else {

            ctx.opcode = ldl_code(ctx.nip);

        }

        LOG_DISAS("translate opcode %08x (%02x %02x %02x) (%s)\n",

                    ctx.opcode, opc1(ctx.opcode), opc2(ctx.opcode),

                    opc3(ctx.opcode), little_endian ? "little" : "big");

        if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP)))

            tcg_gen_debug_insn_start(ctx.nip);

        ctx.nip += 4;

        table = env->opcodes;

        num_insns++;

        handler = table[opc1(ctx.opcode)];

        if (is_indirect_opcode(handler)) {

            table = ind_table(handler);

            handler = table[opc2(ctx.opcode)];

            if (is_indirect_opcode(handler)) {

                table = ind_table(handler);

                handler = table[opc3(ctx.opcode)];

            }

        }

        /* Is opcode *REALLY* valid ? */

        if (unlikely(handler->handler == &gen_invalid)) {

            if (qemu_log_enabled()) {

                qemu_log("invalid/unsupported opcode: "

                         "%02x - %02x - %02x (%08x) " TARGET_FMT_lx " %d\n",

                         opc1(ctx.opcode), opc2(ctx.opcode),

                         opc3(ctx.opcode), ctx.opcode, ctx.nip - 4, (int)msr_ir);

            } else {

                printf("invalid/unsupported opcode: "

                       "%02x - %02x - %02x (%08x) " TARGET_FMT_lx " %d\n",

                       opc1(ctx.opcode), opc2(ctx.opcode),

                       opc3(ctx.opcode), ctx.opcode, ctx.nip - 4, (int)msr_ir);

            }

        } else {

            if (unlikely((ctx.opcode & handler->inval) != 0)) {

                if (qemu_log_enabled()) {

                    qemu_log("invalid bits: %08x for opcode: "

                             "%02x - %02x - %02x (%08x) " TARGET_FMT_lx "\n",

                             ctx.opcode & handler->inval, opc1(ctx.opcode),

                             opc2(ctx.opcode), opc3(ctx.opcode),

                             ctx.opcode, ctx.nip - 4);

                } else {

                    printf("invalid bits: %08x for opcode: "

                           "%02x - %02x - %02x (%08x) " TARGET_FMT_lx "\n",

                           ctx.opcode & handler->inval, opc1(ctx.opcode),

                           opc2(ctx.opcode), opc3(ctx.opcode),

                           ctx.opcode, ctx.nip - 4);

                }

                gen_inval_exception(ctxp, POWERPC_EXCP_INVAL_INVAL);

                break;

            }

        }

        (*(handler->handler))(&ctx);

#if defined(DO_PPC_STATISTICS)

        handler->count++;

#endif

        /* Check trace mode exceptions */

        if (unlikely(ctx.singlestep_enabled & CPU_SINGLE_STEP &&

                     (ctx.nip <= 0x100 || ctx.nip > 0xF00) &&

                     ctx.exception != POWERPC_SYSCALL &&

                     ctx.exception != POWERPC_EXCP_TRAP &&

                     ctx.exception != POWERPC_EXCP_BRANCH)) {

            gen_exception(ctxp, POWERPC_EXCP_TRACE);

        } else if (unlikely(((ctx.nip & (TARGET_PAGE_SIZE - 1)) == 0) ||

                            (env->singlestep_enabled) ||

                            singlestep ||

                            num_insns >= max_insns)) {

            /* if we reach a page boundary or are single stepping, stop

             * generation

             */

            break;

        }

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    if (ctx.exception == POWERPC_EXCP_NONE) {

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

    } else if (ctx.exception != POWERPC_EXCP_BRANCH) {

        if (unlikely(env->singlestep_enabled)) {

            gen_debug_exception(ctxp);

        }

        /* Generate the return instruction */

        tcg_gen_exit_tb(0);

    }

    gen_icount_end(tb, num_insns);

    *gen_opc_ptr = INDEX_op_end;

    if (unlikely(search_pc)) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = ctx.nip - pc_start;

        tb->icount = num_insns;

    }

#if defined(DEBUG_DISAS)

    qemu_log_mask(CPU_LOG_TB_CPU, "---------------- excp: %04x\n", ctx.exception);

    log_cpu_state_mask(CPU_LOG_TB_CPU, env, 0);

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        int flags;

        flags = env->bfd_mach;

        flags |= ctx.le_mode << 16;

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

        log_target_disas(pc_start, ctx.nip - pc_start, flags);

        qemu_log("\n");

    }

#endif

}


static void vtd_handle_gcmd_qie(IntelIOMMUState *s, bool en)

{

    uint64_t iqa_val = vtd_get_quad_raw(s, DMAR_IQA_REG);

    trace_vtd_inv_qi_enable(en);

    if (en) {

        s->iq = iqa_val & VTD_IQA_IQA_MASK(VTD_HOST_ADDRESS_WIDTH);

        /* 2^(x+8) entries */

        s->iq_size = 1UL << ((iqa_val & VTD_IQA_QS) + 8);

        s->qi_enabled = true;

        trace_vtd_inv_qi_setup(s->iq, s->iq_size);

        /* Ok - report back to driver */

        vtd_set_clear_mask_long(s, DMAR_GSTS_REG, 0, VTD_GSTS_QIES);

        if (s->iq_tail != 0) {

            /*

             * This is a spec violation but Windows guests are known to set up

             * Queued Invalidation this way so we allow the write and process

             * Invalidation Descriptors right away.

             */

            trace_vtd_warn_invalid_qi_tail(s->iq_tail);

            if (!(vtd_get_long_raw(s, DMAR_FSTS_REG) & VTD_FSTS_IQE)) {

                vtd_fetch_inv_desc(s);

            }

        }

    } else {

        if (vtd_queued_inv_disable_check(s)) {

            /* disable Queued Invalidation */

            vtd_set_quad_raw(s, DMAR_IQH_REG, 0);

            s->iq_head = 0;

            s->qi_enabled = false;

            /* Ok - report back to driver */

            vtd_set_clear_mask_long(s, DMAR_GSTS_REG, VTD_GSTS_QIES, 0);

        } else {

            trace_vtd_err_qi_disable(s->iq_head, s->iq_tail, s->iq_last_desc_type);

        }

    }

}


static void mv88w8618_pit_write(void *opaque, target_phys_addr_t offset,

                                uint64_t value, unsigned size)

{

    mv88w8618_pit_state *s = opaque;

    mv88w8618_timer_state *t;

    int i;

    switch (offset) {

    case MP_PIT_TIMER1_LENGTH ... MP_PIT_TIMER4_LENGTH:

        t = &s->timer[offset >> 2];

        t->limit = value;

        if (t->limit > 0) {

            ptimer_set_limit(t->ptimer, t->limit, 1);

        } else {

            ptimer_stop(t->ptimer);

        }

        break;

    case MP_PIT_CONTROL:

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

            t = &s->timer[i];

            if (value & 0xf && t->limit > 0) {

                ptimer_set_limit(t->ptimer, t->limit, 0);

                ptimer_set_freq(t->ptimer, t->freq);

                ptimer_run(t->ptimer, 0);

            } else {

                ptimer_stop(t->ptimer);

            }

            value >>= 4;

        }

        break;

    case MP_BOARD_RESET:

        if (value == MP_BOARD_RESET_MAGIC) {

            qemu_system_reset_request();

        }

        break;

    }

}


static void ivshmem_plain_init(Object *obj)

{

    IVShmemState *s = IVSHMEM_PLAIN(obj);

    object_property_add_link(obj, "memdev", TYPE_MEMORY_BACKEND,

                             (Object **)&s->hostmem,

                             ivshmem_check_memdev_is_busy,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE,

                             &error_abort);

    s->not_legacy_32bit = 1;

}


void xen_hvm_init(PCMachineState *pcms, MemoryRegion **ram_memory)

{

    int i, rc;

    xen_pfn_t ioreq_pfn;

    xen_pfn_t bufioreq_pfn;

    evtchn_port_t bufioreq_evtchn;

    XenIOState *state;

    state = g_malloc0(sizeof (XenIOState));

    state->xce_handle = xen_xc_evtchn_open(NULL, 0);

    if (state->xce_handle == XC_HANDLER_INITIAL_VALUE) {

        perror("xen: event channel open");

        goto err;

    }

    state->xenstore = xs_daemon_open();

    if (state->xenstore == NULL) {

        perror("xen: xenstore open");

        goto err;

    }

    rc = xen_create_ioreq_server(xen_xc, xen_domid, &state->ioservid);

    if (rc < 0) {

        perror("xen: ioreq server create");

        goto err;

    }

    state->exit.notify = xen_exit_notifier;

    qemu_add_exit_notifier(&state->exit);

    state->suspend.notify = xen_suspend_notifier;

    qemu_register_suspend_notifier(&state->suspend);

    state->wakeup.notify = xen_wakeup_notifier;

    qemu_register_wakeup_notifier(&state->wakeup);

    rc = xen_get_ioreq_server_info(xen_xc, xen_domid, state->ioservid,

                                   &ioreq_pfn, &bufioreq_pfn,

                                   &bufioreq_evtchn);

    if (rc < 0) {

        error_report("failed to get ioreq server info: error %d handle=" XC_INTERFACE_FMT,

                     errno, xen_xc);

        goto err;

    }

    DPRINTF("shared page at pfn %lx\n", ioreq_pfn);

    DPRINTF("buffered io page at pfn %lx\n", bufioreq_pfn);

    DPRINTF("buffered io evtchn is %x\n", bufioreq_evtchn);

    state->shared_page = xc_map_foreign_range(xen_xc, xen_domid, XC_PAGE_SIZE,

                                              PROT_READ|PROT_WRITE, ioreq_pfn);

    if (state->shared_page == NULL) {

        error_report("map shared IO page returned error %d handle=" XC_INTERFACE_FMT,

                     errno, xen_xc);

        goto err;

    }

    rc = xen_get_vmport_regs_pfn(xen_xc, xen_domid, &ioreq_pfn);

    if (!rc) {

        DPRINTF("shared vmport page at pfn %lx\n", ioreq_pfn);

        state->shared_vmport_page =

            xc_map_foreign_range(xen_xc, xen_domid, XC_PAGE_SIZE,

                                 PROT_READ|PROT_WRITE, ioreq_pfn);

        if (state->shared_vmport_page == NULL) {

            error_report("map shared vmport IO page returned error %d handle="

                         XC_INTERFACE_FMT, errno, xen_xc);

            goto err;

        }

    } else if (rc != -ENOSYS) {

        error_report("get vmport regs pfn returned error %d, rc=%d",

                     errno, rc);

        goto err;

    }

    state->buffered_io_page = xc_map_foreign_range(xen_xc, xen_domid,

                                                   XC_PAGE_SIZE,

                                                   PROT_READ|PROT_WRITE,

                                                   bufioreq_pfn);

    if (state->buffered_io_page == NULL) {

        error_report("map buffered IO page returned error %d", errno);

        goto err;

    }

    /* Note: cpus is empty at this point in init */

    state->cpu_by_vcpu_id = g_malloc0(max_cpus * sizeof(CPUState *));

    rc = xen_set_ioreq_server_state(xen_xc, xen_domid, state->ioservid, true);

    if (rc < 0) {

        error_report("failed to enable ioreq server info: error %d handle=" XC_INTERFACE_FMT,

                     errno, xen_xc);

        goto err;

    }

    state->ioreq_local_port = g_malloc0(max_cpus * sizeof (evtchn_port_t));

    /* FIXME: how about if we overflow the page here? */

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

        rc = xc_evtchn_bind_interdomain(state->xce_handle, xen_domid,

                                        xen_vcpu_eport(state->shared_page, i));

        if (rc == -1) {

            error_report("shared evtchn %d bind error %d", i, errno);

            goto err;

        }

        state->ioreq_local_port[i] = rc;

    }

    rc = xc_evtchn_bind_interdomain(state->xce_handle, xen_domid,

                                    bufioreq_evtchn);

    if (rc == -1) {

        error_report("buffered evtchn bind error %d", errno);

        goto err;

    }

    state->bufioreq_local_port = rc;

    /* Init RAM management */

    xen_map_cache_init(xen_phys_offset_to_gaddr, state);

    xen_ram_init(pcms, ram_size, ram_memory);

    qemu_add_vm_change_state_handler(xen_hvm_change_state_handler, state);

    state->memory_listener = xen_memory_listener;

    QLIST_INIT(&state->physmap);

    memory_listener_register(&state->memory_listener, &address_space_memory);

    state->log_for_dirtybit = NULL;

    state->io_listener = xen_io_listener;

    memory_listener_register(&state->io_listener, &address_space_io);

    state->device_listener = xen_device_listener;

    device_listener_register(&state->device_listener);

    /* Initialize backend core & drivers */

    if (xen_be_init() != 0) {

        error_report("xen backend core setup failed");

        goto err;

    }

    xen_be_register("console", &xen_console_ops);

    xen_be_register("vkbd", &xen_kbdmouse_ops);

    xen_be_register("qdisk", &xen_blkdev_ops);

    xen_read_physmap(state);

    return;

err:

    error_report("xen hardware virtual machine initialisation failed");

    exit(1);

}


static void block_io_signals(void)

{

    sigset_t set;

    struct sigaction sigact;

    sigemptyset(&set);

    sigaddset(&set, SIGUSR2);

    sigaddset(&set, SIGIO);

    sigaddset(&set, SIGALRM);

    sigaddset(&set, SIGCHLD);

    pthread_sigmask(SIG_BLOCK, &set, NULL);

    sigemptyset(&set);

    sigaddset(&set, SIGUSR1);

    pthread_sigmask(SIG_UNBLOCK, &set, NULL);

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

    sigact.sa_handler = cpu_signal;

    sigaction(SIGUSR1, &sigact, NULL);

}


static void vga_update_text(void *opaque, console_ch_t *chardata)

{

    VGACommonState *s =  opaque;

    int graphic_mode, i, cursor_offset, cursor_visible;

    int cw, cheight, width, height, size, c_min, c_max;

    uint32_t *src;

    console_ch_t *dst, val;

    char msg_buffer[80];

    int full_update = 0;

    qemu_flush_coalesced_mmio_buffer();

    if (!(s->ar_index & 0x20)) {

        graphic_mode = GMODE_BLANK;

    } else {

        graphic_mode = s->gr[VGA_GFX_MISC] & VGA_GR06_GRAPHICS_MODE;

    }

    if (graphic_mode != s->graphic_mode) {

        s->graphic_mode = graphic_mode;

        full_update = 1;

    }

    if (s->last_width == -1) {

        s->last_width = 0;

        full_update = 1;

    }

    switch (graphic_mode) {

    case GMODE_TEXT:

        /* TODO: update palette */

        full_update |= update_basic_params(s);

        /* total width & height */

        cheight = (s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1;

        cw = 8;

        if (!(s->sr[VGA_SEQ_CLOCK_MODE] & VGA_SR01_CHAR_CLK_8DOTS)) {

            cw = 9;

        }

        if (s->sr[VGA_SEQ_CLOCK_MODE] & 0x08) {

            cw = 16; /* NOTE: no 18 pixel wide */

        }

        width = (s->cr[VGA_CRTC_H_DISP] + 1);

        if (s->cr[VGA_CRTC_V_TOTAL] == 100) {

            /* ugly hack for CGA 160x100x16 - explain me the logic */

            height = 100;

        } else {

            height = s->cr[VGA_CRTC_V_DISP_END] |

                ((s->cr[VGA_CRTC_OVERFLOW] & 0x02) << 7) |

                ((s->cr[VGA_CRTC_OVERFLOW] & 0x40) << 3);

            height = (height + 1) / cheight;

        }

        size = (height * width);

        if (size > CH_ATTR_SIZE) {

            if (!full_update)

                return;

            snprintf(msg_buffer, sizeof(msg_buffer), "%i x %i Text mode",

                     width, height);

            break;

        }

        if (width != s->last_width || height != s->last_height ||

            cw != s->last_cw || cheight != s->last_ch) {

            s->last_scr_width = width * cw;

            s->last_scr_height = height * cheight;

            qemu_console_resize(s->con, s->last_scr_width, s->last_scr_height);

            dpy_text_resize(s->con, width, height);

            s->last_depth = 0;

            s->last_width = width;

            s->last_height = height;

            s->last_ch = cheight;

            s->last_cw = cw;

            full_update = 1;

        }

        if (full_update) {

            s->full_update_gfx = 1;

        }

        if (s->full_update_text) {

            s->full_update_text = 0;

            full_update |= 1;

        }

        /* Update "hardware" cursor */

        cursor_offset = ((s->cr[VGA_CRTC_CURSOR_HI] << 8) |

                         s->cr[VGA_CRTC_CURSOR_LO]) - s->start_addr;

        if (cursor_offset != s->cursor_offset ||

            s->cr[VGA_CRTC_CURSOR_START] != s->cursor_start ||

            s->cr[VGA_CRTC_CURSOR_END] != s->cursor_end || full_update) {

            cursor_visible = !(s->cr[VGA_CRTC_CURSOR_START] & 0x20);

            if (cursor_visible && cursor_offset < size && cursor_offset >= 0)

                dpy_text_cursor(s->con,

                                TEXTMODE_X(cursor_offset),

                                TEXTMODE_Y(cursor_offset));

            else

                dpy_text_cursor(s->con, -1, -1);

            s->cursor_offset = cursor_offset;

            s->cursor_start = s->cr[VGA_CRTC_CURSOR_START];

            s->cursor_end = s->cr[VGA_CRTC_CURSOR_END];

        }

        src = (uint32_t *) s->vram_ptr + s->start_addr;

        dst = chardata;

        if (full_update) {

            for (i = 0; i < size; src ++, dst ++, i ++)

                console_write_ch(dst, VMEM2CHTYPE(le32_to_cpu(*src)));

            dpy_text_update(s->con, 0, 0, width, height);

        } else {

            c_max = 0;

            for (i = 0; i < size; src ++, dst ++, i ++) {

                console_write_ch(&val, VMEM2CHTYPE(le32_to_cpu(*src)));

                if (*dst != val) {

                    *dst = val;

                    c_max = i;

                    break;

                }

            }

            c_min = i;

            for (; i < size; src ++, dst ++, i ++) {

                console_write_ch(&val, VMEM2CHTYPE(le32_to_cpu(*src)));

                if (*dst != val) {

                    *dst = val;

                    c_max = i;

                }

            }

            if (c_min <= c_max) {

                i = TEXTMODE_Y(c_min);

                dpy_text_update(s->con, 0, i, width, TEXTMODE_Y(c_max) - i + 1);

            }

        }

        return;

    case GMODE_GRAPH:

        if (!full_update)

            return;

        s->get_resolution(s, &width, &height);

        snprintf(msg_buffer, sizeof(msg_buffer), "%i x %i Graphic mode",

                 width, height);

        break;

    case GMODE_BLANK:

    default:

        if (!full_update)

            return;

        snprintf(msg_buffer, sizeof(msg_buffer), "VGA Blank mode");

        break;

    }

    /* Display a message */

    s->last_width = 60;

    s->last_height = height = 3;

    dpy_text_cursor(s->con, -1, -1);

    dpy_text_resize(s->con, s->last_width, height);

    for (dst = chardata, i = 0; i < s->last_width * height; i ++)

        console_write_ch(dst ++, ' ');

    size = strlen(msg_buffer);

    width = (s->last_width - size) / 2;

    dst = chardata + s->last_width + width;

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

        console_write_ch(dst ++, 0x00200100 | msg_buffer[i]);

    dpy_text_update(s->con, 0, 0, s->last_width, height);

}


static void init_proc_book3s_64(CPUPPCState *env, int version)

{

    gen_spr_ne_601(env);

    gen_tbl(env);

    gen_spr_book3s_altivec(env);

    gen_spr_book3s_pmu_sup(env);

    gen_spr_book3s_pmu_user(env);

    gen_spr_book3s_dbg(env);

    gen_spr_book3s_common(env);

    switch (version) {

    case BOOK3S_CPU_970:

    case BOOK3S_CPU_POWER5PLUS:

        gen_spr_970_hid(env);

        gen_spr_970_hior(env);

        gen_low_BATs(env);

        gen_spr_970_pmu_sup(env);

        gen_spr_970_pmu_user(env);

        break;

    case BOOK3S_CPU_POWER7:

    case BOOK3S_CPU_POWER8:

        gen_spr_book3s_ids(env);

        gen_spr_amr(env);

        gen_spr_book3s_purr(env);

        break;

    default:

        g_assert_not_reached();

    }

    if (version >= BOOK3S_CPU_POWER5PLUS) {

        gen_spr_power5p_common(env);

        gen_spr_power5p_lpar(env);

        gen_spr_power5p_ear(env);

    } else {

        gen_spr_970_lpar(env);

    }

    if (version == BOOK3S_CPU_970) {

        gen_spr_970_dbg(env);

    }

    if (version >= BOOK3S_CPU_POWER6) {

        gen_spr_power6_common(env);

        gen_spr_power6_dbg(env);

    }

    if (version >= BOOK3S_CPU_POWER8) {

        gen_spr_power8_tce_address_control(env);

        gen_spr_power8_ids(env);

        gen_spr_power8_ebb(env);

        gen_spr_power8_fscr(env);

        gen_spr_power8_pmu_sup(env);

        gen_spr_power8_pmu_user(env);

        gen_spr_power8_tm(env);

    }

#if !defined(CONFIG_USER_ONLY)

    switch (version) {

    case BOOK3S_CPU_970:

    case BOOK3S_CPU_POWER5PLUS:

        env->slb_nr = 64;

        break;

    case BOOK3S_CPU_POWER7:

    case BOOK3S_CPU_POWER8:

    default:

        env->slb_nr = 32;

        break;

    }

#endif

    /* Allocate hardware IRQ controller */

    switch (version) {

    case BOOK3S_CPU_970:

    case BOOK3S_CPU_POWER5PLUS:

        init_excp_970(env);

        ppc970_irq_init(env);

        break;

    case BOOK3S_CPU_POWER7:

    case BOOK3S_CPU_POWER8:

        init_excp_POWER7(env);

        ppcPOWER7_irq_init(env);

        break;

    default:

        g_assert_not_reached();

    }

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

}


void cpu_single_step(CPUState *cpu, int enabled)

{

#if defined(TARGET_HAS_ICE)

    if (cpu->singlestep_enabled != enabled) {

        cpu->singlestep_enabled = enabled;

        if (kvm_enabled()) {

            kvm_update_guest_debug(cpu, 0);

        } else {

            /* must flush all the translated code to avoid inconsistencies */

            /* XXX: only flush what is necessary */

            CPUArchState *env = cpu->env_ptr;

            tb_flush(env);

        }

    }

#endif

}


static void qmp_input_type_null(Visitor *v, const char *name, Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

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

    if (!qobj) {

        return;

    }

    if (qobject_type(qobj) != QTYPE_QNULL) {

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

                   "null");

    }

}


static int ism_write_header(AVFormatContext *s)

{

    SmoothStreamingContext *c = s->priv_data;

    int ret = 0, i;

    AVOutputFormat *oformat;

    mkdir(s->filename, 0777);

    oformat = av_guess_format("ismv", NULL, NULL);

    if (!oformat) {

        ret = AVERROR_MUXER_NOT_FOUND;

        goto fail;

    }

    c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);

    if (!c->streams) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

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

        OutputStream *os = &c->streams[i];

        AVFormatContext *ctx;

        AVStream *st;

        AVDictionary *opts = NULL;

        char buf[10];

        if (!s->streams[i]->codec->bit_rate) {

            av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);

            ret = AVERROR(EINVAL);

            goto fail;

        }

        snprintf(os->dirname, sizeof(os->dirname), "%s/QualityLevels(%d)", s->filename, s->streams[i]->codec->bit_rate);

        mkdir(os->dirname, 0777);

        ctx = avformat_alloc_context();

        if (!ctx) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        os->ctx = ctx;

        ctx->oformat = oformat;

        ctx->interrupt_callback = s->interrupt_callback;

        if (!(st = avformat_new_stream(ctx, NULL))) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        avcodec_copy_context(st->codec, s->streams[i]->codec);

        st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;

        ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, ism_write, ism_seek);

        if (!ctx->pb) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        snprintf(buf, sizeof(buf), "%d", c->lookahead_count);

        av_dict_set(&opts, "ism_lookahead", buf, 0);

        av_dict_set(&opts, "movflags", "frag_custom", 0);

        if ((ret = avformat_write_header(ctx, &opts)) < 0) {

             goto fail;

        }

        os->ctx_inited = 1;

        avio_flush(ctx->pb);

        av_dict_free(&opts);

        s->streams[i]->time_base = st->time_base;

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

            c->has_video = 1;

            os->stream_type_tag = "video";

            if (st->codec->codec_id == AV_CODEC_ID_H264) {

                os->fourcc = "H264";

            } else if (st->codec->codec_id == AV_CODEC_ID_VC1) {

                os->fourcc = "WVC1";

            } else {

                av_log(s, AV_LOG_ERROR, "Unsupported video codec\n");

                ret = AVERROR(EINVAL);

                goto fail;

            }

        } else {

            c->has_audio = 1;

            os->stream_type_tag = "audio";

            if (st->codec->codec_id == AV_CODEC_ID_AAC) {

                os->fourcc = "AACL";

                os->audio_tag = 0xff;

            } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {

                os->fourcc = "WMAP";

                os->audio_tag = 0x0162;

            } else {

                av_log(s, AV_LOG_ERROR, "Unsupported audio codec\n");

                ret = AVERROR(EINVAL);

                goto fail;

            }

            os->packet_size = st->codec->block_align ? st->codec->block_align : 4;

        }

        get_private_data(os);

    }

    if (!c->has_video && c->min_frag_duration <= 0) {

        av_log(s, AV_LOG_WARNING, "no video stream and no min frag duration set\n");

        ret = AVERROR(EINVAL);

    }

    ret = write_manifest(s, 0);

fail:

    if (ret)

        ism_free(s);

    return ret;

}


static int proxy_chown(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp)

{

    int retval;

    retval = v9fs_request(fs_ctx->private, T_CHOWN, NULL, "sdd",

                          fs_path, credp->fc_uid, credp->fc_gid);

    if (retval < 0) {

        errno = -retval;

    }

    return retval;

}


static void test_validate_union_flat(TestInputVisitorData *data,

                                     const void *unused)

{

    UserDefFlatUnion *tmp = NULL;

    Visitor *v;

    Error *errp = NULL;

    v = validate_test_init(data,

                           "{ 'enum1': 'value1', "

                           "'string': 'str', "

                           "'boolean': true }");

    /* TODO when generator bug is fixed, add 'integer': 41 */

    visit_type_UserDefFlatUnion(v, &tmp, NULL, &errp);

    g_assert(!error_is_set(&errp));

    qapi_free_UserDefFlatUnion(tmp);

}


void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)

{

    char buf[4096];

    va_list ap;

    va_start(ap, fmt);

    vsnprintf(buf, sizeof(buf), fmt, ap);

    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));

    va_end(ap);

}


void laio_io_plug(BlockDriverState *bs, void *aio_ctx)

{

    struct qemu_laio_state *s = aio_ctx;

    s->io_q.plugged++;

}


static int cmd_valid_while_locked(SDState *sd, SDRequest *req)

{

    /* Valid commands in locked state:

     * basic class (0)

     * lock card class (7)

     * CMD16

     * implicitly, the ACMD prefix CMD55

     * ACMD41 and ACMD42

     * Anything else provokes an "illegal command" response.

     */

    if (sd->expecting_acmd) {

        return req->cmd == 41 || req->cmd == 42;

    }

    if (req->cmd == 16 || req->cmd == 55) {

        return 1;

    }

    return sd_cmd_class[req->cmd] == 0 || sd_cmd_class[req->cmd] == 7;

}


static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res,

    uint16_t *refcount_table, int64_t refcount_table_size, int64_t l2_offset,

    int flags)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l2_table, l2_entry;

    uint64_t next_contiguous_offset = 0;

    int i, l2_size, nb_csectors, ret;

    /* Read L2 table from disk */

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

    l2_table = g_malloc(l2_size);

    ret = bdrv_pread(bs->file, l2_offset, l2_table, l2_size);

    if (ret < 0) {

        fprintf(stderr, "ERROR: I/O error in check_refcounts_l2\n");

        res->check_errors++;

        goto fail;

    }

    /* Do the actual checks */

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

        l2_entry = be64_to_cpu(l2_table[i]);

        switch (qcow2_get_cluster_type(l2_entry)) {

        case QCOW2_CLUSTER_COMPRESSED:

            /* Compressed clusters don't have QCOW_OFLAG_COPIED */

            if (l2_entry & QCOW_OFLAG_COPIED) {

                fprintf(stderr, "ERROR: cluster %" PRId64 ": "

                    "copied flag must never be set for compressed "

                    "clusters\n", l2_entry >> s->cluster_bits);

                l2_entry &= ~QCOW_OFLAG_COPIED;

                res->corruptions++;

            }

            /* Mark cluster as used */

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

                           s->csize_mask) + 1;

            l2_entry &= s->cluster_offset_mask;

            ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,

                                l2_entry & ~511, nb_csectors * 512);

            if (ret < 0) {

                goto fail;

            }

            if (flags & CHECK_FRAG_INFO) {

                res->bfi.allocated_clusters++;

                res->bfi.compressed_clusters++;

                /* Compressed clusters are fragmented by nature.  Since they

                 * take up sub-sector space but we only have sector granularity

                 * I/O we need to re-read the same sectors even for adjacent

                 * compressed clusters.

                 */

                res->bfi.fragmented_clusters++;

            }

            break;

        case QCOW2_CLUSTER_ZERO:

            if ((l2_entry & L2E_OFFSET_MASK) == 0) {

                break;

            }

            /* fall through */

        case QCOW2_CLUSTER_NORMAL:

        {

            uint64_t offset = l2_entry & L2E_OFFSET_MASK;

            if (flags & CHECK_FRAG_INFO) {

                res->bfi.allocated_clusters++;

                if (next_contiguous_offset &&

                    offset != next_contiguous_offset) {

                    res->bfi.fragmented_clusters++;

                }

                next_contiguous_offset = offset + s->cluster_size;

            }

            /* Mark cluster as used */

            ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,

                                offset, s->cluster_size);

            if (ret < 0) {

                goto fail;

            }

            /* Correct offsets are cluster aligned */

            if (offset_into_cluster(s, offset)) {

                fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "

                    "properly aligned; L2 entry corrupted.\n", offset);

                res->corruptions++;

            }

            break;

        }

        case QCOW2_CLUSTER_UNALLOCATED:

            break;

        default:

            abort();

        }

    }

    g_free(l2_table);

    return 0;

fail:

    g_free(l2_table);

    return ret;

}


static void spapr_pci_unplug_request(HotplugHandler *plug_handler,

                                     DeviceState *plugged_dev, Error **errp)

{

    sPAPRPHBState *phb = SPAPR_PCI_HOST_BRIDGE(DEVICE(plug_handler));

    PCIDevice *pdev = PCI_DEVICE(plugged_dev);

    sPAPRDRConnectorClass *drck;

    sPAPRDRConnector *drc = spapr_phb_get_pci_drc(phb, pdev);

    if (!phb->dr_enabled) {

        error_setg(errp, QERR_BUS_NO_HOTPLUG,

                   object_get_typename(OBJECT(phb)));

        return;

    }

    g_assert(drc);

    g_assert(drc->dev == plugged_dev);

    drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    if (!drck->release_pending(drc)) {

        PCIBus *bus = PCI_BUS(qdev_get_parent_bus(DEVICE(pdev)));

        uint32_t slotnr = PCI_SLOT(pdev->devfn);

        sPAPRDRConnector *func_drc;

        sPAPRDRConnectorClass *func_drck;

        sPAPRDREntitySense state;

        int i;

        /* ensure any other present functions are pending unplug */

        if (PCI_FUNC(pdev->devfn) == 0) {

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

                func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),

                                                      PCI_DEVFN(slotnr, i));

                func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);

                state = func_drck->dr_entity_sense(func_drc);

                if (state == SPAPR_DR_ENTITY_SENSE_PRESENT

                    && !func_drck->release_pending(func_drc)) {

                    error_setg(errp,

                               "PCI: slot %d, function %d still present. "

                               "Must unplug all non-0 functions first.",

                               slotnr, i);

                    return;

                }

            }

        }

        spapr_drc_detach(drc);

        /* if this isn't func 0, defer unplug event. otherwise signal removal

         * for all present functions

         */

        if (PCI_FUNC(pdev->devfn) == 0) {

            for (i = 7; i >= 0; i--) {

                func_drc = spapr_phb_get_pci_func_drc(phb, pci_bus_num(bus),

                                                      PCI_DEVFN(slotnr, i));

                func_drck = SPAPR_DR_CONNECTOR_GET_CLASS(func_drc);

                state = func_drck->dr_entity_sense(func_drc);

                if (state == SPAPR_DR_ENTITY_SENSE_PRESENT) {

                    spapr_hotplug_req_remove_by_index(func_drc);

                }

            }

        }

    }

}