static int extract_extradata_h2645(AVBSFContext *ctx, AVPacket *pkt,

                                   uint8_t **data, int *size)

{

    static const int extradata_nal_types_hevc[] = {

        HEVC_NAL_VPS, HEVC_NAL_SPS, HEVC_NAL_PPS,

    };

    static const int extradata_nal_types_h264[] = {

        H264_NAL_SPS, H264_NAL_PPS,

    };

    ExtractExtradataContext *s = ctx->priv_data;

    H2645Packet h2645_pkt = { 0 };

    int extradata_size = 0;

    const int *extradata_nal_types;

    int nb_extradata_nal_types;

    int i, has_sps = 0, has_vps = 0, ret = 0;

    if (ctx->par_in->codec_id == AV_CODEC_ID_HEVC) {

        extradata_nal_types    = extradata_nal_types_hevc;

        nb_extradata_nal_types = FF_ARRAY_ELEMS(extradata_nal_types_hevc);

    } else {

        extradata_nal_types    = extradata_nal_types_h264;

        nb_extradata_nal_types = FF_ARRAY_ELEMS(extradata_nal_types_h264);

    }

    ret = ff_h2645_packet_split(&h2645_pkt, pkt->data, pkt->size,

                                ctx, 0, 0, ctx->par_in->codec_id, 1);

    if (ret < 0)

        return ret;

    for (i = 0; i < h2645_pkt.nb_nals; i++) {

        H2645NAL *nal = &h2645_pkt.nals[i];

        if (val_in_array(extradata_nal_types, nb_extradata_nal_types, nal->type)) {

            extradata_size += nal->raw_size + 3;

            if (ctx->par_in->codec_id == AV_CODEC_ID_HEVC) {

                if (nal->type == HEVC_NAL_SPS) has_sps = 1;

                if (nal->type == HEVC_NAL_VPS) has_vps = 1;

            } else {

                if (nal->type == H264_NAL_SPS) has_sps = 1;

            }

        }

    }

    if (extradata_size &&

        ((ctx->par_in->codec_id == AV_CODEC_ID_HEVC && has_sps && has_vps) ||

         (ctx->par_in->codec_id == AV_CODEC_ID_H264 && has_sps))) {

        AVBufferRef *filtered_buf;

        uint8_t *extradata, *filtered_data;

        if (s->remove) {

            filtered_buf = av_buffer_alloc(pkt->size + AV_INPUT_BUFFER_PADDING_SIZE);

            if (!filtered_buf) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            filtered_data = filtered_buf->data;

        }

        extradata = av_malloc(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);

        if (!extradata) {

            av_buffer_unref(&filtered_buf);

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        *data = extradata;

        *size = extradata_size;

        for (i = 0; i < h2645_pkt.nb_nals; i++) {

            H2645NAL *nal = &h2645_pkt.nals[i];

            if (val_in_array(extradata_nal_types, nb_extradata_nal_types,

                             nal->type)) {

                AV_WB24(extradata, 1); // startcode

                memcpy(extradata + 3, nal->raw_data, nal->raw_size);

                extradata += 3 + nal->raw_size;

            } else if (s->remove) {

                AV_WB24(filtered_data, 1); // startcode

                memcpy(filtered_data + 3, nal->raw_data, nal->raw_size);

                filtered_data += 3 + nal->raw_size;

            }

        }

        if (s->remove) {

            av_buffer_unref(&pkt->buf);

            pkt->buf  = filtered_buf;

            pkt->data = filtered_buf->data;

            pkt->size = filtered_data - filtered_buf->data;

        }

    }

fail:

    ff_h2645_packet_uninit(&h2645_pkt);

    return ret;

}


static void FUNC(put_hevc_epel_bi_w_h)(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride,

                                       int16_t *src2,

                                       int height, int denom, int wx0, int wx1,

                                       int ox0, int ox1, intptr_t mx, intptr_t my, int width)

{

    int x, y;

    pixel *src = (pixel *)_src;

    ptrdiff_t srcstride  = _srcstride / sizeof(pixel);

    pixel *dst          = (pixel *)_dst;

    ptrdiff_t dststride = _dststride / sizeof(pixel);

    const int8_t *filter = ff_hevc_epel_filters[mx - 1];

    int shift = 14 + 1 - BIT_DEPTH;

    int log2Wd = denom + shift - 1;

    ox0     = ox0 * (1 << (BIT_DEPTH - 8));

    ox1     = ox1 * (1 << (BIT_DEPTH - 8));

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

        for (x = 0; x < width; x++)

            dst[x] = av_clip_pixel(((EPEL_FILTER(src, 1) >> (BIT_DEPTH - 8)) * wx1 + src2[x] * wx0 +

                                    ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1));

        src  += srcstride;

        dst  += dststride;

        src2 += MAX_PB_SIZE;

    }

}


void sdl2_gl_scanout(DisplayChangeListener *dcl,

                     uint32_t backing_id, bool backing_y_0_top,

                     uint32_t x, uint32_t y,

                     uint32_t w, uint32_t h)

{

    struct sdl2_console *scon = container_of(dcl, struct sdl2_console, dcl);

    assert(scon->opengl);

    scon->x = x;

    scon->y = y;

    scon->w = w;

    scon->h = h;

    scon->tex_id = backing_id;

    scon->y0_top = backing_y_0_top;

    SDL_GL_MakeCurrent(scon->real_window, scon->winctx);

    if (scon->tex_id == 0 || scon->w == 0 || scon->h == 0) {

        sdl2_set_scanout_mode(scon, false);

        return;

    }

    sdl2_set_scanout_mode(scon, true);

    if (!scon->fbo_id) {

        glGenFramebuffers(1, &scon->fbo_id);

    }

    glBindFramebuffer(GL_FRAMEBUFFER_EXT, scon->fbo_id);

    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,

                              GL_TEXTURE_2D, scon->tex_id, 0);

}


static void mm_stop_timer(struct qemu_alarm_timer *t)

{

    timeKillEvent(mm_timer);

    timeEndPeriod(mm_period);

}


static void tcg_out_qemu_st(TCGContext *s, TCGReg data, TCGReg addr,

                            TCGMemOpIdx oi)

{

    TCGMemOp memop = get_memop(oi);

#ifdef CONFIG_SOFTMMU

    unsigned memi = get_mmuidx(oi);

    TCGReg addrz, param;

    tcg_insn_unit *func;

    tcg_insn_unit *label_ptr;

    addrz = tcg_out_tlb_load(s, addr, memi, memop,

                             offsetof(CPUTLBEntry, addr_write));

    /* The fast path is exactly one insn.  Thus we can perform the entire

       TLB Hit in the (annulled) delay slot of the branch over TLB Miss.  */

    /* beq,a,pt %[xi]cc, label0 */

    label_ptr = s->code_ptr;

    tcg_out_bpcc0(s, COND_E, BPCC_A | BPCC_PT

                  | (TARGET_LONG_BITS == 64 ? BPCC_XCC : BPCC_ICC), 0);

    /* delay slot */

    tcg_out_ldst_rr(s, data, addrz, TCG_REG_O1,

                    qemu_st_opc[memop & (MO_BSWAP | MO_SIZE)]);

    /* TLB Miss.  */

    param = TCG_REG_O1;

    if (!SPARC64 && TARGET_LONG_BITS == 64) {

        /* Skip the high-part; we'll perform the extract in the trampoline.  */

        param++;

    }

    tcg_out_mov(s, TCG_TYPE_REG, param++, addr);

    if (!SPARC64 && (memop & MO_SIZE) == MO_64) {

        /* Skip the high-part; we'll perform the extract in the trampoline.  */

        param++;

    }

    tcg_out_mov(s, TCG_TYPE_REG, param++, data);

    func = qemu_st_trampoline[memop & (MO_BSWAP | MO_SIZE)];

    tcg_debug_assert(func != NULL);

    tcg_out_call_nodelay(s, func);

    /* delay slot */

    tcg_out_movi(s, TCG_TYPE_I32, param, oi);

    *label_ptr |= INSN_OFF19(tcg_ptr_byte_diff(s->code_ptr, label_ptr));

#else

    if (SPARC64 && TARGET_LONG_BITS == 32) {

        tcg_out_arithi(s, TCG_REG_T1, addr, 0, SHIFT_SRL);

        addr = TCG_REG_T1;

    }

    tcg_out_ldst_rr(s, data, addr,

                    (guest_base ? TCG_GUEST_BASE_REG : TCG_REG_G0),

                    qemu_st_opc[memop & (MO_BSWAP | MO_SIZE)]);

#endif /* CONFIG_SOFTMMU */

}


QEMUFile *qemu_fopen_fd(int fd)

{

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

    if (s == NULL)

        return NULL;

    s->fd = fd;

    s->file = qemu_fopen_ops(s, fd_put_buffer, fd_get_buffer, fd_close, NULL);

    return s->file;

}


static void pred_spatial_direct_motion(const H264Context *const h, H264SliceContext *sl,

                                       int *mb_type)

{

    int b8_stride = 2;

    int b4_stride = h->b_stride;

    int mb_xy = sl->mb_xy, mb_y = sl->mb_y;

    int mb_type_col[2];

    const int16_t (*l1mv0)[2], (*l1mv1)[2];

    const int8_t *l1ref0, *l1ref1;

    const int is_b8x8 = IS_8X8(*mb_type);

    unsigned int sub_mb_type = MB_TYPE_L0L1;

    int i8, i4;

    int ref[2];

    int mv[2];

    int list;

    assert(sl->ref_list[1][0].reference & 3);

    await_reference_mb_row(h, sl->ref_list[1][0].parent,

                           sl->mb_y + !!IS_INTERLACED(*mb_type));

#define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16 | MB_TYPE_INTRA4x4 | \

                                MB_TYPE_INTRA16x16 | MB_TYPE_INTRA_PCM)

    /* ref = min(neighbors) */

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

        int left_ref     = sl->ref_cache[list][scan8[0] - 1];

        int top_ref      = sl->ref_cache[list][scan8[0] - 8];

        int refc         = sl->ref_cache[list][scan8[0] - 8 + 4];

        const int16_t *C = sl->mv_cache[list][scan8[0]  - 8 + 4];

        if (refc == PART_NOT_AVAILABLE) {

            refc = sl->ref_cache[list][scan8[0] - 8 - 1];

            C    = sl->mv_cache[list][scan8[0]  - 8 - 1];

        }

        ref[list] = FFMIN3((unsigned)left_ref,

                           (unsigned)top_ref,

                           (unsigned)refc);

        if (ref[list] >= 0) {

            /* This is just pred_motion() but with the cases removed that

             * cannot happen for direct blocks. */

            const int16_t *const A = sl->mv_cache[list][scan8[0] - 1];

            const int16_t *const B = sl->mv_cache[list][scan8[0] - 8];

            int match_count = (left_ref == ref[list]) +

                              (top_ref  == ref[list]) +

                              (refc     == ref[list]);

            if (match_count > 1) { // most common

                mv[list] = pack16to32(mid_pred(A[0], B[0], C[0]),

                                      mid_pred(A[1], B[1], C[1]));

            } else {

                assert(match_count == 1);

                if (left_ref == ref[list])

                    mv[list] = AV_RN32A(A);

                else if (top_ref == ref[list])

                    mv[list] = AV_RN32A(B);

                else

                    mv[list] = AV_RN32A(C);

            }

        } else {

            int mask = ~(MB_TYPE_L0 << (2 * list));

            mv[list]  = 0;

            ref[list] = -1;

            if (!is_b8x8)

                *mb_type &= mask;

            sub_mb_type &= mask;

        }

    }

    if (ref[0] < 0 && ref[1] < 0) {

        ref[0] = ref[1] = 0;

        if (!is_b8x8)

            *mb_type |= MB_TYPE_L0L1;

        sub_mb_type |= MB_TYPE_L0L1;

    }

    if (!(is_b8x8 | mv[0] | mv[1])) {

        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);

        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);

        *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                 MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                   MB_TYPE_16x16 | MB_TYPE_DIRECT2;

        return;

    }

    if (IS_INTERLACED(sl->ref_list[1][0].parent->mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL

        if (!IS_INTERLACED(*mb_type)) {                    //     AFR/FR    -> AFL/FL

            mb_y  = (sl->mb_y & ~1) + sl->col_parity;

            mb_xy = sl->mb_x +

                    ((sl->mb_y & ~1) + sl->col_parity) * h->mb_stride;

            b8_stride = 0;

        } else {

            mb_y  += sl->col_fieldoff;

            mb_xy += h->mb_stride * sl->col_fieldoff; // non-zero for FL -> FL & differ parity

        }

        goto single_col;

    } else {                                             // AFL/AFR/FR/FL -> AFR/FR

        if (IS_INTERLACED(*mb_type)) {                   // AFL       /FL -> AFR/FR

            mb_y           =  sl->mb_y & ~1;

            mb_xy          = (sl->mb_y & ~1) * h->mb_stride + sl->mb_x;

            mb_type_col[0] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy + h->mb_stride];

            b8_stride      = 2 + 4 * h->mb_stride;

            b4_stride     *= 6;

            if (IS_INTERLACED(mb_type_col[0]) !=

                IS_INTERLACED(mb_type_col[1])) {

                mb_type_col[0] &= ~MB_TYPE_INTERLACED;

                mb_type_col[1] &= ~MB_TYPE_INTERLACED;

            }

            sub_mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if ((mb_type_col[0] & MB_TYPE_16x16_OR_INTRA) &&

                (mb_type_col[1] & MB_TYPE_16x16_OR_INTRA) &&

                !is_b8x8) {

                *mb_type |= MB_TYPE_16x8 | MB_TYPE_DIRECT2;  /* B_16x8 */

            } else {

                *mb_type |= MB_TYPE_8x8;

            }

        } else {                                         //     AFR/FR    -> AFR/FR

single_col:

            mb_type_col[0] =

            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            sub_mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if (!is_b8x8 && (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)) {

                *mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_16x16 */

            } else if (!is_b8x8 &&

                       (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16))) {

                *mb_type |= MB_TYPE_DIRECT2 |

                            (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16));

            } else {

                if (!h->ps.sps->direct_8x8_inference_flag) {

                    /* FIXME: Save sub mb types from previous frames (or derive

                     * from MVs) so we know exactly what block size to use. */

                    sub_mb_type += (MB_TYPE_8x8 - MB_TYPE_16x16); /* B_SUB_4x4 */

                }

                *mb_type |= MB_TYPE_8x8;

            }

        }

    }

    await_reference_mb_row(h, sl->ref_list[1][0].parent, mb_y);

    l1mv0  = &sl->ref_list[1][0].parent->motion_val[0][h->mb2b_xy[mb_xy]];

    l1mv1  = &sl->ref_list[1][0].parent->motion_val[1][h->mb2b_xy[mb_xy]];

    l1ref0 = &sl->ref_list[1][0].parent->ref_index[0][4 * mb_xy];

    l1ref1 = &sl->ref_list[1][0].parent->ref_index[1][4 * mb_xy];

    if (!b8_stride) {

        if (sl->mb_y & 1) {

            l1ref0 += 2;

            l1ref1 += 2;

            l1mv0  += 2 * b4_stride;

            l1mv1  += 2 * b4_stride;

        }

    }

    if (IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])) {

        int n = 0;

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

            int x8  = i8 & 1;

            int y8  = i8 >> 1;

            int xy8 = x8     + y8 * b8_stride;

            int xy4 = x8 * 3 + y8 * b4_stride;

            int a, b;

            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                continue;

            sl->sub_mb_type[i8] = sub_mb_type;

            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[0], 1);

            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[1], 1);

            if (!IS_INTRA(mb_type_col[y8]) && !sl->ref_list[1][0].parent->long_ref &&

                ((l1ref0[xy8] == 0 &&

                  FFABS(l1mv0[xy4][0]) <= 1 &&

                  FFABS(l1mv0[xy4][1]) <= 1) ||

                 (l1ref0[xy8] < 0 &&

                  l1ref1[xy8] == 0 &&

                  FFABS(l1mv1[xy4][0]) <= 1 &&

                  FFABS(l1mv1[xy4][1]) <= 1))) {

                a =

                b = 0;

                if (ref[0] > 0)

                    a = mv[0];

                if (ref[1] > 0)

                    b = mv[1];

                n++;

            } else {

                a = mv[0];

                b = mv[1];

            }

            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, a, 4);

            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, b, 4);

        }

        if (!is_b8x8 && !(n & 3))

            *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                     MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                       MB_TYPE_16x16 | MB_TYPE_DIRECT2;

    } else if (IS_16X16(*mb_type)) {

        int a, b;

        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

        if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&

            ((l1ref0[0] == 0 &&

              FFABS(l1mv0[0][0]) <= 1 &&

              FFABS(l1mv0[0][1]) <= 1) ||

             (l1ref0[0] < 0 && !l1ref1[0] &&

              FFABS(l1mv1[0][0]) <= 1 &&

              FFABS(l1mv1[0][1]) <= 1 &&

              h->sei.unregistered.x264_build > 33U))) {

            a = b = 0;

            if (ref[0] > 0)

                a = mv[0];

            if (ref[1] > 0)

                b = mv[1];

        } else {

            a = mv[0];

            b = mv[1];

        }

        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);

        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);

    } else {

        int n = 0;

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

            const int x8 = i8 & 1;

            const int y8 = i8 >> 1;

            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                continue;

            sl->sub_mb_type[i8] = sub_mb_type;

            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, mv[0], 4);

            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, mv[1], 4);

            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[0], 1);

            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[1], 1);

            assert(b8_stride == 2);

            /* col_zero_flag */

            if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&

                (l1ref0[i8] == 0 ||

                 (l1ref0[i8] < 0 &&

                  l1ref1[i8] == 0 &&

                  h->sei.unregistered.x264_build > 33U))) {

                const int16_t (*l1mv)[2] = l1ref0[i8] == 0 ? l1mv0 : l1mv1;

                if (IS_SUB_8X8(sub_mb_type)) {

                    const int16_t *mv_col = l1mv[x8 * 3 + y8 * 3 * b4_stride];

                    if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {

                        if (ref[0] == 0)

                            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2,

                                           8, 0, 4);

                        if (ref[1] == 0)

                            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2,

                                           8, 0, 4);

                        n += 4;

                    }

                } else {

                    int m = 0;

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

                        const int16_t *mv_col = l1mv[x8 * 2 + (i4 & 1) +

                                                     (y8 * 2 + (i4 >> 1)) * b4_stride];

                        if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {

                            if (ref[0] == 0)

                                AV_ZERO32(sl->mv_cache[0][scan8[i8 * 4 + i4]]);

                            if (ref[1] == 0)

                                AV_ZERO32(sl->mv_cache[1][scan8[i8 * 4 + i4]]);

                            m++;

                        }

                    }

                    if (!(m & 3))

                        sl->sub_mb_type[i8] += MB_TYPE_16x16 - MB_TYPE_8x8;

                    n += m;

                }

            }

        }

        if (!is_b8x8 && !(n & 15))

            *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                     MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                       MB_TYPE_16x16 | MB_TYPE_DIRECT2;

    }

}


static void boston_lcd_event(void *opaque, int event)

{

    BostonState *s = opaque;

    if (event == CHR_EVENT_OPENED && !s->lcd_inited) {

        qemu_chr_fe_printf(&s->lcd_display, "        ");

        s->lcd_inited = true;

    }

}


void add_command(const cmdinfo_t *ci)

{

    cmdtab = realloc((void *)cmdtab, ++ncmds * sizeof(*cmdtab));

    cmdtab[ncmds - 1] = *ci;

    qsort(cmdtab, ncmds, sizeof(*cmdtab), compare);

}


static void openpic_update_irq(OpenPICState *opp, int n_IRQ)

{

    IRQ_src_t *src;

    int i;

    src = &opp->src[n_IRQ];

    if (!src->pending) {

        /* no irq pending */

        DPRINTF("%s: IRQ %d is not pending\n", __func__, n_IRQ);

        return;

    }

    if (src->ipvp & IPVP_MASK_MASK) {

        /* Interrupt source is disabled */

        DPRINTF("%s: IRQ %d is disabled\n", __func__, n_IRQ);

        return;

    }

    if (IPVP_PRIORITY(src->ipvp) == 0) {

        /* Priority set to zero */

        DPRINTF("%s: IRQ %d has 0 priority\n", __func__, n_IRQ);

        return;

    }

    if (src->ipvp & IPVP_ACTIVITY_MASK) {

        /* IRQ already active */

        DPRINTF("%s: IRQ %d is already active\n", __func__, n_IRQ);

        return;

    }

    if (src->ide == 0) {

        /* No target */

        DPRINTF("%s: IRQ %d has no target\n", __func__, n_IRQ);

        return;

    }

    if (src->ide == (1 << src->last_cpu)) {

        /* Only one CPU is allowed to receive this IRQ */

        IRQ_local_pipe(opp, src->last_cpu, n_IRQ);

    } else if (!(src->ipvp & IPVP_MODE_MASK)) {

        /* Directed delivery mode */

        for (i = 0; i < opp->nb_cpus; i++) {

            if (src->ide & (1 << i)) {

                IRQ_local_pipe(opp, i, n_IRQ);

            }

        }

    } else {

        /* Distributed delivery mode */

        for (i = src->last_cpu + 1; i != src->last_cpu; i++) {

            if (i == opp->nb_cpus)

                i = 0;

            if (src->ide & (1 << i)) {

                IRQ_local_pipe(opp, i, n_IRQ);

                src->last_cpu = i;

                break;

            }

        }

    }

}


static inline void usb_bt_fifo_out_enqueue(struct USBBtState *s,

                struct usb_hci_out_fifo_s *fifo,

                void (*send)(struct HCIInfo *, const uint8_t *, int),

                int (*complete)(const uint8_t *, int),

                const uint8_t *data, int len)

{

    if (fifo->len) {

        memcpy(fifo->data + fifo->len, data, len);

        fifo->len += len;

        if (complete(fifo->data, fifo->len)) {

            send(s->hci, fifo->data, fifo->len);

            fifo->len = 0;

        }

    } else if (complete(data, len))

        send(s->hci, data, len);

    else {

        memcpy(fifo->data, data, len);

        fifo->len = len;

    }

    /* TODO: do we need to loop? */

}


static void compute_status(HTTPContext *c)

{

    HTTPContext *c1;

    FFStream *stream;

    char *p;

    time_t ti;

    int i, len;

    AVIOContext *pb;

    if (avio_open_dyn_buf(&pb) < 0) {

        /* XXX: return an error ? */

        c->buffer_ptr = c->buffer;

        c->buffer_end = c->buffer;

        return;

    }

    avio_printf(pb, "HTTP/1.0 200 OK\r\n");

    avio_printf(pb, "Content-type: %s\r\n", "text/html");

    avio_printf(pb, "Pragma: no-cache\r\n");

    avio_printf(pb, "\r\n");

    avio_printf(pb, "<title>%s Status</title>\n", program_name);

    if (c->stream->feed_filename[0])

        avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);

    avio_printf(pb, "\n");

    avio_printf(pb, "
%s Status
\n", program_name);

    /* format status */

    avio_printf(pb, "
Available Streams
\n");

    avio_printf(pb, "
\n");

    avio_printf(pb, "
PathServed
Conns
bytesFormatBit rate
kbits/sVideo
kbits/s
CodecAudio
kbits/s
CodecFeed\n");

    stream = first_stream;

    while (stream != NULL) {

        char sfilename[1024];

        char *eosf;

        if (stream->feed != stream) {

            av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);

            eosf = sfilename + strlen(sfilename);

            if (eosf - sfilename >= 4) {

                if (strcmp(eosf - 4, ".asf") == 0)

                    strcpy(eosf - 4, ".asx");

                else if (strcmp(eosf - 3, ".rm") == 0)

                    strcpy(eosf - 3, ".ram");

                else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {

                    /* generate a sample RTSP director if

                       unicast. Generate an SDP redirector if

                       multicast */

                    eosf = strrchr(sfilename, '.');

                    if (!eosf)

                        eosf = sfilename + strlen(sfilename);

                    if (stream->is_multicast)

                        strcpy(eosf, ".sdp");

                    else

                        strcpy(eosf, ".rtsp");

                }

            }

            avio_printf(pb, "
%s ",

                         sfilename, stream->filename);

            avio_printf(pb, " %d  ",

                        stream->conns_served);

            fmt_bytecount(pb, stream->bytes_served);

            switch(stream->stream_type) {

            case STREAM_TYPE_LIVE: {

                    int audio_bit_rate = 0;

                    int video_bit_rate = 0;

                    const char *audio_codec_name = "";

                    const char *video_codec_name = "";

                    const char *audio_codec_name_extra = "";

                    const char *video_codec_name_extra = "";

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

                        AVStream *st = stream->streams[i];

                        AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);

                        switch(st->codec->codec_type) {

                        case AVMEDIA_TYPE_AUDIO:

                            audio_bit_rate += st->codec->bit_rate;

                            if (codec) {

                                if (*audio_codec_name)

                                    audio_codec_name_extra = "...";

                                audio_codec_name = codec->name;

                            }

                            break;

                        case AVMEDIA_TYPE_VIDEO:

                            video_bit_rate += st->codec->bit_rate;

                            if (codec) {

                                if (*video_codec_name)

                                    video_codec_name_extra = "...";

                                video_codec_name = codec->name;

                            }

                            break;

                        case AVMEDIA_TYPE_DATA:

                            video_bit_rate += st->codec->bit_rate;

                            break;

                        default:

                            abort();

                        }

                    }

                    avio_printf(pb, " %s  %d  %d  %s %s  %d  %s %s",

                                 stream->fmt->name,

                                 stream->bandwidth,

                                 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,

                                 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);

                    if (stream->feed)

                        avio_printf(pb, "%s", stream->feed->filename);

                    else

                        avio_printf(pb, "%s", stream->feed_filename);

                    avio_printf(pb, "\n");

                }

                break;

            default:

                avio_printf(pb, " -  -  -  - \n");

                break;

            }

        }

        stream = stream->next;

    }

    avio_printf(pb, "
\n");

    stream = first_stream;

    while (stream != NULL) {

        if (stream->feed == stream) {

            avio_printf(pb, "
Feed %s
", stream->filename);

            if (stream->pid) {

                avio_printf(pb, "Running as pid %d.\n", stream->pid);

#if defined(linux) && !defined(CONFIG_NOCUTILS)

                {

                    FILE *pid_stat;

                    char ps_cmd[64];

                    /* This is somewhat linux specific I guess */

                    snprintf(ps_cmd, sizeof(ps_cmd),

                             "ps -o \"%%cpu,cputime\" --no-headers %d",

                             stream->pid);

                    pid_stat = popen(ps_cmd, "r");

                    if (pid_stat) {

                        char cpuperc[10];

                        char cpuused[64];

                        if (fscanf(pid_stat, "%9s %63s", cpuperc,

                                   cpuused) == 2) {

                            avio_printf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",

                                         cpuperc, cpuused);

                        }

                        fclose(pid_stat);

                    }

                }

#endif

                avio_printf(pb, "
");

            }

            avio_printf(pb, "

Streamtypekbits/scodecParameters\n");

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

                AVStream *st = stream->streams[i];

                AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);

                const char *type = "unknown";

                char parameters[64];

                parameters[0] = 0;

                switch(st->codec->codec_type) {

                case AVMEDIA_TYPE_AUDIO:

                    type = "audio";

                    snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz", st->codec->channels, st->codec->sample_rate);

                    break;

                case AVMEDIA_TYPE_VIDEO:

                    type = "video";

                    snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec->width, st->codec->height,

                                st->codec->qmin, st->codec->qmax, st->codec->time_base.den / st->codec->time_base.num);

                    break;

                default:

                    abort();

                }

                avio_printf(pb, "
%d%s%d%s%s\n",

                        i, type, st->codec->bit_rate/1000, codec ? codec->name : "", parameters);

            }

            avio_printf(pb, "
\n");

        }

        stream = stream->next;

    }

    /* connection status */

    avio_printf(pb, "
Connection Status
\n");

    avio_printf(pb, "Number of connections: %d / %d
\n",

                 nb_connections, nb_max_connections);

    avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k
\n",

                 current_bandwidth, max_bandwidth);

    avio_printf(pb, "
\n");

    avio_printf(pb, "
#FileIPProtoStateTarget bits/secActual bits/secBytes transferred\n");

    c1 = first_http_ctx;

    i = 0;

    while (c1 != NULL) {

        int bitrate;

        int j;

        bitrate = 0;

        if (c1->stream) {

            for (j = 0; j < c1->stream->nb_streams; j++) {

                if (!c1->stream->feed)

                    bitrate += c1->stream->streams[j]->codec->bit_rate;

                else if (c1->feed_streams[j] >= 0)

                    bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;

            }

        }

        i++;

        p = inet_ntoa(c1->from_addr.sin_addr);

        avio_printf(pb, "
%d%s%s%s%s%s",

                    i,

                    c1->stream ? c1->stream->filename : "",

                    c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",

                    p,

                    c1->protocol,

                    http_state[c1->state]);

        fmt_bytecount(pb, bitrate);

        avio_printf(pb, "");

        fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);

        avio_printf(pb, "");

        fmt_bytecount(pb, c1->data_count);

        avio_printf(pb, "\n");

        c1 = c1->next;

    }

    avio_printf(pb, "
\n");

    /* date */

    ti = time(NULL);

    p = ctime(&ti);

    avio_printf(pb, "
Generated at %s", p);

    avio_printf(pb, "\n\n");

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

    c->buffer_ptr = c->pb_buffer;

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

}


static int ram_save_compressed_page(QEMUFile *f, PageSearchStatus *pss,

                                    bool last_stage,

                                    uint64_t *bytes_transferred)

{

    int pages = -1;

    uint64_t bytes_xmit;

    uint8_t *p;

    int ret;

    RAMBlock *block = pss->block;

    ram_addr_t offset = pss->offset;

    p = block->host + offset;

    bytes_xmit = 0;

    ret = ram_control_save_page(f, block->offset,

                                offset, TARGET_PAGE_SIZE, &bytes_xmit);

    if (bytes_xmit) {

        *bytes_transferred += bytes_xmit;

        pages = 1;

    }

    if (block == last_sent_block) {

        offset |= RAM_SAVE_FLAG_CONTINUE;

    }

    if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {

        if (ret != RAM_SAVE_CONTROL_DELAYED) {

            if (bytes_xmit > 0) {

                acct_info.norm_pages++;

            } else if (bytes_xmit == 0) {

                acct_info.dup_pages++;

            }

        }

    } else {

        /* When starting the process of a new block, the first page of

         * the block should be sent out before other pages in the same

         * block, and all the pages in last block should have been sent

         * out, keeping this order is important, because the 'cont' flag

         * is used to avoid resending the block name.

         */

        if (block != last_sent_block) {

            flush_compressed_data(f);

            pages = save_zero_page(f, block, offset, p, bytes_transferred);

            if (pages == -1) {

                set_compress_params(&comp_param[0], block, offset);

                /* Use the qemu thread to compress the data to make sure the

                 * first page is sent out before other pages

                 */

                bytes_xmit = do_compress_ram_page(&comp_param[0]);

                acct_info.norm_pages++;

                qemu_put_qemu_file(f, comp_param[0].file);

                *bytes_transferred += bytes_xmit;

                pages = 1;

            }

        } else {

            pages = save_zero_page(f, block, offset, p, bytes_transferred);

            if (pages == -1) {

                pages = compress_page_with_multi_thread(f, block, offset,

                                                        bytes_transferred);

            }

        }

    }

    return pages;

}


void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,

                      bool has_base, const char *base,

                      bool has_backing_file, const char *backing_file,

                      bool has_speed, int64_t speed,

                      bool has_on_error, BlockdevOnError on_error,

                      Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *base_bs = NULL;

    AioContext *aio_context;

    Error *local_err = NULL;

    const char *base_name = NULL;

    if (!has_on_error) {

        on_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    bs = qmp_get_root_bs(device, errp);

    if (!bs) {

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {

        goto out;

    }

    if (has_base) {

        base_bs = bdrv_find_backing_image(bs, base);

        if (base_bs == NULL) {

            error_setg(errp, QERR_BASE_NOT_FOUND, base);

            goto out;

        }

        assert(bdrv_get_aio_context(base_bs) == aio_context);

        base_name = base;

    }

    /* if we are streaming the entire chain, the result will have no backing

     * file, and specifying one is therefore an error */

    if (base_bs == NULL && has_backing_file) {

        error_setg(errp, "backing file specified, but streaming the "

                         "entire chain");

        goto out;

    }

    /* backing_file string overrides base bs filename */

    base_name = has_backing_file ? backing_file : base_name;

    stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,

                 has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    trace_qmp_block_stream(bs, bs->job);

out:

    aio_context_release(aio_context);

}


int ff_dxva2_commit_buffer(AVCodecContext *avctx,

                           AVDXVAContext *ctx,

                           DECODER_BUFFER_DESC *dsc,

                           unsigned type, const void *data, unsigned size,

                           unsigned mb_count)

{

    void     *dxva_data;

    unsigned dxva_size;

    int      result;

    HRESULT hr;

#if CONFIG_D3D11VA

    if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD)

        hr = ID3D11VideoContext_GetDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context,

                                                 D3D11VA_CONTEXT(ctx)->decoder,

                                                 type,

                                                 &dxva_size, &dxva_data);

#endif

#if CONFIG_DXVA2

    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)

        hr = IDirectXVideoDecoder_GetBuffer(DXVA2_CONTEXT(ctx)->decoder, type,

                                            &dxva_data, &dxva_size);

#endif

    if (FAILED(hr)) {

        av_log(avctx, AV_LOG_ERROR, "Failed to get a buffer for %u: 0x%x\n",

               type, hr);

        return -1;

    }

    if (size <= dxva_size) {

        memcpy(dxva_data, data, size);

#if CONFIG_D3D11VA

        if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD) {

            D3D11_VIDEO_DECODER_BUFFER_DESC *dsc11 = dsc;

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

            dsc11->BufferType           = type;

            dsc11->DataSize             = size;

            dsc11->NumMBsInBuffer       = mb_count;

        }

#endif

#if CONFIG_DXVA2

        if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {

            DXVA2_DecodeBufferDesc *dsc2 = dsc;

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

            dsc2->CompressedBufferType = type;

            dsc2->DataSize             = size;

            dsc2->NumMBsInBuffer       = mb_count;

        }

#endif

        result = 0;

    } else {

        av_log(avctx, AV_LOG_ERROR, "Buffer for type %u was too small\n", type);

        result = -1;

    }

#if CONFIG_D3D11VA

    if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD)

        hr = ID3D11VideoContext_ReleaseDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder, type);

#endif

#if CONFIG_DXVA2

    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)

        hr = IDirectXVideoDecoder_ReleaseBuffer(DXVA2_CONTEXT(ctx)->decoder, type);

#endif

    if (FAILED(hr)) {

        av_log(avctx, AV_LOG_ERROR,

               "Failed to release buffer type %u: 0x%x\n",

               type, hr);

        result = -1;

    }

    return result;

}


static int inet_listen_saddr(InetSocketAddress *saddr,

                             int port_offset,

                             bool update_addr,

                             Error **errp)

{

    struct addrinfo ai,*res,*e;

    char port[33];

    char uaddr[INET6_ADDRSTRLEN+1];

    char uport[33];

    int slisten, rc, port_min, port_max, p;

    Error *err = NULL;

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

    ai.ai_flags = AI_PASSIVE;

    if (saddr->has_numeric && saddr->numeric) {

        ai.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;

    }

    ai.ai_family = inet_ai_family_from_address(saddr, &err);

    ai.ai_socktype = SOCK_STREAM;

    if (err) {

        error_propagate(errp, err);

        return -1;

    }

    if (saddr->host == NULL) {

        error_setg(errp, "host not specified");

        return -1;

    }

    if (saddr->port != NULL) {

        pstrcpy(port, sizeof(port), saddr->port);

    } else {

        port[0] = '\0';

    }

    /* lookup */

    if (port_offset) {

        unsigned long long baseport;

        if (strlen(port) == 0) {

            error_setg(errp, "port not specified");

            return -1;

        }

        if (parse_uint_full(port, &baseport, 10) < 0) {

            error_setg(errp, "can't convert to a number: %s", port);

            return -1;

        }

        if (baseport > 65535 ||

            baseport + port_offset > 65535) {

            error_setg(errp, "port %s out of range", port);

            return -1;

        }

        snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);

    }

    rc = getaddrinfo(strlen(saddr->host) ? saddr->host : NULL,

                     strlen(port) ? port : NULL, &ai, &res);

    if (rc != 0) {

        error_setg(errp, "address resolution failed for %s:%s: %s",

                   saddr->host, port, gai_strerror(rc));

        return -1;

    }

    /* create socket + bind */

    for (e = res; e != NULL; e = e->ai_next) {

        getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,

		        uaddr,INET6_ADDRSTRLEN,uport,32,

		        NI_NUMERICHOST | NI_NUMERICSERV);

        slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);

        if (slisten < 0) {

            if (!e->ai_next) {

                error_setg_errno(errp, errno, "Failed to create socket");

            }

            continue;

        }

        socket_set_fast_reuse(slisten);

        port_min = inet_getport(e);

        port_max = saddr->has_to ? saddr->to + port_offset : port_min;

        for (p = port_min; p <= port_max; p++) {

            inet_setport(e, p);

            if (try_bind(slisten, saddr, e) >= 0) {

                goto listen;

            }

            if (p == port_max) {

                if (!e->ai_next) {

                    error_setg_errno(errp, errno, "Failed to bind socket");

                }

            }

        }

        closesocket(slisten);

    }

    freeaddrinfo(res);

    return -1;

listen:

    if (listen(slisten,1) != 0) {

        error_setg_errno(errp, errno, "Failed to listen on socket");

        closesocket(slisten);

        freeaddrinfo(res);

        return -1;

    }

    if (update_addr) {

        g_free(saddr->host);

        saddr->host = g_strdup(uaddr);

        g_free(saddr->port);

        saddr->port = g_strdup_printf("%d",

                                      inet_getport(e) - port_offset);

        saddr->has_ipv6 = saddr->ipv6 = e->ai_family == PF_INET6;

        saddr->has_ipv4 = saddr->ipv4 = e->ai_family != PF_INET6;

    }

    freeaddrinfo(res);

    return slisten;

}


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

{

    AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;

    if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&

        codec->codec_id == AV_CODEC_ID_H264 &&

        atom.size > 11) {

        avio_skip(pb, 10);

        /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */

        if (avio_rb16(pb) == 0xd4d)

            codec->width = 1440;

        return 0;

    }

    return mov_read_avid(c, pb, atom);

}


void vmstate_unregister(const VMStateDescription *vmsd, void *opaque)

{

    SaveStateEntry *se, *new_se;

    TAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {

        if (se->vmsd == vmsd && se->opaque == opaque) {

            TAILQ_REMOVE(&savevm_handlers, se, entry);

            qemu_free(se);

        }

    }

}


static int virtio_net_handle_mac(VirtIONet *n, uint8_t cmd,

                                 struct iovec *iov, unsigned int iov_cnt)

{

    struct virtio_net_ctrl_mac mac_data;

    size_t s;

    NetClientState *nc = qemu_get_queue(n->nic);

    if (cmd == VIRTIO_NET_CTRL_MAC_ADDR_SET) {

        if (iov_size(iov, iov_cnt) != sizeof(n->mac)) {

            return VIRTIO_NET_ERR;

        }

        s = iov_to_buf(iov, iov_cnt, 0, &n->mac, sizeof(n->mac));

        assert(s == sizeof(n->mac));

        qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);

        rxfilter_notify(nc);

        return VIRTIO_NET_OK;

    }

    if (cmd != VIRTIO_NET_CTRL_MAC_TABLE_SET) {

        return VIRTIO_NET_ERR;

    }

    int in_use = 0;

    int first_multi = 0;

    uint8_t uni_overflow = 0;

    uint8_t multi_overflow = 0;

    uint8_t *macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);

    s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,

                   sizeof(mac_data.entries));

    mac_data.entries = ldl_p(&mac_data.entries);

    if (s != sizeof(mac_data.entries)) {

        goto error;

    }

    iov_discard_front(&iov, &iov_cnt, s);

    if (mac_data.entries * ETH_ALEN > iov_size(iov, iov_cnt)) {

        goto error;

    }

    if (mac_data.entries <= MAC_TABLE_ENTRIES) {

        s = iov_to_buf(iov, iov_cnt, 0, macs,

                       mac_data.entries * ETH_ALEN);

        if (s != mac_data.entries * ETH_ALEN) {

            goto error;

        }

        in_use += mac_data.entries;

    } else {

        uni_overflow = 1;

    }

    iov_discard_front(&iov, &iov_cnt, mac_data.entries * ETH_ALEN);

    first_multi = in_use;

    s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,

                   sizeof(mac_data.entries));

    mac_data.entries = ldl_p(&mac_data.entries);

    if (s != sizeof(mac_data.entries)) {

        goto error;

    }

    iov_discard_front(&iov, &iov_cnt, s);

    if (mac_data.entries * ETH_ALEN != iov_size(iov, iov_cnt)) {

        goto error;

    }

    if (in_use + mac_data.entries <= MAC_TABLE_ENTRIES) {

        s = iov_to_buf(iov, iov_cnt, 0, &macs[in_use * ETH_ALEN],

                       mac_data.entries * ETH_ALEN);

        if (s != mac_data.entries * ETH_ALEN) {

            goto error;

        }

        in_use += mac_data.entries;

    } else {

        multi_overflow = 1;

    }

    n->mac_table.in_use = in_use;

    n->mac_table.first_multi = first_multi;

    n->mac_table.uni_overflow = uni_overflow;

    n->mac_table.multi_overflow = multi_overflow;

    memcpy(n->mac_table.macs, macs, MAC_TABLE_ENTRIES * ETH_ALEN);

    g_free(macs);

    rxfilter_notify(nc);

    return VIRTIO_NET_OK;

error:

    g_free(macs);

    return VIRTIO_NET_ERR;

}


static av_cold int ffmmal_init_decoder(AVCodecContext *avctx)
{
    MMALDecodeContext *ctx = avctx->priv_data;
    MMAL_STATUS_T status;
    MMAL_ES_FORMAT_T *format_in;
    MMAL_COMPONENT_T *decoder;
    char tmp[32];
    int ret = 0;
    bcm_host_init();
    if (mmal_vc_init()) {
        av_log(avctx, AV_LOG_ERROR, "Cannot initialize MMAL VC driver!\n");
        return AVERROR(ENOSYS);
    if ((ret = ff_get_format(avctx, avctx->codec->pix_fmts)) < 0)
        return ret;
    avctx->pix_fmt = ret;
    if ((status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &ctx->decoder)))
        goto fail;
    decoder = ctx->decoder;
    format_in = decoder->input[0]->format;
    format_in->type = MMAL_ES_TYPE_VIDEO;
    switch (avctx->codec_id) {
        case AV_CODEC_ID_MPEG2VIDEO:
            format_in->encoding = MMAL_ENCODING_MP2V;
            break;
        case AV_CODEC_ID_MPEG4:
            format_in->encoding = MMAL_ENCODING_MP4V;
            break;
        case AV_CODEC_ID_VC1:
            format_in->encoding = MMAL_ENCODING_WVC1;
            break;
        case AV_CODEC_ID_H264:
        default:
            format_in->encoding = MMAL_ENCODING_H264;
            break;
    format_in->es->video.width = FFALIGN(avctx->width, 32);
    format_in->es->video.height = FFALIGN(avctx->height, 16);
    format_in->es->video.crop.width = avctx->width;
    format_in->es->video.crop.height = avctx->height;
    format_in->es->video.frame_rate.num = 24000;
    format_in->es->video.frame_rate.den = 1001;
    format_in->es->video.par.num = avctx->sample_aspect_ratio.num;
    format_in->es->video.par.den = avctx->sample_aspect_ratio.den;
    format_in->flags = MMAL_ES_FORMAT_FLAG_FRAMED;
    av_get_codec_tag_string(tmp, sizeof(tmp), format_in->encoding);
    av_log(avctx, AV_LOG_DEBUG, "Using MMAL %s encoding.\n", tmp);
    if ((status = mmal_port_format_commit(decoder->input[0])))
        goto fail;
    decoder->input[0]->buffer_num =
        FFMAX(decoder->input[0]->buffer_num_min, 20);
    decoder->input[0]->buffer_size =
        FFMAX(decoder->input[0]->buffer_size_min, 512 * 1024);
    ctx->pool_in = mmal_pool_create(decoder->input[0]->buffer_num, 0);
    if (!ctx->pool_in) {
        ret = AVERROR(ENOMEM);
        goto fail;
    if ((ret = ffmal_update_format(avctx)) < 0)
        goto fail;
    ctx->queue_decoded_frames = mmal_queue_create();
    if (!ctx->queue_decoded_frames)
        goto fail;
    decoder->input[0]->userdata = (void*)avctx;
    decoder->output[0]->userdata = (void*)avctx;
    decoder->control->userdata = (void*)avctx;
    if ((status = mmal_port_enable(decoder->control, control_port_cb)))
        goto fail;
    if ((status = mmal_port_enable(decoder->input[0], input_callback)))
        goto fail;
    if ((status = mmal_port_enable(decoder->output[0], output_callback)))
        goto fail;
    if ((status = mmal_component_enable(decoder)))
        goto fail;
    return 0;
fail:
    ffmmal_close_decoder(avctx);
    return ret < 0 ? ret : AVERROR_UNKNOWN;


static int ogg_get_length(AVFormatContext *s)

{

    struct ogg *ogg = s->priv_data;

    int i;

    int64_t size, end;

    int streams_left=0;

    if(!s->pb->seekable)

        return 0;

// already set

    if (s->duration != AV_NOPTS_VALUE)

        return 0;

    size = avio_size(s->pb);

    if(size < 0)

        return 0;

    end = size > MAX_PAGE_SIZE? size - MAX_PAGE_SIZE: 0;

    ogg_save (s);

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

    while (!ogg_read_page (s, &i)){

        if (ogg->streams[i].granule != -1 && ogg->streams[i].granule != 0 &&

            ogg->streams[i].codec) {

            s->streams[i]->duration =

                ogg_gptopts (s, i, ogg->streams[i].granule, NULL);

            if (s->streams[i]->start_time != AV_NOPTS_VALUE){

                s->streams[i]->duration -= s->streams[i]->start_time;

                streams_left-= (ogg->streams[i].got_start==-1);

                ogg->streams[i].got_start= 1;

            }else if(!ogg->streams[i].got_start){

                ogg->streams[i].got_start= -1;

                streams_left++;

            }

        }

    }

    ogg_restore (s, 0);

    ogg_save (s);

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

    ogg_reset(s);

    while (!ogg_packet(s, &i, NULL, NULL, NULL)) {

        int64_t pts = ogg_calc_pts(s, i, NULL);

        if (pts != AV_NOPTS_VALUE && s->streams[i]->start_time == AV_NOPTS_VALUE && !ogg->streams[i].got_start){

            s->streams[i]->duration -= pts;

            ogg->streams[i].got_start= 1;

            streams_left--;

        }else if(s->streams[i]->start_time != AV_NOPTS_VALUE && !ogg->streams[i].got_start){

            ogg->streams[i].got_start= 1;

            streams_left--;

        }

        }

            if(streams_left<=0)

                break;

    }

    ogg_restore (s, 0);

    return 0;

}


static int mimic_decode_frame(AVCodecContext *avctx, void *data,

                              int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MimicContext *ctx = avctx->priv_data;

    GetByteContext gb;

    int is_pframe;

    int width, height;

    int quality, num_coeffs;

    int swap_buf_size = buf_size - MIMIC_HEADER_SIZE;

    if (buf_size <= MIMIC_HEADER_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "insufficient data\n");

        return -1;

    }

    bytestream2_init(&gb, buf, MIMIC_HEADER_SIZE);

    bytestream2_skip(&gb, 2); /* some constant (always 256) */

    quality    = bytestream2_get_le16u(&gb);

    width      = bytestream2_get_le16u(&gb);

    height     = bytestream2_get_le16u(&gb);

    bytestream2_skip(&gb, 4); /* some constant */

    is_pframe  = bytestream2_get_le32u(&gb);

    num_coeffs = bytestream2_get_byteu(&gb);

    bytestream2_skip(&gb, 3); /* some constant */

    if(!ctx->avctx) {

        int i;

        if(!(width == 160 && height == 120) &&

           !(width == 320 && height == 240)) {

            av_log(avctx, AV_LOG_ERROR, "invalid width/height!\n");

            return -1;

        }

        ctx->avctx     = avctx;

        avctx->width   = width;

        avctx->height  = height;

        avctx->pix_fmt = PIX_FMT_YUV420P;

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

            ctx->num_vblocks[i] = -((-height) >> (3 + !!i));

            ctx->num_hblocks[i] =     width   >> (3 + !!i) ;

        }

    } else if(width != ctx->avctx->width || height != ctx->avctx->height) {

        av_log(avctx, AV_LOG_ERROR, "resolution changing is not supported\n");

        return -1;

    }

    if(is_pframe && !ctx->buf_ptrs[ctx->prev_index].data[0]) {

        av_log(avctx, AV_LOG_ERROR, "decoding must start with keyframe\n");

        return -1;

    }

    ctx->buf_ptrs[ctx->cur_index].reference = 1;

    ctx->buf_ptrs[ctx->cur_index].pict_type = is_pframe ? AV_PICTURE_TYPE_P:AV_PICTURE_TYPE_I;

    if(ff_thread_get_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index])) {

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

        return -1;

    }

    ctx->next_prev_index = ctx->cur_index;

    ctx->next_cur_index  = (ctx->cur_index - 1) & 15;

    prepare_avpic(ctx, &ctx->flipped_ptrs[ctx->cur_index],

                  (AVPicture*) &ctx->buf_ptrs[ctx->cur_index]);

    ff_thread_finish_setup(avctx);

    av_fast_malloc(&ctx->swap_buf, &ctx->swap_buf_size,

                                 swap_buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if(!ctx->swap_buf)

        return AVERROR(ENOMEM);

    ctx->dsp.bswap_buf(ctx->swap_buf,

                        (const uint32_t*) (buf + MIMIC_HEADER_SIZE),

                        swap_buf_size>>2);

    init_get_bits(&ctx->gb, ctx->swap_buf, swap_buf_size << 3);

    if(!decode(ctx, quality, num_coeffs, !is_pframe)) {

        if (avctx->active_thread_type&FF_THREAD_FRAME)

            ff_thread_report_progress(&ctx->buf_ptrs[ctx->cur_index], INT_MAX, 0);

        else {

            ff_thread_release_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index]);

            return -1;

        }

    }

    *(AVFrame*)data = ctx->buf_ptrs[ctx->cur_index];

    *data_size = sizeof(AVFrame);

    ctx->prev_index = ctx->next_prev_index;

    ctx->cur_index  = ctx->next_cur_index;

    /* Only release frames that aren't used for backreferences anymore */

    if(ctx->buf_ptrs[ctx->cur_index].data[0])

        ff_thread_release_buffer(avctx, &ctx->buf_ptrs[ctx->cur_index]);

    return buf_size;

}


static int ipvideo_decode_block_opcode_0x8(IpvideoContext *s)

{

    int x, y;

    unsigned char P[2];

    unsigned int flags = 0;

    /* 2-color encoding for each 4x4 quadrant, or 2-color encoding on

     * either top and bottom or left and right halves */

    CHECK_STREAM_PTR(2);

    P[0] = *s->stream_ptr++;

    P[1] = *s->stream_ptr++;

    if (P[0] <= P[1]) {

        CHECK_STREAM_PTR(14);

        s->stream_ptr -= 2;

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

            // new values for each 4x4 block

            if (!(y & 3)) {

                P[0] = *s->stream_ptr++; P[1] = *s->stream_ptr++;

                flags = bytestream_get_le16(&s->stream_ptr);

            }

            for (x = 0; x < 4; x++, flags >>= 1)

                *s->pixel_ptr++ = P[flags & 1];

            s->pixel_ptr += s->stride - 4;

            // switch to right half

            if (y == 7) s->pixel_ptr -= 8 * s->stride - 4;

        }

    } else {

        /* need 10 more bytes */

        CHECK_STREAM_PTR(10);

        if (s->stream_ptr[4] <= s->stream_ptr[5]) {

            flags = bytestream_get_le32(&s->stream_ptr);

            /* vertical split; left & right halves are 2-color encoded */

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

                for (x = 0; x < 4; x++, flags >>= 1)

                    *s->pixel_ptr++ = P[flags & 1];

                s->pixel_ptr += s->stride - 4;

                // switch to right half

                if (y == 7) {

                    s->pixel_ptr -= 8 * s->stride - 4;

                    P[0] = *s->stream_ptr++; P[1] = *s->stream_ptr++;

                    flags = bytestream_get_le32(&s->stream_ptr);

                }

            }

        } else {

            /* horizontal split; top & bottom halves are 2-color encoded */

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

                if (y == 4) {

                    P[0] = *s->stream_ptr++;

                    P[1] = *s->stream_ptr++;

                }

                flags = *s->stream_ptr++ | 0x100;

                for (; flags != 1; flags >>= 1)

                    *s->pixel_ptr++ = P[flags & 1];

                s->pixel_ptr += s->line_inc;

            }

        }

    }

    /* report success */

    return 0;

}


static int gdb_set_avr_reg(CPUState *env, uint8_t *mem_buf, int n)

{

    if (n < 32) {

#ifdef WORDS_BIGENDIAN

        env->avr[n].u64[0] = ldq_p(mem_buf);

        env->avr[n].u64[1] = ldq_p(mem_buf+8);

#else

        env->avr[n].u64[1] = ldq_p(mem_buf);

        env->avr[n].u64[0] = ldq_p(mem_buf+8);

#endif

        return 16;

    }

    if (n == 33) {

        env->vscr = ldl_p(mem_buf);

        return 4;

    }

    if (n == 34) {

        env->spr[SPR_VRSAVE] = (target_ulong)ldl_p(mem_buf);

        return 4;

    }

    return 0;

}


static void vga_draw_text(VGACommonState *s, int full_update)

{

    DisplaySurface *surface = qemu_console_surface(s->con);

    int cx, cy, cheight, cw, ch, cattr, height, width, ch_attr;

    int cx_min, cx_max, linesize, x_incr, line, line1;

    uint32_t offset, fgcol, bgcol, v, cursor_offset;

    uint8_t *d1, *d, *src, *dest, *cursor_ptr;

    const uint8_t *font_ptr, *font_base[2];

    int dup9, line_offset;

    uint32_t *palette;

    uint32_t *ch_attr_ptr;

    int64_t now = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);

    /* compute font data address (in plane 2) */

    v = s->sr[VGA_SEQ_CHARACTER_MAP];

    offset = (((v >> 4) & 1) | ((v << 1) & 6)) * 8192 * 4 + 2;

    if (offset != s->font_offsets[0]) {

        s->font_offsets[0] = offset;

        full_update = 1;

    }

    font_base[0] = s->vram_ptr + offset;

    offset = (((v >> 5) & 1) | ((v >> 1) & 6)) * 8192 * 4 + 2;

    font_base[1] = s->vram_ptr + offset;

    if (offset != s->font_offsets[1]) {

        s->font_offsets[1] = offset;

        full_update = 1;

    }

    if (s->plane_updated & (1 << 2) || s->has_chain4_alias) {

        /* if the plane 2 was modified since the last display, it

           indicates the font may have been modified */

        s->plane_updated = 0;

        full_update = 1;

    }

    full_update |= update_basic_params(s);

    line_offset = s->line_offset;

    vga_get_text_resolution(s, &width, &height, &cw, &cheight);

    if ((height * width) <= 1) {

        /* better than nothing: exit if transient size is too small */

        return;

    }

    if ((height * width) > CH_ATTR_SIZE) {

        /* better than nothing: exit if transient size is too big */

        return;

    }

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

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

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

        surface = qemu_console_surface(s->con);

        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;

    }

    full_update |= update_palette16(s);

    palette = s->last_palette;

    x_incr = cw * surface_bytes_per_pixel(surface);

    if (full_update) {

        s->full_update_text = 1;

    }

    if (s->full_update_gfx) {

        s->full_update_gfx = 0;

        full_update |= 1;

    }

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

      /* if the cursor position changed, we update the old and new

         chars */

        if (s->cursor_offset < CH_ATTR_SIZE)

            s->last_ch_attr[s->cursor_offset] = -1;

        if (cursor_offset < CH_ATTR_SIZE)

            s->last_ch_attr[cursor_offset] = -1;

        s->cursor_offset = cursor_offset;

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

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

    }

    cursor_ptr = s->vram_ptr + (s->start_addr + cursor_offset) * 4;

    if (now >= s->cursor_blink_time) {

        s->cursor_blink_time = now + VGA_TEXT_CURSOR_PERIOD_MS / 2;

        s->cursor_visible_phase = !s->cursor_visible_phase;

    }

    dest = surface_data(surface);

    linesize = surface_stride(surface);

    ch_attr_ptr = s->last_ch_attr;

    line = 0;

    offset = s->start_addr * 4;

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

        d1 = dest;

        src = s->vram_ptr + offset;

        cx_min = width;

        cx_max = -1;

        for(cx = 0; cx < width; cx++) {

            ch_attr = *(uint16_t *)src;

            if (full_update || ch_attr != *ch_attr_ptr || src == cursor_ptr) {

                if (cx < cx_min)

                    cx_min = cx;

                if (cx > cx_max)

                    cx_max = cx;

                *ch_attr_ptr = ch_attr;

#ifdef HOST_WORDS_BIGENDIAN

                ch = ch_attr >> 8;

                cattr = ch_attr & 0xff;

#else

                ch = ch_attr & 0xff;

                cattr = ch_attr >> 8;

#endif

                font_ptr = font_base[(cattr >> 3) & 1];

                font_ptr += 32 * 4 * ch;

                bgcol = palette[cattr >> 4];

                fgcol = palette[cattr & 0x0f];

                if (cw == 16) {

                    vga_draw_glyph16(d1, linesize,

                                     font_ptr, cheight, fgcol, bgcol);

                } else if (cw != 9) {

                    vga_draw_glyph8(d1, linesize,

                                    font_ptr, cheight, fgcol, bgcol);

                } else {

                    dup9 = 0;

                    if (ch >= 0xb0 && ch <= 0xdf &&

                        (s->ar[VGA_ATC_MODE] & 0x04)) {

                        dup9 = 1;

                    }

                    vga_draw_glyph9(d1, linesize,

                                    font_ptr, cheight, fgcol, bgcol, dup9);

                }

                if (src == cursor_ptr &&

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

                    s->cursor_visible_phase) {

                    int line_start, line_last, h;

                    /* draw the cursor */

                    line_start = s->cr[VGA_CRTC_CURSOR_START] & 0x1f;

                    line_last = s->cr[VGA_CRTC_CURSOR_END] & 0x1f;

                    /* XXX: check that */

                    if (line_last > cheight - 1)

                        line_last = cheight - 1;

                    if (line_last >= line_start && line_start < cheight) {

                        h = line_last - line_start + 1;

                        d = d1 + linesize * line_start;

                        if (cw == 16) {

                            vga_draw_glyph16(d, linesize,

                                             cursor_glyph, h, fgcol, bgcol);

                        } else if (cw != 9) {

                            vga_draw_glyph8(d, linesize,

                                            cursor_glyph, h, fgcol, bgcol);

                        } else {

                            vga_draw_glyph9(d, linesize,

                                            cursor_glyph, h, fgcol, bgcol, 1);

                        }

                    }

                }

            }

            d1 += x_incr;

            src += 4;

            ch_attr_ptr++;

        }

        if (cx_max != -1) {

            dpy_gfx_update(s->con, cx_min * cw, cy * cheight,

                           (cx_max - cx_min + 1) * cw, cheight);

        }

        dest += linesize * cheight;

        line1 = line + cheight;

        offset += line_offset;

        if (line < s->line_compare && line1 >= s->line_compare) {

            offset = 0;

        }

        line = line1;

    }

}


int64_t qemu_ftell(QEMUFile *f)

{

    qemu_fflush(f);

    return f->pos;

}


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

{

    LibQuviContext *qc = s->priv_data;

    return av_read_frame(qc->fmtctx, pkt);

}


static PCIDevice *qemu_pci_hot_add_storage(Monitor *mon,

                                           const char *devaddr,

                                           const char *opts)

{

    PCIDevice *dev;

    DriveInfo *dinfo = NULL;

    int type = -1;

    char buf[128];

    PCIBus *bus;

    int devfn;

    if (get_param_value(buf, sizeof(buf), "if", opts)) {

        if (!strcmp(buf, "scsi"))

            type = IF_SCSI;

        else if (!strcmp(buf, "virtio")) {

            type = IF_VIRTIO;

        } else {

            monitor_printf(mon, "type %s not a hotpluggable PCI device.\n", buf);

            return NULL;

        }

    } else {

        monitor_printf(mon, "no if= specified\n");

        return NULL;

    }

    if (get_param_value(buf, sizeof(buf), "file", opts)) {

        dinfo = add_init_drive(opts);

        if (!dinfo)

            return NULL;

        if (dinfo->devaddr) {

            monitor_printf(mon, "Parameter addr not supported\n");

            return NULL;

        }

    } else {

        dinfo = NULL;

    }

    bus = pci_get_bus_devfn(&devfn, devaddr);

    if (!bus) {

        monitor_printf(mon, "Invalid PCI device address %s\n", devaddr);

        return NULL;

    }

    switch (type) {

    case IF_SCSI:

        if (!dinfo) {

            monitor_printf(mon, "scsi requires a backing file/device.\n");

            return NULL;

        }

        dev = pci_create(bus, devfn, "lsi53c895a");

        if (qdev_init(&dev->qdev) < 0)

            dev = NULL;

        if (dev) {

            BusState *scsibus = QLIST_FIRST(&dev->qdev.child_bus);

            scsi_bus_legacy_add_drive(DO_UPCAST(SCSIBus, qbus, scsibus),

                                      dinfo, dinfo->unit);

        }

        break;

    case IF_VIRTIO:

        if (!dinfo) {

            monitor_printf(mon, "virtio requires a backing file/device.\n");

            return NULL;

        }

        dev = pci_create(bus, devfn, "virtio-blk-pci");

        qdev_prop_set_drive(&dev->qdev, "drive", dinfo);

        if (qdev_init(&dev->qdev) < 0)

            dev = NULL;

        break;

    default:

        dev = NULL;

    }

    return dev;

}


uint16_t eeprom93xx_read(eeprom_t *eeprom)

{

    /* Return status of pin DO (0 or 1). */

    logout("CS=%u DO=%u\n", eeprom->eecs, eeprom->eedo);

    return (eeprom->eedo);

}


static void sysctl_write(void *opaque, target_phys_addr_t addr, uint32_t value)

{

    MilkymistSysctlState *s = opaque;

    trace_milkymist_sysctl_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_GPIO_OUT:

    case R_GPIO_INTEN:

    case R_TIMER0_COUNTER:

        if (value > s->regs[R_TIMER0_COUNTER]) {

            value = s->regs[R_TIMER0_COUNTER];

            error_report("milkymist_sysctl: timer0: trying to write a "

                    "value greater than the limit. Clipping.");

        }

        /* milkymist timer counts up */

        value = s->regs[R_TIMER0_COUNTER] - value;

        ptimer_set_count(s->ptimer0, value);

        break;

    case R_TIMER1_COUNTER:

        if (value > s->regs[R_TIMER1_COUNTER]) {

            value = s->regs[R_TIMER1_COUNTER];

            error_report("milkymist_sysctl: timer1: trying to write a "

                    "value greater than the limit. Clipping.");

        }

        /* milkymist timer counts up */

        value = s->regs[R_TIMER1_COUNTER] - value;

        ptimer_set_count(s->ptimer1, value);

        break;

    case R_TIMER0_COMPARE:

        ptimer_set_limit(s->ptimer0, value, 0);

        s->regs[addr] = value;

        break;

    case R_TIMER1_COMPARE:

        ptimer_set_limit(s->ptimer1, value, 0);

        s->regs[addr] = value;

        break;

    case R_TIMER0_CONTROL:

        s->regs[addr] = value;

        if (s->regs[R_TIMER0_CONTROL] & CTRL_ENABLE) {

            trace_milkymist_sysctl_start_timer1();

            ptimer_run(s->ptimer0, 0);

        } else {

            trace_milkymist_sysctl_stop_timer1();

            ptimer_stop(s->ptimer0);

        }

        break;

    case R_TIMER1_CONTROL:

        s->regs[addr] = value;

        if (s->regs[R_TIMER1_CONTROL] & CTRL_ENABLE) {

            trace_milkymist_sysctl_start_timer1();

            ptimer_run(s->ptimer1, 0);

        } else {

            trace_milkymist_sysctl_stop_timer1();

            ptimer_stop(s->ptimer1);

        }

        break;

    case R_ICAP:

        sysctl_icap_write(s, value);

        break;

    case R_SYSTEM_ID:

        qemu_system_reset_request();

        break;

    case R_GPIO_IN:

    case R_CAPABILITIES:

        error_report("milkymist_sysctl: write to read-only register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    default:

        error_report("milkymist_sysctl: write access to unkown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

}


AVFrame *avcodec_alloc_frame(void)

{

    AVFrame *frame = av_mallocz(sizeof(AVFrame));

    if (frame == NULL)

        return NULL;

FF_DISABLE_DEPRECATION_WARNINGS

    avcodec_get_frame_defaults(frame);

FF_ENABLE_DEPRECATION_WARNINGS

    return frame;

}


static int add_hfyu_left_prediction_int16_c(uint16_t *dst, const uint16_t *src, unsigned mask, int w, int acc){

    int i;

    for(i=0; i<w-1; i++){

        acc+= src[i];

        dst[i]= acc & mask;

        i++;

        acc+= src[i];

        dst[i]= acc & mask;

    }

    for(; i<w; i++){

        acc+= src[i];

        dst[i]= acc & mask;

    }

    return acc;

}


qemu_irq *pxa2xx_pic_init(target_phys_addr_t base, CPUState *env)

{

    PXA2xxPICState *s;

    int iomemtype;

    qemu_irq *qi;

    s = (PXA2xxPICState *)

            qemu_mallocz(sizeof(PXA2xxPICState));

    if (!s)

        return NULL;

    s->cpu_env = env;

    s->int_pending[0] = 0;

    s->int_pending[1] = 0;

    s->int_enabled[0] = 0;

    s->int_enabled[1] = 0;

    s->is_fiq[0] = 0;

    s->is_fiq[1] = 0;

    qi = qemu_allocate_irqs(pxa2xx_pic_set_irq, s, PXA2XX_PIC_SRCS);

    /* Enable IC memory-mapped registers access.  */

    iomemtype = cpu_register_io_memory(pxa2xx_pic_readfn,

                    pxa2xx_pic_writefn, s, DEVICE_NATIVE_ENDIAN);

    cpu_register_physical_memory(base, 0x00100000, iomemtype);

    /* Enable IC coprocessor access.  */

    cpu_arm_set_cp_io(env, 6, pxa2xx_pic_cp_read, pxa2xx_pic_cp_write, s);

    register_savevm(NULL, "pxa2xx_pic", 0, 0, pxa2xx_pic_save,

                    pxa2xx_pic_load, s);

    return qi;

}


int net_init_vde(QemuOpts *opts, const NetClientOptions *new_opts,

                 const char *name, VLANState *vlan)

{

    const char *sock;

    const char *group;

    int port, mode;

    sock  = qemu_opt_get(opts, "sock");

    group = qemu_opt_get(opts, "group");

    port = qemu_opt_get_number(opts, "port", 0);

    mode = qemu_opt_get_number(opts, "mode", 0700);

    if (net_vde_init(vlan, "vde", name, sock, port, group, mode) == -1) {

        return -1;

    }

    return 0;

}


static const ID3v2EMFunc *get_extra_meta_func(const char *tag, int isv34)

{

    int i = 0;

    while (ff_id3v2_extra_meta_funcs[i].tag3) {

        if (!memcmp(tag,

                    (isv34 ?

                        ff_id3v2_extra_meta_funcs[i].tag4 :

                        ff_id3v2_extra_meta_funcs[i].tag3),

                    (isv34 ? 4 : 3)))

            return &ff_id3v2_extra_meta_funcs[i];

        i++;

    }

    return NULL;

}


int av_buffersrc_add_ref(AVFilterContext *buffer_filter,

                         AVFilterBufferRef *picref, int flags)

{

    BufferSourceContext *c = buffer_filter->priv;

    AVFilterBufferRef *buf;

    int ret;

    if (!picref) {

        c->eof = 1;

        return 0;

    } else if (c->eof)

        return AVERROR(EINVAL);

    if (!av_fifo_space(c->fifo) &&

        (ret = av_fifo_realloc2(c->fifo, av_fifo_size(c->fifo) +

                                         sizeof(buf))) < 0)

        return ret;

    if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {

        ret = check_format_change(buffer_filter, picref);

        if (ret < 0)

            return ret;

    }

    if (flags & AV_BUFFERSRC_FLAG_NO_COPY)

        buf = picref;

    else

        buf = copy_buffer_ref(buffer_filter, picref);

    if ((ret = av_fifo_generic_write(c->fifo, &buf, sizeof(buf), NULL)) < 0) {

        if (buf != picref)

            avfilter_unref_buffer(buf);

        return ret;

    }

    c->nb_failed_requests = 0;

    return 0;

}


static void qstring_destroy_obj(QObject *obj)

{

    QString *qs;

    assert(obj != NULL);

    qs = qobject_to_qstring(obj);

    g_free(qs->string);

    g_free(qs);

}


bool aio_pending(AioContext *ctx)

{

    AioHandler *node;

    bool result = false;

    /*

     * We have to walk very carefully in case aio_set_fd_handler is

     * called while we're walking.

     */

    qemu_lockcnt_inc(&ctx->list_lock);

    QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {

        if (node->pfd.revents && node->io_notify) {

            result = true;

            break;

        }

        if ((node->pfd.revents & G_IO_IN) && node->io_read) {

            result = true;

            break;

        }

        if ((node->pfd.revents & G_IO_OUT) && node->io_write) {

            result = true;

            break;

        }

    }

    qemu_lockcnt_dec(&ctx->list_lock);

    return result;

}


static size_t get_request_size(VirtQueue *vq)

{

    unsigned int in, out;

    virtqueue_get_avail_bytes(vq, &in, &out);

    return in;

}


static void do_quit(int argc, const char **argv)

{

    exit(0);

}


static void pc_init1(ram_addr_t ram_size,

                     const char *boot_device,

                     const char *kernel_filename,

                     const char *kernel_cmdline,

                     const char *initrd_filename,

                     const char *cpu_model,

                     int pci_enabled,

                     int kvmclock_enabled)

{

    int i;

    ram_addr_t below_4g_mem_size, above_4g_mem_size;

    PCIBus *pci_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *cpu_irq;

    qemu_irq *isa_irq;

    qemu_irq *i8259;

    qemu_irq *cmos_s3;

    qemu_irq *smi_irq;

    IsaIrqState *isa_irq_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    FDCtrl *floppy_controller;

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    pc_cpus_init(cpu_model);

    if (kvmclock_enabled) {

        kvmclock_create();

    }

    /* allocate ram and load rom/bios */

    pc_memory_init(ram_size, kernel_filename, kernel_cmdline, initrd_filename,

                   &below_4g_mem_size, &above_4g_mem_size);

    cpu_irq = pc_allocate_cpu_irq();

    i8259 = i8259_init(cpu_irq[0]);

    isa_irq_state = qemu_mallocz(sizeof(*isa_irq_state));

    isa_irq_state->i8259 = i8259;

    if (pci_enabled) {

        ioapic_init(isa_irq_state);

    }

    isa_irq = qemu_allocate_irqs(isa_irq_handler, isa_irq_state, 24);

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, isa_irq, ram_size);

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus_new(NULL);

    }

    isa_bus_irqs(isa_irq);

    pc_register_ferr_irq(isa_reserve_irq(13));

    pc_vga_init(pci_enabled? pci_bus: NULL);

    /* init basic PC hardware */

    pc_basic_device_init(isa_irq, &floppy_controller, &rtc_state);

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

        NICInfo *nd = &nd_table[i];

        if (!pci_enabled || (nd->model && strcmp(nd->model, "ne2k_isa") == 0))

            pc_init_ne2k_isa(nd);

        else

            pci_nic_init_nofail(nd, "e1000", NULL);

    }

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

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

        exit(1);

    }

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

        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

    }

    if (pci_enabled) {

        PCIDevice *dev;

        dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            dev = isa_ide_init(ide_iobase[i], ide_iobase2[i], ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            idebus[i] = qdev_get_child_bus(&dev->qdev, "ide.0");

        }

    }

    audio_init(isa_irq, pci_enabled ? pci_bus : NULL);

    pc_cmos_init(below_4g_mem_size, above_4g_mem_size, boot_device,

                 idebus[0], idebus[1], floppy_controller, rtc_state);

    if (pci_enabled && usb_enabled) {

        usb_uhci_piix3_init(pci_bus, piix3_devfn + 2);

    }

    if (pci_enabled && acpi_enabled) {

        uint8_t *eeprom_buf = qemu_mallocz(8 * 256); /* XXX: make this persistent */

        i2c_bus *smbus;

        cmos_s3 = qemu_allocate_irqs(pc_cmos_set_s3_resume, rtc_state, 1);

        smi_irq = qemu_allocate_irqs(pc_acpi_smi_interrupt, first_cpu, 1);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              isa_reserve_irq(9), *cmos_s3, *smi_irq,

                              kvm_enabled());

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

            DeviceState *eeprom;

            eeprom = qdev_create((BusState *)smbus, "smbus-eeprom");

            qdev_prop_set_uint8(eeprom, "address", 0x50 + i);

            qdev_prop_set_ptr(eeprom, "data", eeprom_buf + (i * 256));

            qdev_init_nofail(eeprom);

        }

    }

    if (i440fx_state) {

        i440fx_init_memory_mappings(i440fx_state);

    }

    if (pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

}


static av_cold int roq_decode_init(AVCodecContext *avctx)

{

    RoqContext *s = avctx->priv_data;

    s->avctx = avctx;

    if (avctx->width % 16 || avctx->height % 16) {

        av_log(avctx, AV_LOG_ERROR,

               "Dimensions must be a multiple of 16\n");

        return AVERROR_PATCHWELCOME;

    }

    s->width = avctx->width;

    s->height = avctx->height;

    s->last_frame    = av_frame_alloc();

    s->current_frame = av_frame_alloc();

    if (!s->current_frame || !s->last_frame) {

        av_frame_free(&s->current_frame);

        av_frame_free(&s->last_frame);

        return AVERROR(ENOMEM);

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV444P;

    return 0;

}


static int usb_bt_handle_data(USBDevice *dev, USBPacket *p)

{

    struct USBBtState *s = (struct USBBtState *) dev->opaque;

    int ret = 0;

    if (!s->config)

        goto fail;

    switch (p->pid) {

    case USB_TOKEN_IN:

        switch (p->devep & 0xf) {

        case USB_EVT_EP:

            ret = usb_bt_fifo_dequeue(&s->evt, p);

            break;

        case USB_ACL_EP:

            ret = usb_bt_fifo_dequeue(&s->acl, p);

            break;

        case USB_SCO_EP:

            ret = usb_bt_fifo_dequeue(&s->sco, p);

            break;

        default:

            goto fail;

        }

        break;

    case USB_TOKEN_OUT:

        switch (p->devep & 0xf) {

        case USB_ACL_EP:

            usb_bt_fifo_out_enqueue(s, &s->outacl, s->hci->acl_send,

                            usb_bt_hci_acl_complete, p->data, p->len);

            break;

        case USB_SCO_EP:

            usb_bt_fifo_out_enqueue(s, &s->outsco, s->hci->sco_send,

                            usb_bt_hci_sco_complete, p->data, p->len);

            break;

        default:

            goto fail;

        }

        break;

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


static void rtas_ibm_read_slot_reset_state2(PowerPCCPU *cpu,

                                            sPAPREnvironment *spapr,

                                            uint32_t token, uint32_t nargs,

                                            target_ulong args, uint32_t nret,

                                            target_ulong rets)

{

    sPAPRPHBState *sphb;

    sPAPRPHBClass *spc;

    uint64_t buid;

    int state, ret;

    if ((nargs != 3) || (nret != 4 && nret != 5)) {

        goto param_error_exit;

    }

    buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    sphb = find_phb(spapr, buid);

    if (!sphb) {

        goto param_error_exit;

    }

    spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);

    if (!spc->eeh_get_state) {

        goto param_error_exit;

    }

    ret = spc->eeh_get_state(sphb, &state);

    rtas_st(rets, 0, ret);

    if (ret != RTAS_OUT_SUCCESS) {

        return;

    }

    rtas_st(rets, 1, state);

    rtas_st(rets, 2, RTAS_EEH_SUPPORT);

    rtas_st(rets, 3, RTAS_EEH_PE_UNAVAIL_INFO);

    if (nret >= 5) {

        rtas_st(rets, 4, RTAS_EEH_PE_RECOVER_INFO);

    }

    return;

param_error_exit:

    rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

}


void qmp_migrate_set_cache_size(int64_t value, Error **errp)

{

    MigrationState *s = migrate_get_current();

    /* Check for truncation */

    if (value != (size_t)value) {

        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",

                  "exceeding address space");

        return;

    }

    s->xbzrle_cache_size = xbzrle_cache_resize(value);

}


int path_is_absolute(const char *path)

{

    const char *p;

#ifdef _WIN32

    /* specific case for names like: "\\.\d:" */

    if (*path == '/' || *path == '\\')

        return 1;

#endif

    p = strchr(path, ':');

    if (p)

        p++;

    else

        p = path;

#ifdef _WIN32

    return (*p == '/' || *p == '\\');

#else

    return (*p == '/');

#endif

}


opts_end_struct(Visitor *v, Error **errp)

{

    OptsVisitor *ov = to_ov(v);

    GHashTableIter iter;

    GQueue *any;

    if (--ov->depth > 0) {

        return;

    }

    /* we should have processed all (distinct) QemuOpt instances */

    g_hash_table_iter_init(&iter, ov->unprocessed_opts);

    if (g_hash_table_iter_next(&iter, NULL, (void **)&any)) {

        const QemuOpt *first;

        first = g_queue_peek_head(any);

        error_setg(errp, QERR_INVALID_PARAMETER, first->name);

    }

    g_hash_table_destroy(ov->unprocessed_opts);

    ov->unprocessed_opts = NULL;

    if (ov->fake_id_opt) {

        g_free(ov->fake_id_opt->name);

        g_free(ov->fake_id_opt->str);

        g_free(ov->fake_id_opt);

    }

    ov->fake_id_opt = NULL;

}


static av_cold int shorten_decode_close(AVCodecContext *avctx)

{

    ShortenContext *s = avctx->priv_data;

    int i;

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

        s->decoded[i] -= s->nwrap;

        av_freep(&s->decoded[i]);

        av_freep(&s->offset[i]);

    }

    av_freep(&s->bitstream);

    av_freep(&s->coeffs);

    return 0;

}


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

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_and_aver_dst_4x4_msa(src + stride - 2,

                                         src - (stride * 2),

                                         stride, dst, stride);

}


static uint32_t apic_mem_readl(void *opaque, target_phys_addr_t addr)

{

    DeviceState *d;

    APICCommonState *s;

    uint32_t val;

    int index;

    d = cpu_get_current_apic();

    if (!d) {

        return 0;

    }

    s = DO_UPCAST(APICCommonState, busdev.qdev, d);

    index = (addr >> 4) & 0xff;

    switch(index) {

    case 0x02: /* id */

        val = s->id << 24;

        break;

    case 0x03: /* version */

        val = 0x11 | ((APIC_LVT_NB - 1) << 16); /* version 0x11 */

        break;

    case 0x08:

        apic_sync_vapic(s, SYNC_FROM_VAPIC);

        if (apic_report_tpr_access) {

            cpu_report_tpr_access(s->cpu_env, TPR_ACCESS_READ);

        }

        val = s->tpr;

        break;

    case 0x09:

        val = apic_get_arb_pri(s);

        break;

    case 0x0a:

        /* ppr */

        val = apic_get_ppr(s);

        break;

    case 0x0b:

        val = 0;

        break;

    case 0x0d:

        val = s->log_dest << 24;

        break;

    case 0x0e:

        val = s->dest_mode << 28;

        break;

    case 0x0f:

        val = s->spurious_vec;

        break;

    case 0x10 ... 0x17:

        val = s->isr[index & 7];

        break;

    case 0x18 ... 0x1f:

        val = s->tmr[index & 7];

        break;

    case 0x20 ... 0x27:

        val = s->irr[index & 7];

        break;

    case 0x28:

        val = s->esr;

        break;

    case 0x30:

    case 0x31:

        val = s->icr[index & 1];

        break;

    case 0x32 ... 0x37:

        val = s->lvt[index - 0x32];

        break;

    case 0x38:

        val = s->initial_count;

        break;

    case 0x39:

        val = apic_get_current_count(s);

        break;

    case 0x3e:

        val = s->divide_conf;

        break;

    default:

        s->esr |= ESR_ILLEGAL_ADDRESS;

        val = 0;

        break;

    }

    trace_apic_mem_readl(addr, val);

    return val;

}


static SocketAddressLegacy *tcp_build_address(const char *host_port, Error **errp)

{

    InetSocketAddress *iaddr = g_new(InetSocketAddress, 1);

    SocketAddressLegacy *saddr;

    if (inet_parse(iaddr, host_port, errp)) {

        qapi_free_InetSocketAddress(iaddr);

        return NULL;

    }

    saddr = g_new0(SocketAddressLegacy, 1);

    saddr->type = SOCKET_ADDRESS_LEGACY_KIND_INET;

    saddr->u.inet.data = iaddr;

    return saddr;

}


static void render_line(int x0, uint8_t y0, int x1, int y1, float *buf)

{

    int dy  = y1 - y0;

    int adx = x1 - x0;

    int ady = FFABS(dy);

    int sy  = dy < 0 ? -1 : 1;

    buf[x0] = ff_vorbis_floor1_inverse_db_table[y0];

    if (ady*2 <= adx) { // optimized common case

        render_line_unrolled(x0, y0, x1, sy, ady, adx, buf);

    } else {

        int base  = dy / adx;

        int x     = x0;

        uint8_t y = y0;

        int err   = -adx;

        ady -= FFABS(base) * adx;

        while (++x < x1) {

            y += base;

            err += ady;

            if (err >= 0) {

                err -= adx;

                y   += sy;

            }

            buf[x] = ff_vorbis_floor1_inverse_db_table[y];

        }

    }

}


static const QObject *qmp_input_get_object(QmpInputVisitor *qiv,

                                           const char *name)

{

    const QObject *qobj;

    if (qiv->nb_stack == 0) {

        qobj = qiv->obj;

    } else {

        qobj = qiv->stack[qiv->nb_stack - 1].obj;

    }

    if (name && qobject_type(qobj) == QTYPE_QDICT) {

        return qdict_get(qobject_to_qdict(qobj), name);

    } else if (qiv->nb_stack > 0 && qobject_type(qobj) == QTYPE_QLIST) {

        return qlist_entry_obj(qiv->stack[qiv->nb_stack - 1].entry);

    }

    return qobj;

}


static BufferPoolEntry *get_pool(AVBufferPool *pool)

{

    BufferPoolEntry *cur = NULL, *last = NULL;

    do {

        FFSWAP(BufferPoolEntry*, cur, last);

        cur = avpriv_atomic_ptr_cas((void * volatile *)&pool->pool, last, NULL);

        if (!cur)

            return NULL;

    } while (cur != last);

    return cur;

}


static void switch_buffer(MPADecodeContext *s, int *pos, int *end_pos,

                          int *end_pos2)

{

    if (s->in_gb.buffer && *pos >= s->gb.size_in_bits) {

        s->gb           = s->in_gb;

        s->in_gb.buffer = NULL;

        assert((get_bits_count(&s->gb) & 7) == 0);

        skip_bits_long(&s->gb, *pos - *end_pos);

        *end_pos2 =

        *end_pos  = *end_pos2 + get_bits_count(&s->gb) - *pos;

        *pos      = get_bits_count(&s->gb);

    }

}


static int vpc_write(BlockDriverState *bs, int64_t sector_num,

    const uint8_t *buf, int nb_sectors)

{

    BDRVVPCState *s = bs->opaque;

    int64_t offset;

    int64_t sectors, sectors_per_block;

    int ret;

    VHDFooter *footer =  (VHDFooter *) s->footer_buf;

    if (cpu_to_be32(footer->type) == VHD_FIXED) {

        return bdrv_write(bs->file, sector_num, buf, nb_sectors);

    }

    while (nb_sectors > 0) {

        offset = get_sector_offset(bs, sector_num, 1);

        sectors_per_block = s->block_size >> BDRV_SECTOR_BITS;

        sectors = sectors_per_block - (sector_num % sectors_per_block);

        if (sectors > nb_sectors) {

            sectors = nb_sectors;

        }

        if (offset == -1) {

            offset = alloc_block(bs, sector_num);

            if (offset < 0)

                return -1;

        }

        ret = bdrv_pwrite(bs->file, offset, buf, sectors * BDRV_SECTOR_SIZE);

        if (ret != sectors * BDRV_SECTOR_SIZE) {

            return -1;

        }

        nb_sectors -= sectors;

        sector_num += sectors;

        buf += sectors * BDRV_SECTOR_SIZE;

    }

    return 0;

}


static int read_old_huffman_tables(HYuvContext *s){

#if 1

    GetBitContext gb;

    int i;

    init_get_bits(&gb, classic_shift_luma, sizeof(classic_shift_luma)*8);

    if(read_len_table(s->len[0], &gb)<0)

        return -1;

    init_get_bits(&gb, classic_shift_chroma, sizeof(classic_shift_chroma)*8);

    if(read_len_table(s->len[1], &gb)<0)

        return -1;

    for(i=0; i<256; i++) s->bits[0][i] = classic_add_luma  [i];

    for(i=0; i<256; i++) s->bits[1][i] = classic_add_chroma[i];

    if(s->bitstream_bpp >= 24){

        memcpy(s->bits[1], s->bits[0], 256*sizeof(uint32_t));

        memcpy(s->len[1] , s->len [0], 256*sizeof(uint8_t));

    }

    memcpy(s->bits[2], s->bits[1], 256*sizeof(uint32_t));

    memcpy(s->len[2] , s->len [1], 256*sizeof(uint8_t));

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

        ff_free_vlc(&s->vlc[i]);

        init_vlc(&s->vlc[i], VLC_BITS, 256, s->len[i], 1, 1, s->bits[i], 4, 4, 0);

    }

    generate_joint_tables(s);

    return 0;

#else

    av_log(s->avctx, AV_LOG_DEBUG, "v1 huffyuv is not supported \n");

    return -1;

#endif

}


exynos4_boards_init_common(MachineState *machine,

                           Exynos4BoardType board_type)

{

    Exynos4BoardState *s = g_new(Exynos4BoardState, 1);

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    if (smp_cpus != EXYNOS4210_NCPUS && !qtest_enabled()) {

        error_report("%s board supports only %d CPU cores, ignoring smp_cpus"

                     " value",

                     mc->name, EXYNOS4210_NCPUS);

    }

    exynos4_board_binfo.ram_size = exynos4_board_ram_size[board_type];

    exynos4_board_binfo.board_id = exynos4_board_id[board_type];

    exynos4_board_binfo.smp_bootreg_addr =

            exynos4_board_smp_bootreg_addr[board_type];

    exynos4_board_binfo.kernel_filename = machine->kernel_filename;

    exynos4_board_binfo.initrd_filename = machine->initrd_filename;

    exynos4_board_binfo.kernel_cmdline = machine->kernel_cmdline;

    exynos4_board_binfo.gic_cpu_if_addr =

            EXYNOS4210_SMP_PRIVATE_BASE_ADDR + 0x100;

    PRINT_DEBUG("\n ram_size: %luMiB [0x%08lx]\n"

            " kernel_filename: %s\n"

            " kernel_cmdline: %s\n"

            " initrd_filename: %s\n",

            exynos4_board_ram_size[board_type] / 1048576,

            exynos4_board_ram_size[board_type],

            machine->kernel_filename,

            machine->kernel_cmdline,

            machine->initrd_filename);

    exynos4_boards_init_ram(s, get_system_memory(),

                            exynos4_board_ram_size[board_type]);

    s->soc = exynos4210_init(get_system_memory());

    return s;

}


static void json_print_section_header(WriterContext *wctx)

{

    JSONContext *json = wctx->priv;

    AVBPrint buf;

    const struct section *section = wctx->section[wctx->level];

    const struct section *parent_section = wctx->level ?

        wctx->section[wctx->level-1] : NULL;

    if (wctx->level && wctx->nb_item[wctx->level-1])

        printf(",\n");

    if (section->flags & SECTION_FLAG_IS_WRAPPER) {

        printf("{\n");

        json->indent_level++;

    } else {

        av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);

        json_escape_str(&buf, section->name, wctx);

        JSON_INDENT();

        json->indent_level++;

        if (section->flags & SECTION_FLAG_IS_ARRAY) {

            printf("\"%s\": [\n", buf.str);

        } else if (!(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {

            printf("\"%s\": {%s", buf.str, json->item_start_end);

        } else {

            printf("{%s", json->item_start_end);

            /* this is required so the parser can distinguish between packets and frames */

            if (parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {

                if (!json->compact)

                    JSON_INDENT();

                printf("\"type\": \"%s\"%s", section->name, json->item_sep);

            }

        }

        av_bprint_finalize(&buf, NULL);

    }

}


build_madt(GArray *table_data, BIOSLinker *linker, VirtGuestInfo *guest_info)

{

    int madt_start = table_data->len;

    const MemMapEntry *memmap = guest_info->memmap;

    const int *irqmap = guest_info->irqmap;

    AcpiMultipleApicTable *madt;

    AcpiMadtGenericDistributor *gicd;

    AcpiMadtGenericMsiFrame *gic_msi;

    int i;

    madt = acpi_data_push(table_data, sizeof *madt);

    gicd = acpi_data_push(table_data, sizeof *gicd);

    gicd->type = ACPI_APIC_GENERIC_DISTRIBUTOR;

    gicd->length = sizeof(*gicd);

    gicd->base_address = memmap[VIRT_GIC_DIST].base;

    gicd->version = guest_info->gic_version;

    for (i = 0; i < guest_info->smp_cpus; i++) {

        AcpiMadtGenericInterrupt *gicc = acpi_data_push(table_data,

                                                     sizeof *gicc);

        ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(i));

        gicc->type = ACPI_APIC_GENERIC_INTERRUPT;

        gicc->length = sizeof(*gicc);

        if (guest_info->gic_version == 2) {

            gicc->base_address = memmap[VIRT_GIC_CPU].base;

        }

        gicc->cpu_interface_number = i;

        gicc->arm_mpidr = armcpu->mp_affinity;

        gicc->uid = i;

        gicc->flags = cpu_to_le32(ACPI_GICC_ENABLED);

        if (armcpu->has_pmu) {

            gicc->performance_interrupt = cpu_to_le32(PPI(VIRTUAL_PMU_IRQ));

        }

    }

    if (guest_info->gic_version == 3) {

        AcpiMadtGenericTranslator *gic_its;

        AcpiMadtGenericRedistributor *gicr = acpi_data_push(table_data,

                                                         sizeof *gicr);

        gicr->type = ACPI_APIC_GENERIC_REDISTRIBUTOR;

        gicr->length = sizeof(*gicr);

        gicr->base_address = cpu_to_le64(memmap[VIRT_GIC_REDIST].base);

        gicr->range_length = cpu_to_le32(memmap[VIRT_GIC_REDIST].size);

        if (its_class_name()) {

            gic_its = acpi_data_push(table_data, sizeof *gic_its);

            gic_its->type = ACPI_APIC_GENERIC_TRANSLATOR;

            gic_its->length = sizeof(*gic_its);

            gic_its->translation_id = 0;

            gic_its->base_address = cpu_to_le64(memmap[VIRT_GIC_ITS].base);

        }

    } else {

        gic_msi = acpi_data_push(table_data, sizeof *gic_msi);

        gic_msi->type = ACPI_APIC_GENERIC_MSI_FRAME;

        gic_msi->length = sizeof(*gic_msi);

        gic_msi->gic_msi_frame_id = 0;

        gic_msi->base_address = cpu_to_le64(memmap[VIRT_GIC_V2M].base);

        gic_msi->flags = cpu_to_le32(1);

        gic_msi->spi_count = cpu_to_le16(NUM_GICV2M_SPIS);

        gic_msi->spi_base = cpu_to_le16(irqmap[VIRT_GIC_V2M] + ARM_SPI_BASE);

    }

    build_header(linker, table_data,

                 (void *)(table_data->data + madt_start), "APIC",

                 table_data->len - madt_start, 3, NULL, NULL);

}


int slirp_can_output(void)

{

    return !slirp_vc || qemu_can_send_packet(slirp_vc);

}


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

{

    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);

    uc->init           = usb_tablet_initfn;

    uc->product_desc   = "QEMU USB Tablet";

    uc->usb_desc       = &desc_tablet;

    uc->handle_packet  = usb_generic_handle_packet;

    uc->handle_reset   = usb_hid_handle_reset;

    uc->handle_control = usb_hid_handle_control;

    uc->handle_data    = usb_hid_handle_data;

    uc->handle_destroy = usb_hid_handle_destroy;

}