static void avc_loopfilter_luma_intra_edge_ver_msa(uint8_t *data,

                                                   uint8_t alpha_in,

                                                   uint8_t beta_in,

                                                   uint32_t img_width)

{

    uint8_t *src;

    v16u8 alpha, beta, p0_asub_q0;

    v16u8 is_less_than_alpha, is_less_than;

    v16u8 is_less_than_beta, negate_is_less_than_beta;

    v8i16 p2_r = { 0 };

    v8i16 p1_r = { 0 };

    v8i16 p0_r = { 0 };

    v8i16 q0_r = { 0 };

    v8i16 q1_r = { 0 };

    v8i16 q2_r = { 0 };

    v8i16 p2_l = { 0 };

    v8i16 p1_l = { 0 };

    v8i16 p0_l = { 0 };

    v8i16 q0_l = { 0 };

    v8i16 q1_l = { 0 };

    v8i16 q2_l = { 0 };

    v16u8 p3_org, p2_org, p1_org, p0_org, q0_org, q1_org, q2_org, q3_org;

    v8i16 p1_org_r, p0_org_r, q0_org_r, q1_org_r;

    v8i16 p1_org_l, p0_org_l, q0_org_l, q1_org_l;

    v16i8 zero = { 0 };

    v16u8 tmp_flag;

    src = data - 4;

    {

        v16u8 row0, row1, row2, row3, row4, row5, row6, row7;

        v16u8 row8, row9, row10, row11, row12, row13, row14, row15;

        LOAD_8VECS_UB(src, img_width,

                      row0, row1, row2, row3, row4, row5, row6, row7);

        LOAD_8VECS_UB(src + (8 * img_width), img_width,

                      row8, row9, row10, row11, row12, row13, row14, row15);

        TRANSPOSE16x8_B_UB(row0, row1, row2, row3, row4, row5, row6, row7,

                           row8, row9, row10, row11, row12, row13, row14, row15,

                           p3_org, p2_org, p1_org, p0_org,

                           q0_org, q1_org, q2_org, q3_org);

    }

    p1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p1_org);

    p0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p0_org);

    q0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q0_org);

    q1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q1_org);

    p1_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p1_org);

    p0_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p0_org);

    q0_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q0_org);

    q1_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q1_org);

    /*  if ( ((unsigned)ABS(p0-q0) < thresholds->alpha_in) &&

       ((unsigned)ABS(p1-p0) < thresholds->beta_in)  &&

       ((unsigned)ABS(q1-q0) < thresholds->beta_in) )   */

    {

        v16u8 p1_asub_p0, q1_asub_q0;

        p0_asub_q0 = __msa_asub_u_b(p0_org, q0_org);

        p1_asub_p0 = __msa_asub_u_b(p1_org, p0_org);

        q1_asub_q0 = __msa_asub_u_b(q1_org, q0_org);

        alpha = (v16u8) __msa_fill_b(alpha_in);

        beta = (v16u8) __msa_fill_b(beta_in);

        is_less_than_alpha = (p0_asub_q0 < alpha);

        is_less_than_beta = (p1_asub_p0 < beta);

        is_less_than = is_less_than_beta & is_less_than_alpha;

        is_less_than_beta = (q1_asub_q0 < beta);

        is_less_than = is_less_than_beta & is_less_than;

    }

    if (!__msa_test_bz_v(is_less_than)) {

        tmp_flag = alpha >> 2;

        tmp_flag = tmp_flag + 2;

        tmp_flag = (p0_asub_q0 < tmp_flag);

        {

            v16u8 p2_asub_p0;

            p2_asub_p0 = __msa_asub_u_b(p2_org, p0_org);

            is_less_than_beta = (p2_asub_p0 < beta);

        }

        is_less_than_beta = tmp_flag & is_less_than_beta;

        negate_is_less_than_beta = __msa_xori_b(is_less_than_beta, 0xff);

        is_less_than_beta = is_less_than_beta & is_less_than;

        negate_is_less_than_beta = negate_is_less_than_beta & is_less_than;

        /* right */

        {

            v16u8 is_less_than_beta_r;

            is_less_than_beta_r =

                (v16u8) __msa_sldi_b((v16i8) is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v(is_less_than_beta_r)) {

                v8i16 p3_org_r;

                p3_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p3_org);

                p2_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(p3_org_r, p0_org_r,

                                                 q0_org_r, p1_org_r,

                                                 p2_r, q1_org_r,

                                                 p0_r, p1_r, p2_r);

            }

        }

        /* left */

        {

            v16u8 is_less_than_beta_l;

            is_less_than_beta_l =

                (v16u8) __msa_sldi_b(zero, (v16i8) is_less_than_beta, 8);

            if (!__msa_test_bz_v(is_less_than_beta_l)) {

                v8i16 p3_org_l;

                p3_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p3_org);

                p2_l = (v8i16) __msa_ilvl_b(zero, (v16i8) p2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(p3_org_l, p0_org_l,

                                                 q0_org_l, p1_org_l,

                                                 p2_l, q1_org_l,

                                                 p0_l, p1_l, p2_l);

            }

        }

        /* combine and store */

        if (!__msa_test_bz_v(is_less_than_beta)) {

            v16u8 p0, p2, p1;

            p0 = (v16u8) __msa_pckev_b((v16i8) p0_l, (v16i8) p0_r);

            p1 = (v16u8) __msa_pckev_b((v16i8) p1_l, (v16i8) p1_r);

            p2 = (v16u8) __msa_pckev_b((v16i8) p2_l, (v16i8) p2_r);

            p0_org = __msa_bmnz_v(p0_org, p0, is_less_than_beta);

            p1_org = __msa_bmnz_v(p1_org, p1, is_less_than_beta);

            p2_org = __msa_bmnz_v(p2_org, p2, is_less_than_beta);

        }

        /* right */

        {

            v16u8 negate_is_less_than_beta_r;

            negate_is_less_than_beta_r =

                (v16u8) __msa_sldi_b((v16i8) negate_is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v(negate_is_less_than_beta_r)) {

                AVC_LOOP_FILTER_P0_OR_Q0(p0_org_r, q1_org_r, p1_org_r, p0_r);

            }

        }

        /* left */

        {

            v16u8 negate_is_less_than_beta_l;

            negate_is_less_than_beta_l =

                (v16u8) __msa_sldi_b(zero, (v16i8) negate_is_less_than_beta, 8);

            if (!__msa_test_bz_v(negate_is_less_than_beta_l)) {

                AVC_LOOP_FILTER_P0_OR_Q0(p0_org_l, q1_org_l, p1_org_l, p0_l);

            }

        }

        if (!__msa_test_bz_v(negate_is_less_than_beta)) {

            v16u8 p0;

            p0 = (v16u8) __msa_pckev_b((v16i8) p0_l, (v16i8) p0_r);

            p0_org = __msa_bmnz_v(p0_org, p0, negate_is_less_than_beta);

        }

        {

            v16u8 q2_asub_q0;

            q2_asub_q0 = __msa_asub_u_b(q2_org, q0_org);

            is_less_than_beta = (q2_asub_q0 < beta);

        }

        is_less_than_beta = is_less_than_beta & tmp_flag;

        negate_is_less_than_beta = __msa_xori_b(is_less_than_beta, 0xff);

        is_less_than_beta = is_less_than_beta & is_less_than;

        negate_is_less_than_beta = negate_is_less_than_beta & is_less_than;

        /* right */

        {

            v16u8 is_less_than_beta_r;

            is_less_than_beta_r =

                (v16u8) __msa_sldi_b((v16i8) is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v(is_less_than_beta_r)) {

                v8i16 q3_org_r;

                q3_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q3_org);

                q2_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(q3_org_r, q0_org_r,

                                                 p0_org_r, q1_org_r,

                                                 q2_r, p1_org_r,

                                                 q0_r, q1_r, q2_r);

            }

        }

        /* left */

        {

            v16u8 is_less_than_beta_l;

            is_less_than_beta_l =

                (v16u8) __msa_sldi_b(zero, (v16i8) is_less_than_beta, 8);

            if (!__msa_test_bz_v(is_less_than_beta_l)) {

                v8i16 q3_org_l;

                q3_org_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q3_org);

                q2_l = (v8i16) __msa_ilvl_b(zero, (v16i8) q2_org);

                AVC_LOOP_FILTER_P0P1P2_OR_Q0Q1Q2(q3_org_l, q0_org_l,

                                                 p0_org_l, q1_org_l,

                                                 q2_l, p1_org_l,

                                                 q0_l, q1_l, q2_l);

            }

        }

        /* combine and store */

        if (!__msa_test_bz_v(is_less_than_beta)) {

            v16u8 q0, q1, q2;

            q0 = (v16u8) __msa_pckev_b((v16i8) q0_l, (v16i8) q0_r);

            q1 = (v16u8) __msa_pckev_b((v16i8) q1_l, (v16i8) q1_r);

            q2 = (v16u8) __msa_pckev_b((v16i8) q2_l, (v16i8) q2_r);

            q0_org = __msa_bmnz_v(q0_org, q0, is_less_than_beta);

            q1_org = __msa_bmnz_v(q1_org, q1, is_less_than_beta);

            q2_org = __msa_bmnz_v(q2_org, q2, is_less_than_beta);

        }

        /* right */

        {

            v16u8 negate_is_less_than_beta_r;

            negate_is_less_than_beta_r =

                (v16u8) __msa_sldi_b((v16i8) negate_is_less_than_beta, zero, 8);

            if (!__msa_test_bz_v(negate_is_less_than_beta_r)) {

                AVC_LOOP_FILTER_P0_OR_Q0(q0_org_r, p1_org_r, q1_org_r, q0_r);

            }

        }

        /* left */

        {

            v16u8 negate_is_less_than_beta_l;

            negate_is_less_than_beta_l =

                (v16u8) __msa_sldi_b(zero, (v16i8) negate_is_less_than_beta, 8);

            if (!__msa_test_bz_v(negate_is_less_than_beta_l)) {

                AVC_LOOP_FILTER_P0_OR_Q0(q0_org_l, p1_org_l, q1_org_l, q0_l);

            }

        }

        if (!__msa_test_bz_v(negate_is_less_than_beta)) {

            v16u8 q0;

            q0 = (v16u8) __msa_pckev_b((v16i8) q0_l, (v16i8) q0_r);

            q0_org = __msa_bmnz_v(q0_org, q0, negate_is_less_than_beta);

        }

    }

    {

        v16u8 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;

        uint32_t out0, out2;

        uint16_t out1, out3;

        tmp0 = (v16u8) __msa_ilvr_b((v16i8) p1_org, (v16i8) p2_org);

        tmp1 = (v16u8) __msa_ilvr_b((v16i8) q0_org, (v16i8) p0_org);

        tmp2 = (v16u8) __msa_ilvr_b((v16i8) q2_org, (v16i8) q1_org);

        tmp3 = (v16u8) __msa_ilvr_h((v8i16) tmp1, (v8i16) tmp0);

        tmp4 = (v16u8) __msa_ilvl_h((v8i16) tmp1, (v8i16) tmp0);

        tmp0 = (v16u8) __msa_ilvl_b((v16i8) p1_org, (v16i8) p2_org);

        tmp1 = (v16u8) __msa_ilvl_b((v16i8) q0_org, (v16i8) p0_org);

        tmp5 = (v16u8) __msa_ilvl_b((v16i8) q2_org, (v16i8) q1_org);

        tmp6 = (v16u8) __msa_ilvr_h((v8i16) tmp1, (v8i16) tmp0);

        tmp7 = (v16u8) __msa_ilvl_h((v8i16) tmp1, (v8i16) tmp0);

        src = data - 3;

        out0 = __msa_copy_u_w((v4i32) tmp3, 0);

        out1 = __msa_copy_u_h((v8i16) tmp2, 0);

        out2 = __msa_copy_u_w((v4i32) tmp3, 1);

        out3 = __msa_copy_u_h((v8i16) tmp2, 1);

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

        out0 = __msa_copy_u_w((v4i32) tmp3, 2);

        out1 = __msa_copy_u_h((v8i16) tmp2, 2);

        out2 = __msa_copy_u_w((v4i32) tmp3, 3);

        out3 = __msa_copy_u_h((v8i16) tmp2, 3);

        src += img_width;

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

        out0 = __msa_copy_u_w((v4i32) tmp4, 0);

        out1 = __msa_copy_u_h((v8i16) tmp2, 4);

        out2 = __msa_copy_u_w((v4i32) tmp4, 1);

        out3 = __msa_copy_u_h((v8i16) tmp2, 5);

        src += img_width;

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

        out0 = __msa_copy_u_w((v4i32) tmp4, 2);

        out1 = __msa_copy_u_h((v8i16) tmp2, 6);

        out2 = __msa_copy_u_w((v4i32) tmp4, 3);

        out3 = __msa_copy_u_h((v8i16) tmp2, 7);

        src += img_width;

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

        out0 = __msa_copy_u_w((v4i32) tmp6, 0);

        out1 = __msa_copy_u_h((v8i16) tmp5, 0);

        out2 = __msa_copy_u_w((v4i32) tmp6, 1);

        out3 = __msa_copy_u_h((v8i16) tmp5, 1);

        src += img_width;

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

        out0 = __msa_copy_u_w((v4i32) tmp6, 2);

        out1 = __msa_copy_u_h((v8i16) tmp5, 2);

        out2 = __msa_copy_u_w((v4i32) tmp6, 3);

        out3 = __msa_copy_u_h((v8i16) tmp5, 3);

        src += img_width;

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

        out0 = __msa_copy_u_w((v4i32) tmp7, 0);

        out1 = __msa_copy_u_h((v8i16) tmp5, 4);

        out2 = __msa_copy_u_w((v4i32) tmp7, 1);

        out3 = __msa_copy_u_h((v8i16) tmp5, 5);

        src += img_width;

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

        out0 = __msa_copy_u_w((v4i32) tmp7, 2);

        out1 = __msa_copy_u_h((v8i16) tmp5, 6);

        out2 = __msa_copy_u_w((v4i32) tmp7, 3);

        out3 = __msa_copy_u_h((v8i16) tmp5, 7);

        src += img_width;

        STORE_WORD(src, out0);

        STORE_HWORD((src + 4), out1);

        src += img_width;

        STORE_WORD(src, out2);

        STORE_HWORD((src + 4), out3);

    }

}


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

{

    struct dshow_ctx *ctx = s->priv_data;

    AVPacketList *pktl = NULL;

    while (!pktl) {

        WaitForSingleObject(ctx->mutex, INFINITE);

        pktl = ctx->pktl;

        if (pktl) {

            *pkt = pktl->pkt;

            ctx->pktl = ctx->pktl->next;

            av_free(pktl);

            ctx->curbufsize -= pkt->size;

        }

        ResetEvent(ctx->event);

        ReleaseMutex(ctx->mutex);

        if (!pktl) {

            if (s->flags & AVFMT_FLAG_NONBLOCK) {

                return AVERROR(EAGAIN);

            } else {

                WaitForSingleObject(ctx->event, INFINITE);

            }

        }

    }

    return pkt->size;

}


static void blend_image(AVFilterContext *ctx,

                        AVFilterBufferRef *dst, AVFilterBufferRef *src,

                        int x, int y)

{

    OverlayContext *over = ctx->priv;

    int i, j, k;

    int width   = src->video->w;

    int height  = src->video->h;

    if (over->main_is_packed_rgb) {

        uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +

                      y * dst->linesize[0];

        uint8_t *sp = src->data[0];

        uint8_t alpha;          ///< the amount of overlay to blend on to main

        const int dr = over->main_rgba_map[R];

        const int dg = over->main_rgba_map[G];

        const int db = over->main_rgba_map[B];

        const int da = over->main_rgba_map[A];

        const int dstep = over->main_pix_step[0];

        const int sr = over->overlay_rgba_map[R];

        const int sg = over->overlay_rgba_map[G];

        const int sb = over->overlay_rgba_map[B];

        const int sa = over->overlay_rgba_map[A];

        const int sstep = over->overlay_pix_step[0];

        const int main_has_alpha = over->main_has_alpha;

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

            uint8_t *d = dp, *s = sp;

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

                alpha = s[sa];

                // if the main channel has an alpha channel, alpha has to be calculated

                // to create an un-premultiplied (straight) alpha value

                if (main_has_alpha && alpha != 0 && alpha != 255) {

                    uint8_t alpha_d = d[da];

                    alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);

                }

                switch (alpha) {

                case 0:

                    break;

                case 255:

                    d[dr] = s[sr];

                    d[dg] = s[sg];

                    d[db] = s[sb];

                    break;

                default:

                    // main_value = main_value * (1 - alpha) + overlay_value * alpha

                    // since alpha is in the range 0-255, the result must divided by 255

                    d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);

                    d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);

                    d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);

                }

                if (main_has_alpha) {

                    switch (alpha) {

                    case 0:

                        break;

                    case 255:

                        d[da] = s[sa];

                        break;

                    default:

                        // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha

                        d[da] += FAST_DIV255((255 - d[da]) * s[sa]);

                    }

                }

                d += dstep;

                s += sstep;

            }

            dp += dst->linesize[0];

            sp += src->linesize[0];

        }

    } else {

        const int main_has_alpha = over->main_has_alpha;

        if (main_has_alpha) {

            uint8_t *da = dst->data[3] + x * over->main_pix_step[3] +

                          y * dst->linesize[3];

            uint8_t *sa = src->data[3];

            uint8_t alpha;          ///< the amount of overlay to blend on to main

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

                uint8_t *d = da, *s = sa;

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

                    alpha = *s;

                    if (alpha != 0 && alpha != 255) {

                        uint8_t alpha_d = *d;

                        alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);

                    }

                    switch (alpha) {

                    case 0:

                        break;

                    case 255:

                        *d = *s;

                        break;

                    default:

                        // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha

                        *d += FAST_DIV255((255 - *d) * *s);

                    }

                    d += 1;

                    s += 1;

                }

                da += dst->linesize[3];

                sa += src->linesize[3];

            }

        }

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

            int hsub = i ? over->hsub : 0;

            int vsub = i ? over->vsub : 0;

            uint8_t *dp = dst->data[i] + (x >> hsub) +

                (y >> vsub) * dst->linesize[i];

            uint8_t *sp = src->data[i];

            uint8_t *ap = src->data[3];

            int wp = FFALIGN(width, 1<<hsub) >> hsub;

            int hp = FFALIGN(height, 1<<vsub) >> vsub;

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

                uint8_t *d = dp, *s = sp, *a = ap;

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

                    // average alpha for color components, improve quality

                    int alpha_v, alpha_h, alpha;

                    if (hsub && vsub && j+1 < hp && k+1 < wp) {

                        alpha = (a[0] + a[src->linesize[3]] +

                                 a[1] + a[src->linesize[3]+1]) >> 2;

                    } else if (hsub || vsub) {

                        alpha_h = hsub && k+1 < wp ?

                            (a[0] + a[1]) >> 1 : a[0];

                        alpha_v = vsub && j+1 < hp ?

                            (a[0] + a[src->linesize[3]]) >> 1 : a[0];

                        alpha = (alpha_v + alpha_h) >> 1;

                    } else

                        alpha = a[0];

                    // if the main channel has an alpha channel, alpha has to be calculated

                    // to create an un-premultiplied (straight) alpha value

                    if (main_has_alpha && alpha != 0 && alpha != 255) {

                        // average alpha for color components, improve quality

                        uint8_t alpha_d;

                        if (hsub && vsub && j+1 < hp && k+1 < wp) {

                            alpha_d = (d[0] + d[src->linesize[3]] +

                                       d[1] + d[src->linesize[3]+1]) >> 2;

                        } else if (hsub || vsub) {

                            alpha_h = hsub && k+1 < wp ?

                                (d[0] + d[1]) >> 1 : d[0];

                            alpha_v = vsub && j+1 < hp ?

                                (d[0] + d[src->linesize[3]]) >> 1 : d[0];

                            alpha_d = (alpha_v + alpha_h) >> 1;

                        } else

                            alpha_d = d[0];

                        alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);

                    }

                    *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);

                    s++;

                    d++;

                    a += 1 << hsub;

                }

                dp += dst->linesize[i];

                sp += src->linesize[i];

                ap += (1 << vsub) * src->linesize[3];

            }

        }

    }

}


static void draw_mandelbrot(AVFilterContext *ctx, uint32_t *color, int linesize, int64_t pts)

{

    MBContext *mb = ctx->priv;

    int x,y,i, in_cidx=0, next_cidx=0, tmp_cidx;

    double scale= mb->start_scale*pow(mb->end_scale/mb->start_scale, pts/mb->end_pts);

    int use_zyklus=0;

    fill_from_cache(ctx, NULL, &in_cidx, NULL, mb->start_y+scale*(-mb->h/2-0.5), scale);

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

        const double ci=mb->start_y+scale*(y-mb->h/2);

        memset(color+linesize*y, 0, sizeof(*color)*mb->w);

        fill_from_cache(ctx, color+linesize*y, &in_cidx, &next_cidx, ci, scale);

        tmp_cidx= in_cidx;

        fill_from_cache(ctx, color+linesize*y, &tmp_cidx, NULL, ci + scale/2, scale);

        for(x=0; x<mb->w; x++){

            const double cr=mb->start_x+scale*(x-mb->w/2);

            double zr=cr;

            double zi=ci;

            uint32_t c=0;

            double dv= mb->dither / (double)(1LL<<32);

            mb->dither= mb->dither*1664525+1013904223;

            if(color[x + y*linesize] & 0xFF000000)

                continue;

            use_zyklus= (x==0 || mb->inner!=BLACK ||color[x-1 + y*linesize] == 0xFF000000);

#define Z_Z2_C(outr,outi,inr,ini)\

            outr= inr*inr - ini*ini + cr;\

            outi= 2*inr*ini + ci;

#define Z_Z2_C_ZYKLUS(outr,outi,inr,ini, Z)\

            Z_Z2_C(outr,outi,inr,ini)\

            if(use_zyklus){\

                if(Z && mb->zyklus[i>>1][0]==outr && mb->zyklus[i>>1][1]==outi)\

                    break;\

                mb->zyklus[i][0]= outr;\

                mb->zyklus[i][1]= outi;\

            }

            for(i=0; i<mb->maxiter-8; i++){

                double t;

                Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)

                i++;

                Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)

                i++;

                Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)

                i++;

                Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)

                i++;

                Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)

                i++;

                Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)

                i++;

                Z_Z2_C_ZYKLUS(t, zi, zr, zi, 0)

                i++;

                Z_Z2_C_ZYKLUS(zr, zi, t, zi, 1)

                if(zr*zr + zi*zi > mb->bailout){

                    i-= FFMIN(7, i);

                    for(; i<mb->maxiter; i++){

                        zr= mb->zyklus[i][0];

                        zi= mb->zyklus[i][1];

                        if(zr*zr + zi*zi > mb->bailout){

                            switch(mb->outer){

                            case            ITERATION_COUNT: zr = i; break;

                            case NORMALIZED_ITERATION_COUNT: zr= i + log2(log(mb->bailout) / log(zr*zr + zi*zi)); break;

                            }

                            c= lrintf((sin(zr)+1)*127) + lrintf((sin(zr/1.234)+1)*127)*256*256 + lrintf((sin(zr/100)+1)*127)*256;

                            break;

                        }

                    }

                    break;

                }

            }

            if(!c){

                if(mb->inner==PERIOD){

                int j;

                for(j=i-1; j; j--)

                    if(SQR(mb->zyklus[j][0]-zr) + SQR(mb->zyklus[j][1]-zi) < 0.0000000000000001)

                        break;

                if(j){

                    c= i-j;

                    c= ((c<<5)&0xE0) + ((c<<16)&0xE000) + ((c<<27)&0xE00000);

                }

                }else if(mb->inner==CONVTIME){

                    c= floor(i*255.0/mb->maxiter+dv)*0x010101;

                } else if(mb->inner==MINCOL){

                    int j;

                    double closest=9999;

                    int closest_index=0;

                    for(j=i-1; j>=0; j--)

                        if(SQR(mb->zyklus[j][0]) + SQR(mb->zyklus[j][1]) < closest){

                            closest= SQR(mb->zyklus[j][0]) + SQR(mb->zyklus[j][1]);

                            closest_index= j;

                        }

                    closest = sqrt(closest);

                    c= lrintf((mb->zyklus[closest_index][0]/closest+1)*127+dv) + lrintf((mb->zyklus[closest_index][1]/closest+1)*127+dv)*256;

                }

            }

            c |= 0xFF000000;

            color[x + y*linesize]= c;

            if(next_cidx < mb->cache_allocated){

                mb->next_cache[next_cidx  ].p[0]= cr;

                mb->next_cache[next_cidx  ].p[1]= ci;

                mb->next_cache[next_cidx++].val = c;

            }

        }

        fill_from_cache(ctx, NULL, &in_cidx, &next_cidx, ci + scale/2, scale);

    }

    FFSWAP(void*, mb->next_cache, mb->point_cache);

    mb->cache_used = next_cidx;

    if(mb->cache_used == mb->cache_allocated)

        av_log(0, AV_LOG_INFO, "Mandelbrot cache is too small!\n");

}


static void opt_mb_qmax(const char *arg)

{

    video_mb_qmax = atoi(arg);

    if (video_mb_qmax < 0 ||

        video_mb_qmax > 31) {

        fprintf(stderr, "qmax must be >= 1 and <= 31\n");

        exit(1);

    }

}


static RawAIOCB *raw_aio_setup(BlockDriverState *bs,

        int64_t sector_num, uint8_t *buf, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    BDRVRawState *s = bs->opaque;

    RawAIOCB *acb;

    if (fd_open(bs) < 0)

        return NULL;

    acb = qemu_aio_get(bs, cb, opaque);

    if (!acb)

        return NULL;

    acb->fd = raw_fd_pool_get(s);

    acb->aiocb.aio_fildes = acb->fd;

    acb->aiocb.aio_sigevent.sigev_signo = SIGUSR2;

    acb->aiocb.aio_sigevent.sigev_notify = SIGEV_SIGNAL;

    acb->aiocb.aio_buf = buf;

    if (nb_sectors < 0)

        acb->aiocb.aio_nbytes = -nb_sectors;

    else

        acb->aiocb.aio_nbytes = nb_sectors * 512;

    acb->aiocb.aio_offset = sector_num * 512;

    acb->next = posix_aio_state->first_aio;

    posix_aio_state->first_aio = acb;

    return acb;

}


static uint32_t tpm_tis_data_read(TPMState *s, uint8_t locty)

{

    TPMTISEmuState *tis = &s->s.tis;

    uint32_t ret = TPM_TIS_NO_DATA_BYTE;

    uint16_t len;

    if ((tis->loc[locty].sts & TPM_TIS_STS_DATA_AVAILABLE)) {

        len = tpm_tis_get_size_from_buffer(&tis->loc[locty].r_buffer);

        ret = tis->loc[locty].r_buffer.buffer[tis->loc[locty].r_offset++];

        if (tis->loc[locty].r_offset >= len) {

            /* got last byte */

            tis->loc[locty].sts = TPM_TIS_STS_VALID;

#ifdef RAISE_STS_IRQ

            tpm_tis_raise_irq(s, locty, TPM_TIS_INT_STS_VALID);

#endif

        }

        DPRINTF("tpm_tis: tpm_tis_data_read byte 0x%02x   [%d]\n",

                ret, tis->loc[locty].r_offset-1);

    }

    return ret;

}


cpu_x86_dump_seg_cache(CPUState *env, FILE *f,

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

                       const char *name, struct SegmentCache *sc)

{

#ifdef TARGET_X86_64

    if (env->hflags & HF_CS64_MASK) {

        cpu_fprintf(f, "%-3s=%04x %016" PRIx64 " %08x %08x", name,

                    sc->selector, sc->base, sc->limit, sc->flags);

    } else

#endif

    {

        cpu_fprintf(f, "%-3s=%04x %08x %08x %08x", name, sc->selector,

                    (uint32_t)sc->base, sc->limit, sc->flags);

    }

    if (!(env->hflags & HF_PE_MASK) || !(sc->flags & DESC_P_MASK))

        goto done;

    cpu_fprintf(f, " DPL=%d ", (sc->flags & DESC_DPL_MASK) >> DESC_DPL_SHIFT);

    if (sc->flags & DESC_S_MASK) {

        if (sc->flags & DESC_CS_MASK) {

            cpu_fprintf(f, (sc->flags & DESC_L_MASK) ? "CS64" :

                           ((sc->flags & DESC_B_MASK) ? "CS32" : "CS16"));

            cpu_fprintf(f, " [%c%c", (sc->flags & DESC_C_MASK) ? 'C' : '-',

                        (sc->flags & DESC_R_MASK) ? 'R' : '-');

        } else {

            cpu_fprintf(f, (sc->flags & DESC_B_MASK) ? "DS  " : "DS16");

            cpu_fprintf(f, " [%c%c", (sc->flags & DESC_E_MASK) ? 'E' : '-',

                        (sc->flags & DESC_W_MASK) ? 'W' : '-');

        }

        cpu_fprintf(f, "%c]", (sc->flags & DESC_A_MASK) ? 'A' : '-');

    } else {

        static const char *sys_type_name[2][16] = {

            { /* 32 bit mode */

                "Reserved", "TSS16-avl", "LDT", "TSS16-busy",

                "CallGate16", "TaskGate", "IntGate16", "TrapGate16",

                "Reserved", "TSS32-avl", "Reserved", "TSS32-busy",

                "CallGate32", "Reserved", "IntGate32", "TrapGate32"

            },

            { /* 64 bit mode */

                "<hiword>", "Reserved", "LDT", "Reserved", "Reserved",

                "Reserved", "Reserved", "Reserved", "Reserved",

                "TSS64-avl", "Reserved", "TSS64-busy", "CallGate64",

                "Reserved", "IntGate64", "TrapGate64"

            }

        };

        cpu_fprintf(f, "%s",

                    sys_type_name[(env->hflags & HF_LMA_MASK) ? 1 : 0]

                                 [(sc->flags & DESC_TYPE_MASK)

                                  >> DESC_TYPE_SHIFT]);

    }

done:

    cpu_fprintf(f, "\n");

}


static int qemu_gluster_parse_uri(BlockdevOptionsGluster *gconf,

                                  const char *filename)

{

    SocketAddress *gsconf;

    URI *uri;

    QueryParams *qp = NULL;

    bool is_unix = false;

    int ret = 0;

    uri = uri_parse(filename);

    if (!uri) {

        return -EINVAL;

    }

    gconf->server = g_new0(SocketAddressList, 1);

    gconf->server->value = gsconf = g_new0(SocketAddress, 1);

    /* transport */

    if (!uri->scheme || !strcmp(uri->scheme, "gluster")) {

        gsconf->type = SOCKET_ADDRESS_TYPE_INET;

    } else if (!strcmp(uri->scheme, "gluster+tcp")) {

        gsconf->type = SOCKET_ADDRESS_TYPE_INET;

    } else if (!strcmp(uri->scheme, "gluster+unix")) {

        gsconf->type = SOCKET_ADDRESS_TYPE_UNIX;

        is_unix = true;

    } else if (!strcmp(uri->scheme, "gluster+rdma")) {

        gsconf->type = SOCKET_ADDRESS_TYPE_INET;

        error_report("Warning: rdma feature is not supported, falling "

                     "back to tcp");

    } else {

        ret = -EINVAL;

        goto out;

    }

    ret = parse_volume_options(gconf, uri->path);

    if (ret < 0) {

        goto out;

    }

    qp = query_params_parse(uri->query);

    if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {

        ret = -EINVAL;

        goto out;

    }

    if (is_unix) {

        if (uri->server || uri->port) {

            ret = -EINVAL;

            goto out;

        }

        if (strcmp(qp->p[0].name, "socket")) {

            ret = -EINVAL;

            goto out;

        }

        gsconf->u.q_unix.path = g_strdup(qp->p[0].value);

    } else {

        gsconf->u.inet.host = g_strdup(uri->server ? uri->server : "localhost");

        if (uri->port) {

            gsconf->u.inet.port = g_strdup_printf("%d", uri->port);

        } else {

            gsconf->u.inet.port = g_strdup_printf("%d", GLUSTER_DEFAULT_PORT);

        }

    }

out:

    if (qp) {

        query_params_free(qp);

    }

    uri_free(uri);

    return ret;

}


static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque, int type)

{

    RawWin32AIOData *acb = g_slice_new(RawWin32AIOData);

    acb->bs = bs;

    acb->hfile = hfile;

    acb->aio_type = type;

    if (qiov) {

        acb->aio_iov = qiov->iov;

        acb->aio_niov = qiov->niov;

    }

    acb->aio_nbytes = nb_sectors * 512;

    acb->aio_offset = sector_num * 512;

    trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);

    return thread_pool_submit_aio(aio_worker, acb, cb, opaque);

}


static void special_write(void *opaque, target_phys_addr_t addr,

                          uint64_t val, unsigned size)

{

    qemu_log("pci: special write cycle");

}


MemoryRegionSection *phys_page_find(AddressSpaceDispatch *d, hwaddr index)

{

    PhysPageEntry lp = d->phys_map;

    PhysPageEntry *p;

    int i;

    for (i = P_L2_LEVELS - 1; i >= 0 && !lp.is_leaf; i--) {

        if (lp.ptr == PHYS_MAP_NODE_NIL) {

            return &phys_sections[phys_section_unassigned];

        }

        p = phys_map_nodes[lp.ptr];

        lp = p[(index >> (i * L2_BITS)) & (L2_SIZE - 1)];

    }

    return &phys_sections[lp.ptr];

}


static inline int qemu_gluster_zerofill(struct glfs_fd *fd, int64_t offset,

                                        int64_t size)

{

    return glfs_zerofill(fd, offset, size);

}


static void write_cont (void *opaque, uint32_t nport, uint32_t data)

{

    struct dma_cont *d = opaque;

    int iport, ichan;

    iport = (nport >> d->dshift) & 0x0f;

    switch (iport) {

    case 8:                     /* command */

        if (data && (data | CMD_NOT_SUPPORTED)) {

            log ("command %#x not supported\n", data);

            goto error;

        }

        d->command = data;

        break;

    case 9:

        ichan = data & 3;

        if (data & 4) {

            d->status |= 1 << (ichan + 4);

        }

        else {

            d->status &= ~(1 << (ichan + 4));

        }

        d->status &= ~(1 << ichan);

        break;

    case 0xa:                   /* single mask */

        if (data & 4)

            d->mask |= 1 << (data & 3);

        else

            d->mask &= ~(1 << (data & 3));

        break;

    case 0xb:                   /* mode */

        {

            ichan = data & 3;

#ifdef DEBUG_DMA

            int op;

            int ai;

            int dir;

            int opmode;

            op = (data >> 2) & 3;

            ai = (data >> 4) & 1;

            dir = (data >> 5) & 1;

            opmode = (data >> 6) & 3;

            linfo ("ichan %d, op %d, ai %d, dir %d, opmode %d\n",

                   ichan, op, ai, dir, opmode);

#endif

            d->regs[ichan].mode = data;

            break;

        }

    case 0xc:                   /* clear flip flop */

        d->flip_flop = 0;

        break;

    case 0xd:                   /* reset */

        d->flip_flop = 0;

        d->mask = ~0;

        d->status = 0;

        d->command = 0;

        break;

    case 0xe:                   /* clear mask for all channels */

        d->mask = 0;

        break;

    case 0xf:                   /* write mask for all channels */

        d->mask = data;

        break;

    default:

        log ("dma: unknown iport %#x\n", iport);

        goto error;

    }

#ifdef DEBUG_DMA

    if (0xc != iport) {

        linfo ("nport %#06x, ichan % 2d, val %#06x\n",

               nport, ichan, data);

    }

#endif

    return;

 error:

    abort ();

}


static void test_visitor_in_fail_list(TestInputVisitorData *data,

                                      const void *unused)

{

    int64_t i64 = -1;

    Visitor *v;

    /* Unvisited list tail */

    v = visitor_input_test_init(data, "[ 1, 2, 3 ]");

    visit_start_list(v, NULL, NULL, 0, &error_abort);

    visit_type_int(v, NULL, &i64, &error_abort);

    g_assert_cmpint(i64, ==, 1);

    visit_type_int(v, NULL, &i64, &error_abort);

    g_assert_cmpint(i64, ==, 2);

    visit_end_list(v, NULL);

    /* BUG: unvisited tail not reported; actually not reportable by design */

}


void qemu_console_copy(QEMUConsole *console, int src_x, int src_y,

                int dst_x, int dst_y, int w, int h) {

    if (active_console == console) {

        if (console->ds->dpy_copy)

            console->ds->dpy_copy(console->ds,

                            src_x, src_y, dst_x, dst_y, w, h);

        else {

            /* TODO */

            console->ds->dpy_update(console->ds, dst_x, dst_y, w, h);

        }

    }

}


static inline void tcg_out_ldst(TCGContext *s, int ret, int addr, int offset, int op)

{

    if (offset == (offset & 0xfff))

        tcg_out32(s, op | INSN_RD(ret) | INSN_RS1(addr) |

                  INSN_IMM13(offset));

    else

        fprintf(stderr, "unimplemented %s with offset %d\n", __func__, offset);

}


static int i440fx_initfn(PCIDevice *dev)

{

    PCII440FXState *d = DO_UPCAST(PCII440FXState, dev, dev);

    pci_config_set_vendor_id(d->dev.config, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(d->dev.config, PCI_DEVICE_ID_INTEL_82441);

    d->dev.config[0x08] = 0x02; // revision

    pci_config_set_class(d->dev.config, PCI_CLASS_BRIDGE_HOST);

    d->dev.config[I440FX_SMRAM] = 0x02;

    cpu_smm_register(&i440fx_set_smm, d);

    return 0;

}


void cpu_register_physical_memory_log(MemoryRegionSection *section,

                                      bool readonly)

{

    MemoryRegionSection now = *section, remain = *section;

    if ((now.offset_within_address_space & ~TARGET_PAGE_MASK)

        || (now.size < TARGET_PAGE_SIZE)) {

        now.size = MIN(TARGET_PAGE_ALIGN(now.offset_within_address_space)

                       - now.offset_within_address_space,

                       now.size);

        register_subpage(&now);

        remain.size -= now.size;

        remain.offset_within_address_space += now.size;

        remain.offset_within_region += now.size;

    }

    while (remain.size >= TARGET_PAGE_SIZE) {

        now = remain;

        if (remain.offset_within_region & ~TARGET_PAGE_MASK) {

            now.size = TARGET_PAGE_SIZE;

            register_subpage(&now);

        } else {

            now.size &= TARGET_PAGE_MASK;

            register_multipage(&now);

        }

        remain.size -= now.size;

        remain.offset_within_address_space += now.size;

        remain.offset_within_region += now.size;

    }

    now = remain;

    if (now.size) {

        register_subpage(&now);

    }

}


static void virtio_blk_handle_flush(BlockRequest *blkreq, int *num_writes,

    VirtIOBlockReq *req)

{

    BlockDriverAIOCB *acb;

    /*

     * Make sure all outstanding writes are posted to the backing device.

     */

    if (*num_writes > 0) {

        do_multiwrite(req->dev->bs, blkreq, *num_writes);

    }

    *num_writes = 0;

    acb = bdrv_aio_flush(req->dev->bs, virtio_blk_flush_complete, req);

    if (!acb) {

        virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);

    }

}


static void gd_update_cursor(VirtualConsole *vc)

{

    GtkDisplayState *s = vc->s;

    GdkWindow *window;

    if (vc->type != GD_VC_GFX) {

        return;

    }

    window = gtk_widget_get_window(GTK_WIDGET(vc->gfx.drawing_area));

    if (s->full_screen || qemu_input_is_absolute() || gd_is_grab_active(s)) {

        gdk_window_set_cursor(window, s->null_cursor);

    } else {

        gdk_window_set_cursor(window, NULL);

    }

}


static void sdhci_sdma_transfer_multi_blocks(SDHCIState *s)

{

    bool page_aligned = false;

    unsigned int n, begin;

    const uint16_t block_size = s->blksize & 0x0fff;

    uint32_t boundary_chk = 1 << (((s->blksize & 0xf000) >> 12) + 12);

    uint32_t boundary_count = boundary_chk - (s->sdmasysad % boundary_chk);

    /* XXX: Some sd/mmc drivers (for example, u-boot-slp) do not account for

     * possible stop at page boundary if initial address is not page aligned,

     * allow them to work properly */

    if ((s->sdmasysad % boundary_chk) == 0) {

        page_aligned = true;

    }

    if (s->trnmod & SDHC_TRNS_READ) {

        s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |

                SDHC_DAT_LINE_ACTIVE;

        while (s->blkcnt) {

            if (s->data_count == 0) {

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

                    s->fifo_buffer[n] = sdbus_read_data(&s->sdbus);

                }

            }

            begin = s->data_count;

            if (((boundary_count + begin) < block_size) && page_aligned) {

                s->data_count = boundary_count + begin;

                boundary_count = 0;

             } else {

                s->data_count = block_size;

                boundary_count -= block_size - begin;

                if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

                    s->blkcnt--;

                }

            }

            dma_memory_write(&address_space_memory, s->sdmasysad,

                             &s->fifo_buffer[begin], s->data_count - begin);

            s->sdmasysad += s->data_count - begin;

            if (s->data_count == block_size) {

                s->data_count = 0;

            }

            if (page_aligned && boundary_count == 0) {

                break;

            }

        }

    } else {

        s->prnsts |= SDHC_DOING_WRITE | SDHC_DATA_INHIBIT |

                SDHC_DAT_LINE_ACTIVE;

        while (s->blkcnt) {

            begin = s->data_count;

            if (((boundary_count + begin) < block_size) && page_aligned) {

                s->data_count = boundary_count + begin;

                boundary_count = 0;

             } else {

                s->data_count = block_size;

                boundary_count -= block_size - begin;

            }

            dma_memory_read(&address_space_memory, s->sdmasysad,

                            &s->fifo_buffer[begin], s->data_count);

            s->sdmasysad += s->data_count - begin;

            if (s->data_count == block_size) {

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

                    sdbus_write_data(&s->sdbus, s->fifo_buffer[n]);

                }

                s->data_count = 0;

                if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

                    s->blkcnt--;

                }

            }

            if (page_aligned && boundary_count == 0) {

                break;

            }

        }

    }

    if (s->blkcnt == 0) {

        sdhci_end_transfer(s);

    } else {

        if (s->norintstsen & SDHC_NISEN_DMA) {

            s->norintsts |= SDHC_NIS_DMA;

        }

        sdhci_update_irq(s);

    }

}


static int read_access_unit(AVCodecContext *avctx, void* data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MLPDecodeContext *m = avctx->priv_data;

    GetBitContext gb;

    unsigned int length, substr;

    unsigned int substream_start;

    unsigned int header_size = 4;

    unsigned int substr_header_size = 0;

    uint8_t substream_parity_present[MAX_SUBSTREAMS];

    uint16_t substream_data_len[MAX_SUBSTREAMS];

    uint8_t parity_bits;

    if (buf_size < 4)

        return 0;

    length = (AV_RB16(buf) & 0xfff) * 2;

    if (length > buf_size)

        return -1;

    init_get_bits(&gb, (buf + 4), (length - 4) * 8);

    m->is_major_sync_unit = 0;

    if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {

        if (read_major_sync(m, &gb) < 0)

            goto error;

        m->is_major_sync_unit = 1;

        header_size += 28;

    }

    if (!m->params_valid) {

        av_log(m->avctx, AV_LOG_WARNING,

               "Stream parameters not seen; skipping frame.\n");

        *data_size = 0;

        return length;

    }

    substream_start = 0;

    for (substr = 0; substr < m->num_substreams; substr++) {

        int extraword_present, checkdata_present, end, nonrestart_substr;

        extraword_present = get_bits1(&gb);

        nonrestart_substr = get_bits1(&gb);

        checkdata_present = get_bits1(&gb);

        skip_bits1(&gb);

        end = get_bits(&gb, 12) * 2;

        substr_header_size += 2;

        if (extraword_present) {

            if (m->avctx->codec_id == CODEC_ID_MLP) {

                av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");

                goto error;

            }

            skip_bits(&gb, 16);

            substr_header_size += 2;

        }

        if (!(nonrestart_substr ^ m->is_major_sync_unit)) {

            av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");

            goto error;

        }

        if (end + header_size + substr_header_size > length) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "Indicated length of substream %d data goes off end of "

                   "packet.\n", substr);

            end = length - header_size - substr_header_size;

        }

        if (end < substream_start) {

            av_log(avctx, AV_LOG_ERROR,

                   "Indicated end offset of substream %d data "

                   "is smaller than calculated start offset.\n",

                   substr);

            goto error;

        }

        if (substr > m->max_decoded_substream)

            continue;

        substream_parity_present[substr] = checkdata_present;

        substream_data_len[substr] = end - substream_start;

        substream_start = end;

    }

    parity_bits  = ff_mlp_calculate_parity(buf, 4);

    parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);

    if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {

        av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");

        goto error;

    }

    buf += header_size + substr_header_size;

    for (substr = 0; substr <= m->max_decoded_substream; substr++) {

        SubStream *s = &m->substream[substr];

        init_get_bits(&gb, buf, substream_data_len[substr] * 8);

        m->matrix_changed = 0;

        memset(m->filter_changed, 0, sizeof(m->filter_changed));

        s->blockpos = 0;

        do {

            unsigned int ch;

            if (get_bits1(&gb)) {

                if (get_bits1(&gb)) {

                    /* A restart header should be present. */

                    if (read_restart_header(m, &gb, buf, substr) < 0)

                        goto next_substr;

                    s->restart_seen = 1;

                }

                if (!s->restart_seen) {

                    goto next_substr;

                }

                if (read_decoding_params(m, &gb, substr) < 0)

                    goto next_substr;

            }

            if (m->matrix_changed > 1) {

                av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");

                goto next_substr;

            }

            for (ch = 0; ch < s->max_channel; ch++)

                if (m->filter_changed[ch][FIR] > 1 ||

                    m->filter_changed[ch][IIR] > 1) {

                    av_log(m->avctx, AV_LOG_ERROR, "Filters may change only once per access unit.\n");

                    goto next_substr;

                }

            if (!s->restart_seen) {

                goto next_substr;

            }

            if (read_block_data(m, &gb, substr) < 0)

                return -1;

            if (get_bits_count(&gb) >= substream_data_len[substr] * 8)

                goto substream_length_mismatch;

        } while (!get_bits1(&gb));

        skip_bits(&gb, (-get_bits_count(&gb)) & 15);

        if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {

            int shorten_by;

            if (get_bits(&gb, 16) != 0xD234)

                return -1;

            shorten_by = get_bits(&gb, 16);

            if      (m->avctx->codec_id == CODEC_ID_TRUEHD && shorten_by  & 0x2000)

                s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);

            else if (m->avctx->codec_id == CODEC_ID_MLP    && shorten_by != 0xD234)

                return -1;

            if (substr == m->max_decoded_substream)

                av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");

        }

        if (substream_parity_present[substr]) {

            uint8_t parity, checksum;

            if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)

                goto substream_length_mismatch;

            parity   = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);

            checksum = ff_mlp_checksum8       (buf, substream_data_len[substr] - 2);

            if ((get_bits(&gb, 8) ^ parity) != 0xa9    )

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);

            if ( get_bits(&gb, 8)           != checksum)

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n"    , substr);

        }

        if (substream_data_len[substr] * 8 != get_bits_count(&gb)) {

            goto substream_length_mismatch;

        }

next_substr:

        if (!s->restart_seen) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "No restart header present in substream %d.\n", substr);

        }

        buf += substream_data_len[substr];

    }

    rematrix_channels(m, m->max_decoded_substream);

    if (output_data(m, m->max_decoded_substream, data, data_size) < 0)

        return -1;

    return length;

substream_length_mismatch:

    av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);

    return -1;

error:

    m->params_valid = 0;

    return -1;

}


static int coroutine_fn blkreplay_co_preadv(BlockDriverState *bs,

    uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)

{

    uint64_t reqid = request_id++;

    int ret = bdrv_co_preadv(bs->file->bs, offset, bytes, qiov, flags);

    block_request_create(reqid, bs, qemu_coroutine_self());

    qemu_coroutine_yield();

    return ret;

}


void s390x_tod_timer(void *opaque)

{

    S390CPU *cpu = opaque;

    CPUS390XState *env = &cpu->env;

    env->pending_int |= INTERRUPT_TOD;

    cpu_interrupt(CPU(cpu), CPU_INTERRUPT_HARD);

}


static uint8_t qpci_spapr_io_readb(QPCIBus *bus, void *addr)

{

    QPCIBusSPAPR *s = container_of(bus, QPCIBusSPAPR, bus);

    uint64_t port = (uintptr_t)addr;

    uint8_t v;

    if (port < s->pio.size) {

        v = readb(s->pio_cpu_base + port);

    } else {

        v = readb(s->mmio_cpu_base + port);

    }

    return v;

}


static void bench_cb(void *opaque, int ret)

{

    BenchData *b = opaque;

    BlockAIOCB *acb;

    if (ret < 0) {

        error_report("Failed request: %s\n", strerror(-ret));

        exit(EXIT_FAILURE);

    }

    if (b->in_flush) {

        /* Just finished a flush with drained queue: Start next requests */

        assert(b->in_flight == 0);

        b->in_flush = false;

    } else if (b->in_flight > 0) {

        int remaining = b->n - b->in_flight;

        b->n--;

        b->in_flight--;

        /* Time for flush? Drain queue if requested, then flush */

        if (b->flush_interval && remaining % b->flush_interval == 0) {

            if (!b->in_flight || !b->drain_on_flush) {

                BlockCompletionFunc *cb;

                if (b->drain_on_flush) {

                    b->in_flush = true;

                    cb = bench_cb;

                } else {

                    cb = bench_undrained_flush_cb;

                }

                acb = blk_aio_flush(b->blk, cb, b);

                if (!acb) {

                    error_report("Failed to issue flush request");

                    exit(EXIT_FAILURE);

                }

            }

            if (b->drain_on_flush) {

                return;

            }

        }

    }

    while (b->n > b->in_flight && b->in_flight < b->nrreq) {

        if (b->write) {

            acb = blk_aio_pwritev(b->blk, b->offset, b->qiov, 0,

                                  bench_cb, b);

        } else {

            acb = blk_aio_preadv(b->blk, b->offset, b->qiov, 0,

                                 bench_cb, b);

        }

        if (!acb) {

            error_report("Failed to issue request");

            exit(EXIT_FAILURE);

        }

        b->in_flight++;

        b->offset += b->step;

        b->offset %= b->image_size;

    }

}


static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,

                                                   int64_t offset,

                                                   int64_t length,

                                                   uint64_t addend,

                                                   bool decrease,

                                                   enum qcow2_discard_type type)

{

    BDRVQcowState *s = bs->opaque;

    int64_t start, last, cluster_offset;

    void *refcount_block = NULL;

    int64_t old_table_index = -1;

    int ret;

#ifdef DEBUG_ALLOC2

    fprintf(stderr, "update_refcount: offset=%" PRId64 " size=%" PRId64

            " addend=%s%" PRIu64 "\n", offset, length, decrease ? "-" : "",

            addend);

#endif

    if (length < 0) {

        return -EINVAL;

    } else if (length == 0) {

        return 0;

    }

    if (decrease) {

        qcow2_cache_set_dependency(bs, s->refcount_block_cache,

            s->l2_table_cache);

    }

    start = start_of_cluster(s, offset);

    last = start_of_cluster(s, offset + length - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size)

    {

        int block_index;

        uint64_t refcount;

        int64_t cluster_index = cluster_offset >> s->cluster_bits;

        int64_t table_index = cluster_index >> s->refcount_block_bits;

        /* Load the refcount block and allocate it if needed */

        if (table_index != old_table_index) {

            if (refcount_block) {

                ret = qcow2_cache_put(bs, s->refcount_block_cache,

                                      &refcount_block);

                if (ret < 0) {

                    goto fail;

                }

            }

            ret = alloc_refcount_block(bs, cluster_index, &refcount_block);

            if (ret < 0) {

                goto fail;

            }

        }

        old_table_index = table_index;

        qcow2_cache_entry_mark_dirty(bs, s->refcount_block_cache,

                                     refcount_block);

        /* we can update the count and save it */

        block_index = cluster_index & (s->refcount_block_size - 1);

        refcount = s->get_refcount(refcount_block, block_index);

        if (decrease ? (refcount - addend > refcount)

                     : (refcount + addend < refcount ||

                        refcount + addend > s->refcount_max))

        {

            ret = -EINVAL;

            goto fail;

        }

        if (decrease) {

            refcount -= addend;

        } else {

            refcount += addend;

        }

        if (refcount == 0 && cluster_index < s->free_cluster_index) {

            s->free_cluster_index = cluster_index;

        }

        s->set_refcount(refcount_block, block_index, refcount);

        if (refcount == 0 && s->discard_passthrough[type]) {

            update_refcount_discard(bs, cluster_offset, s->cluster_size);

        }

    }

    ret = 0;

fail:

    if (!s->cache_discards) {

        qcow2_process_discards(bs, ret);

    }

    /* Write last changed block to disk */

    if (refcount_block) {

        int wret;

        wret = qcow2_cache_put(bs, s->refcount_block_cache, &refcount_block);

        if (wret < 0) {

            return ret < 0 ? ret : wret;

        }

    }

    /*

     * Try do undo any updates if an error is returned (This may succeed in

     * some cases like ENOSPC for allocating a new refcount block)

     */

    if (ret < 0) {

        int dummy;

        dummy = update_refcount(bs, offset, cluster_offset - offset, addend,

                                !decrease, QCOW2_DISCARD_NEVER);

        (void)dummy;

    }

    return ret;

}


static void virtio_scsi_clear_aio(VirtIOSCSI *s)

{

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    int i;

    if (s->ctrl_vring) {

        aio_set_event_notifier(s->ctx, &s->ctrl_vring->host_notifier,

                               false, NULL);

    }

    if (s->event_vring) {

        aio_set_event_notifier(s->ctx, &s->event_vring->host_notifier,

                               false, NULL);

    }

    if (s->cmd_vrings) {

        for (i = 0; i < vs->conf.num_queues && s->cmd_vrings[i]; i++) {

            aio_set_event_notifier(s->ctx, &s->cmd_vrings[i]->host_notifier,

                                   false, NULL);

        }

    }

}


create_iovec(BlockBackend *blk, QEMUIOVector *qiov, char **argv, int nr_iov,

             int pattern)

{

    size_t *sizes = g_new0(size_t, nr_iov);

    size_t count = 0;

    void *buf = NULL;

    void *p;

    int i;

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

        char *arg = argv[i];

        int64_t len;

        len = cvtnum(arg);

        if (len < 0) {

            print_cvtnum_err(len, arg);

            goto fail;

        }

        /* should be SIZE_T_MAX, but that doesn't exist */

        if (len > INT_MAX) {

            printf("Argument '%s' exceeds maximum size %d\n", arg, INT_MAX);

            goto fail;

        }

        sizes[i] = len;

        count += len;

    }

    qemu_iovec_init(qiov, nr_iov);

    buf = p = qemu_io_alloc(blk, count, pattern);

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

        qemu_iovec_add(qiov, p, sizes[i]);

        p += sizes[i];

    }

fail:

    g_free(sizes);

    return buf;

}


static void pflash_update(pflash_t *pfl, int offset,

                          int size)

{

    int offset_end;

    if (pfl->bs) {

        offset_end = offset + size;

        /* round to sectors */

        offset = offset >> 9;

        offset_end = (offset_end + 511) >> 9;

        bdrv_write(pfl->bs, offset, pfl->storage + (offset << 9),

                   offset_end - offset);

    }

}


static int piix4_initfn(PCIDevice *d)

{

    uint8_t *pci_conf;

    isa_bus_new(&d->qdev);

    register_savevm("PIIX4", 0, 2, piix_save, piix_load, d);

    pci_conf = d->config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371AB_0); // 82371AB/EB/MB PIIX4 PCI-to-ISA bridge

    pci_config_set_class(pci_conf, PCI_CLASS_BRIDGE_ISA);

    pci_conf[PCI_HEADER_TYPE] =

        PCI_HEADER_TYPE_NORMAL | PCI_HEADER_TYPE_MULTI_FUNCTION; // header_type = PCI_multifunction, generic

    piix4_dev = d;

    piix4_reset(d);

    qemu_register_reset(piix4_reset, d);

    return 0;

}


void nbd_client_session_detach_aio_context(NbdClientSession *client)

{

    aio_set_fd_handler(bdrv_get_aio_context(client->bs), client->sock,

                       NULL, NULL, NULL);

}


static void fd_put_notify(void *opaque)

{

    QEMUFileFD *s = opaque;

    /* Remove writable callback and do a put notify */

    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);

    qemu_file_put_notify(s->file);

}


int qemu_savevm_state_iterate(Monitor *mon, QEMUFile *f)

{

    SaveStateEntry *se;

    int ret = 1;

    QTAILQ_FOREACH(se, &savevm_handlers, entry) {

        if (se->save_live_state == NULL)

            continue;

        /* Section type */

        qemu_put_byte(f, QEMU_VM_SECTION_PART);

        qemu_put_be32(f, se->section_id);

        ret = se->save_live_state(mon, f, QEMU_VM_SECTION_PART, se->opaque);

        if (!ret) {

            /* Do not proceed to the next vmstate before this one reported

               completion of the current stage. This serializes the migration

               and reduces the probability that a faster changing state is

               synchronized over and over again. */

            break;

        }

    }

    if (ret != 0) {

        return ret;

    }

    ret = qemu_file_get_error(f);

    if (ret != 0) {

        qemu_savevm_state_cancel(mon, f);

    }

    return ret;

}


int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,

    int n_start, int n_end, int *num, uint64_t *host_offset, QCowL2Meta **m)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t start, remaining;

    uint64_t cluster_offset;

    uint64_t cur_bytes;

    int ret;

    trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset,

                                      n_start, n_end);

    assert(n_start * BDRV_SECTOR_SIZE == offset_into_cluster(s, offset));

    offset = start_of_cluster(s, offset);

again:

    start = offset + (n_start << BDRV_SECTOR_BITS);

    remaining = (n_end - n_start) << BDRV_SECTOR_BITS;

    cluster_offset = 0;

    *host_offset = 0;

    /*

     * Now start gathering as many contiguous clusters as possible:

     *

     * 1. Check for overlaps with in-flight allocations

     *

     *      a) Overlap not in the first cluster -> shorten this request and let

     *         the caller handle the rest in its next loop iteration.

     *

     *      b) Real overlaps of two requests. Yield and restart the search for

     *         contiguous clusters (the situation could have changed while we

     *         were sleeping)

     *

     *      c) TODO: Request starts in the same cluster as the in-flight

     *         allocation ends. Shorten the COW of the in-fight allocation, set

     *         cluster_offset to write to the same cluster and set up the right

     *         synchronisation between the in-flight request and the new one.

     */

    cur_bytes = remaining;

    ret = handle_dependencies(bs, start, &cur_bytes);

    if (ret == -EAGAIN) {

        goto again;

    } else if (ret < 0) {

        return ret;

    } else {

        /* handle_dependencies() may have decreased cur_bytes (shortened

         * the allocations below) so that the next dependency is processed

         * correctly during the next loop iteration. */

    }

    /*

     * 2. Count contiguous COPIED clusters.

     */

    ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);

    if (ret < 0) {

        return ret;

    } else if (ret) {

        if (!*host_offset) {

            *host_offset = start_of_cluster(s, cluster_offset);

        }

        start           += cur_bytes;

        remaining       -= cur_bytes;

        cluster_offset  += cur_bytes;

        cur_bytes = remaining;

    } else if (cur_bytes == 0) {

        goto done;

    }

    /* If there is something left to allocate, do that now */

    if (remaining == 0) {

        goto done;

    }

    /*

     * 3. If the request still hasn't completed, allocate new clusters,

     *    considering any cluster_offset of steps 1c or 2.

     */

    ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);

    if (ret < 0) {

        return ret;

    } else if (ret) {

        if (!*host_offset) {

            *host_offset = start_of_cluster(s, cluster_offset);

        }

        start           += cur_bytes;

        remaining       -= cur_bytes;

        cluster_offset  += cur_bytes;

    }

    /* Some cleanup work */

done:

    *num = (n_end - n_start) - (remaining >> BDRV_SECTOR_BITS);

    assert(*num > 0);

    assert(*host_offset != 0);

    return 0;

}


QemuConsole *graphic_console_init(DeviceState *dev, uint32_t head,

                                  const GraphicHwOps *hw_ops,

                                  void *opaque)

{

    int width = 640;

    int height = 480;

    QemuConsole *s;

    DisplayState *ds;

    ds = get_alloc_displaystate();

    trace_console_gfx_new();

    s = new_console(ds, GRAPHIC_CONSOLE, head);

    s->hw_ops = hw_ops;

    s->hw = opaque;

    if (dev) {

        object_property_set_link(OBJECT(s), OBJECT(dev), "device",

                                 &error_abort);

    }

    s->surface = qemu_create_displaysurface(width, height);

    return s;

}


static inline void stw_phys_internal(target_phys_addr_t addr, uint32_t val,

                                     enum device_endian endian)

{

    uint8_t *ptr;

    MemoryRegionSection *section;

    section = phys_page_find(addr >> TARGET_PAGE_BITS);

    if (!memory_region_is_ram(section->mr) || section->readonly) {

        addr = memory_region_section_addr(section, addr);

        if (memory_region_is_ram(section->mr)) {

            section = &phys_sections[phys_section_rom];

        }

#if defined(TARGET_WORDS_BIGENDIAN)

        if (endian == DEVICE_LITTLE_ENDIAN) {

            val = bswap16(val);

        }

#else

        if (endian == DEVICE_BIG_ENDIAN) {

            val = bswap16(val);

        }

#endif

        io_mem_write(section->mr, addr, val, 2);

    } else {

        unsigned long addr1;

        addr1 = (memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK)

            + memory_region_section_addr(section, addr);

        /* RAM case */

        ptr = qemu_get_ram_ptr(addr1);

        switch (endian) {

        case DEVICE_LITTLE_ENDIAN:

            stw_le_p(ptr, val);

            break;

        case DEVICE_BIG_ENDIAN:

            stw_be_p(ptr, val);

            break;

        default:

            stw_p(ptr, val);

            break;

        }

        invalidate_and_set_dirty(addr1, 2);

    }

}


bool virtio_disk_is_eckd(void)

{

    if (guessed_disk_nature) {

        return (blk_cfg.blk_size  == 4096);

    }

    return (blk_cfg.geometry.heads == 15)

        && (blk_cfg.geometry.sectors == 12)

        && (blk_cfg.blk_size  == 4096);

}


static int nbd_send_option_request(QIOChannel *ioc, uint32_t opt,

                                   uint32_t len, const char *data,

                                   Error **errp)

{

    nbd_option req;

    QEMU_BUILD_BUG_ON(sizeof(req) != 16);

    if (len == -1) {

        req.length = len = strlen(data);

    }

    TRACE("Sending option request %" PRIu32", len %" PRIu32, opt, len);

    stq_be_p(&req.magic, NBD_OPTS_MAGIC);

    stl_be_p(&req.option, opt);

    stl_be_p(&req.length, len);

    if (write_sync(ioc, &req, sizeof(req), errp) < 0) {

        error_prepend(errp, "Failed to send option request header");

        return -1;

    }

    if (len && write_sync(ioc, (char *) data, len, errp) < 0) {

        error_prepend(errp, "Failed to send option request data");

        return -1;

    }

    return 0;

}


static void rtas_ibm_write_pci_config(sPAPREnvironment *spapr,

                                      uint32_t token, uint32_t nargs,

                                      target_ulong args,

                                      uint32_t nret, target_ulong rets)

{

    uint32_t val, size, addr;

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

    PCIDevice *dev = find_dev(spapr, buid, rtas_ld(args, 0));

    if (!dev) {

        rtas_st(rets, 0, -1);

        return;

    }

    val = rtas_ld(args, 4);

    size = rtas_ld(args, 3);

    addr = rtas_pci_cfgaddr(rtas_ld(args, 0));

    pci_host_config_write_common(dev, addr, pci_config_size(dev), val, size);

    rtas_st(rets, 0, 0);

}


static void *show_parts(void *arg)

{

    char *device = arg;

    int nbd;

    /* linux just needs an open() to trigger

     * the partition table update

     * but remember to load the module with max_part != 0 :

     *     modprobe nbd max_part=63

     */

    nbd = open(device, O_RDWR);

    if (nbd != -1) {

        close(nbd);

    }

    return NULL;

}


static TCGArg *tcg_constant_folding(TCGContext *s, uint16_t *tcg_opc_ptr,

                                    TCGArg *args, TCGOpDef *tcg_op_defs)

{

    int i, nb_ops, op_index, nb_temps, nb_globals, nb_call_args;

    TCGOpcode op;

    const TCGOpDef *def;

    TCGArg *gen_args;

    TCGArg tmp;

    TCGCond cond;

    /* Array VALS has an element for each temp.

       If this temp holds a constant then its value is kept in VALS' element.

       If this temp is a copy of other ones then this equivalence class'

       representative is kept in VALS' element.

       If this temp is neither copy nor constant then corresponding VALS'

       element is unused. */

    nb_temps = s->nb_temps;

    nb_globals = s->nb_globals;

    memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

    nb_ops = tcg_opc_ptr - gen_opc_buf;

    gen_args = args;

    for (op_index = 0; op_index < nb_ops; op_index++) {

        op = gen_opc_buf[op_index];

        def = &tcg_op_defs[op];

        /* Do copy propagation */

        if (!(def->flags & (TCG_OPF_CALL_CLOBBER | TCG_OPF_SIDE_EFFECTS))) {

            assert(op != INDEX_op_call);

            for (i = def->nb_oargs; i < def->nb_oargs + def->nb_iargs; i++) {

                if (temps[args[i]].state == TCG_TEMP_COPY) {

                    args[i] = temps[args[i]].val;

                }

            }

        }

        /* For commutative operations make constant second argument */

        switch (op) {

        CASE_OP_32_64(add):

        CASE_OP_32_64(mul):

        CASE_OP_32_64(and):

        CASE_OP_32_64(or):

        CASE_OP_32_64(xor):

        CASE_OP_32_64(eqv):

        CASE_OP_32_64(nand):

        CASE_OP_32_64(nor):

            if (temps[args[1]].state == TCG_TEMP_CONST) {

                tmp = args[1];

                args[1] = args[2];

                args[2] = tmp;

            }

            break;

        CASE_OP_32_64(brcond):

            if (temps[args[0]].state == TCG_TEMP_CONST

                && temps[args[1]].state != TCG_TEMP_CONST) {

                tmp = args[0];

                args[0] = args[1];

                args[1] = tmp;

                args[2] = tcg_swap_cond(args[2]);

            }

            break;

        CASE_OP_32_64(setcond):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state != TCG_TEMP_CONST) {

                tmp = args[1];

                args[1] = args[2];

                args[2] = tmp;

                args[3] = tcg_swap_cond(args[3]);

            }

            break;

        CASE_OP_32_64(movcond):

            cond = args[5];

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state != TCG_TEMP_CONST) {

                tmp = args[1];

                args[1] = args[2];

                args[2] = tmp;

                cond = tcg_swap_cond(cond);

            }

            /* For movcond, we canonicalize the "false" input reg to match

               the destination reg so that the tcg backend can implement

               a "move if true" operation.  */

            if (args[0] == args[3]) {

                tmp = args[3];

                args[3] = args[4];

                args[4] = tmp;

                cond = tcg_invert_cond(cond);

            }

            args[5] = cond;

        default:

            break;

        }

        /* Simplify expressions for "shift/rot r, 0, a => movi r, 0" */

        switch (op) {

        CASE_OP_32_64(shl):

        CASE_OP_32_64(shr):

        CASE_OP_32_64(sar):

        CASE_OP_32_64(rotl):

        CASE_OP_32_64(rotr):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[1]].val == 0) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tcg_opt_gen_movi(gen_args, args[0], 0, nb_temps, nb_globals);

                args += 3;

                gen_args += 2;

                continue;

            }

            break;

        default:

            break;

        }

        /* Simplify expression for "op r, a, 0 => mov r, a" cases */

        switch (op) {

        CASE_OP_32_64(add):

        CASE_OP_32_64(sub):

        CASE_OP_32_64(shl):

        CASE_OP_32_64(shr):

        CASE_OP_32_64(sar):

        CASE_OP_32_64(rotl):

        CASE_OP_32_64(rotr):

        CASE_OP_32_64(or):

        CASE_OP_32_64(xor):

            if (temps[args[1]].state == TCG_TEMP_CONST) {

                /* Proceed with possible constant folding. */

                break;

            }

            if (temps[args[2]].state == TCG_TEMP_CONST

                && temps[args[2]].val == 0) {

                if ((temps[args[0]].state == TCG_TEMP_COPY

                    && temps[args[0]].val == args[1])

                    || args[0] == args[1]) {

                    gen_opc_buf[op_index] = INDEX_op_nop;

                } else {

                    gen_opc_buf[op_index] = op_to_mov(op);

                    tcg_opt_gen_mov(gen_args, args[0], args[1],

                                    nb_temps, nb_globals);

                    gen_args += 2;

                }

                args += 3;

                continue;

            }

            break;

        default:

            break;

        }

        /* Simplify expression for "op r, a, 0 => movi r, 0" cases */

        switch (op) {

        CASE_OP_32_64(and):

        CASE_OP_32_64(mul):

            if ((temps[args[2]].state == TCG_TEMP_CONST

                && temps[args[2]].val == 0)) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tcg_opt_gen_movi(gen_args, args[0], 0, nb_temps, nb_globals);

                args += 3;

                gen_args += 2;

                continue;

            }

            break;

        default:

            break;

        }

        /* Simplify expression for "op r, a, a => mov r, a" cases */

        switch (op) {

        CASE_OP_32_64(or):

        CASE_OP_32_64(and):

            if (args[1] == args[2]) {

                if (args[1] == args[0]) {

                    gen_opc_buf[op_index] = INDEX_op_nop;

                } else {

                    gen_opc_buf[op_index] = op_to_mov(op);

                    tcg_opt_gen_mov(gen_args, args[0], args[1], nb_temps,

                                    nb_globals);

                    gen_args += 2;

                }

                args += 3;

                continue;

            }

            break;

        default:

            break;

        }

        /* Propagate constants through copy operations and do constant

           folding.  Constants will be substituted to arguments by register

           allocator where needed and possible.  Also detect copies. */

        switch (op) {

        CASE_OP_32_64(mov):

            if ((temps[args[1]].state == TCG_TEMP_COPY

                && temps[args[1]].val == args[0])

                || args[0] == args[1]) {

                args += 2;

                gen_opc_buf[op_index] = INDEX_op_nop;

                break;

            }

            if (temps[args[1]].state != TCG_TEMP_CONST) {

                tcg_opt_gen_mov(gen_args, args[0], args[1],

                                nb_temps, nb_globals);

                gen_args += 2;

                args += 2;

                break;

            }

            /* Source argument is constant.  Rewrite the operation and

               let movi case handle it. */

            op = op_to_movi(op);

            gen_opc_buf[op_index] = op;

            args[1] = temps[args[1]].val;

            /* fallthrough */

        CASE_OP_32_64(movi):

            tcg_opt_gen_movi(gen_args, args[0], args[1], nb_temps, nb_globals);

            gen_args += 2;

            args += 2;

            break;

        CASE_OP_32_64(not):

        CASE_OP_32_64(neg):

        CASE_OP_32_64(ext8s):

        CASE_OP_32_64(ext8u):

        CASE_OP_32_64(ext16s):

        CASE_OP_32_64(ext16u):

        case INDEX_op_ext32s_i64:

        case INDEX_op_ext32u_i64:

            if (temps[args[1]].state == TCG_TEMP_CONST) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tmp = do_constant_folding(op, temps[args[1]].val, 0);

                tcg_opt_gen_movi(gen_args, args[0], tmp, nb_temps, nb_globals);

            } else {

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

            }

            gen_args += 2;

            args += 2;

            break;

        CASE_OP_32_64(add):

        CASE_OP_32_64(sub):

        CASE_OP_32_64(mul):

        CASE_OP_32_64(or):

        CASE_OP_32_64(and):

        CASE_OP_32_64(xor):

        CASE_OP_32_64(shl):

        CASE_OP_32_64(shr):

        CASE_OP_32_64(sar):

        CASE_OP_32_64(rotl):

        CASE_OP_32_64(rotr):

        CASE_OP_32_64(andc):

        CASE_OP_32_64(orc):

        CASE_OP_32_64(eqv):

        CASE_OP_32_64(nand):

        CASE_OP_32_64(nor):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state == TCG_TEMP_CONST) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tmp = do_constant_folding(op, temps[args[1]].val,

                                          temps[args[2]].val);

                tcg_opt_gen_movi(gen_args, args[0], tmp, nb_temps, nb_globals);

                gen_args += 2;

            } else {

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

                gen_args[2] = args[2];

                gen_args += 3;

            }

            args += 3;

            break;

        CASE_OP_32_64(setcond):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state == TCG_TEMP_CONST) {

                gen_opc_buf[op_index] = op_to_movi(op);

                tmp = do_constant_folding_cond(op, temps[args[1]].val,

                                               temps[args[2]].val, args[3]);

                tcg_opt_gen_movi(gen_args, args[0], tmp, nb_temps, nb_globals);

                gen_args += 2;

            } else {

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

                gen_args[2] = args[2];

                gen_args[3] = args[3];

                gen_args += 4;

            }

            args += 4;

            break;

        CASE_OP_32_64(brcond):

            if (temps[args[0]].state == TCG_TEMP_CONST

                && temps[args[1]].state == TCG_TEMP_CONST) {

                if (do_constant_folding_cond(op, temps[args[0]].val,

                                             temps[args[1]].val, args[2])) {

                    memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

                    gen_opc_buf[op_index] = INDEX_op_br;

                    gen_args[0] = args[3];

                    gen_args += 1;

                } else {

                    gen_opc_buf[op_index] = INDEX_op_nop;

                }

            } else {

                memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

                gen_args[2] = args[2];

                gen_args[3] = args[3];

                gen_args += 4;

            }

            args += 4;

            break;

        CASE_OP_32_64(movcond):

            if (temps[args[1]].state == TCG_TEMP_CONST

                && temps[args[2]].state == TCG_TEMP_CONST) {

                tmp = do_constant_folding_cond(op, temps[args[1]].val,

                                               temps[args[2]].val, args[5]);

                if (args[0] == args[4-tmp]

                    || (temps[args[4-tmp]].state == TCG_TEMP_COPY

                        && temps[args[4-tmp]].val == args[0])) {

                    gen_opc_buf[op_index] = INDEX_op_nop;

                } else if (temps[args[4-tmp]].state == TCG_TEMP_CONST) {

                    gen_opc_buf[op_index] = op_to_movi(op);

                    tcg_opt_gen_movi(gen_args, args[0], temps[args[4-tmp]].val,

                                     nb_temps, nb_globals);

                    gen_args += 2;

                } else {

                    gen_opc_buf[op_index] = op_to_mov(op);

                    tcg_opt_gen_mov(gen_args, args[0], args[4-tmp],

                                    nb_temps, nb_globals);

                    gen_args += 2;

                }

            } else {

                reset_temp(args[0], nb_temps, nb_globals);

                gen_args[0] = args[0];

                gen_args[1] = args[1];

                gen_args[2] = args[2];

                gen_args[3] = args[3];

                gen_args[4] = args[4];

                gen_args[5] = args[5];

                gen_args += 6;

            }

            args += 6;

            break;

        case INDEX_op_call:

            nb_call_args = (args[0] >> 16) + (args[0] & 0xffff);

            if (!(args[nb_call_args + 1] & (TCG_CALL_CONST | TCG_CALL_PURE))) {

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

                    reset_temp(i, nb_temps, nb_globals);

                }

            }

            for (i = 0; i < (args[0] >> 16); i++) {

                reset_temp(args[i + 1], nb_temps, nb_globals);

            }

            i = nb_call_args + 3;

            while (i) {

                *gen_args = *args;

                args++;

                gen_args++;

                i--;

            }

            break;

        default:

            /* Default case: we do know nothing about operation so no

               propagation is done.  We trash everything if the operation

               is the end of a basic block, otherwise we only trash the

               output args.  */

            if (def->flags & TCG_OPF_BB_END) {

                memset(temps, 0, nb_temps * sizeof(struct tcg_temp_info));

            } else {

                for (i = 0; i < def->nb_oargs; i++) {

                    reset_temp(args[i], nb_temps, nb_globals);

                }

            }

            for (i = 0; i < def->nb_args; i++) {

                gen_args[i] = args[i];

            }

            args += def->nb_args;

            gen_args += def->nb_args;

            break;

        }

    }

    return gen_args;

}


static inline void tcg_out_sety(TCGContext *s, tcg_target_long val)

{

    if (val == 0 || val == -1)

        tcg_out32(s, WRY | INSN_IMM13(val));

    else

        fprintf(stderr, "unimplemented sety %ld\n", (long)val);

}


static void test_hba_spec(void)

{

    AHCIQState *ahci;

    ahci = ahci_boot();

    ahci_pci_enable(ahci);

    ahci_test_hba_spec(ahci);

    ahci_shutdown(ahci);

}


void pdu_free(V9fsPDU *pdu)

{

    if (pdu) {

        V9fsState *s = pdu->s;

        /*

         * Cancelled pdu are added back to the freelist

         * by flush request .

         */

        if (!pdu->cancelled) {

            QLIST_REMOVE(pdu, next);

            QLIST_INSERT_HEAD(&s->free_list, pdu, next);

        }

    }

}


static av_noinline void emulated_edge_mc_mmxext(uint8_t *buf, const uint8_t *src,

                                                ptrdiff_t buf_stride,

                                                ptrdiff_t src_stride,

                                                int block_w, int block_h,

                                                int src_x, int src_y, int w, int h)

{

    emulated_edge_mc(buf, src, buf_stride, src_stride, block_w, block_h,

                     src_x, src_y, w, h, vfixtbl_mmx, &ff_emu_edge_vvar_mmx,

                     hfixtbl_mmxext, &ff_emu_edge_hvar_mmxext);

}


static int token_is_operator(QObject *obj, char op)

{

    const char *val;

    if (token_get_type(obj) != JSON_OPERATOR) {

        return 0;

    }

    val = token_get_value(obj);

    return (val[0] == op) && (val[1] == 0);

}


static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,

                             const char *replaces,

                             int64_t speed, int64_t granularity,

                             int64_t buf_size,

                             BlockdevOnError on_source_error,

                             BlockdevOnError on_target_error,

                             BlockCompletionFunc *cb,

                             void *opaque, Error **errp,

                             const BlockJobDriver *driver,

                             bool is_none_mode, BlockDriverState *base)

{

    MirrorBlockJob *s;

    if (granularity == 0) {

        /* Choose the default granularity based on the target file's cluster

         * size, clamped between 4k and 64k.  */

        BlockDriverInfo bdi;

        if (bdrv_get_info(target, &bdi) >= 0 && bdi.cluster_size != 0) {

            granularity = MAX(4096, bdi.cluster_size);

            granularity = MIN(65536, granularity);

        } else {

            granularity = 65536;

        }

    }

    assert ((granularity & (granularity - 1)) == 0);

    if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||

         on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&

        !bdrv_iostatus_is_enabled(bs)) {

        error_set(errp, QERR_INVALID_PARAMETER, "on-source-error");

        return;

    }

    s = block_job_create(driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->replaces = g_strdup(replaces);

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->target = target;

    s->is_none_mode = is_none_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = MAX(buf_size, granularity);

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, errp);

    if (!s->dirty_bitmap) {

        return;

    }

    bdrv_set_enable_write_cache(s->target, true);

    bdrv_set_on_error(s->target, on_target_error, on_target_error);

    bdrv_iostatus_enable(s->target);

    s->common.co = qemu_coroutine_create(mirror_run);

    trace_mirror_start(bs, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


static void vnc_connect(VncDisplay *vd, QIOChannelSocket *sioc,

                        bool skipauth, bool websocket)

{

    VncState *vs = g_new0(VncState, 1);

    int i;

    vs->sioc = sioc;

    object_ref(OBJECT(vs->sioc));

    vs->ioc = QIO_CHANNEL(sioc);

    object_ref(OBJECT(vs->ioc));

    vs->vd = vd;

    buffer_init(&vs->input,          "vnc-input/%p", sioc);

    buffer_init(&vs->output,         "vnc-output/%p", sioc);

    buffer_init(&vs->jobs_buffer,    "vnc-jobs_buffer/%p", sioc);

    buffer_init(&vs->tight.tight,    "vnc-tight/%p", sioc);

    buffer_init(&vs->tight.zlib,     "vnc-tight-zlib/%p", sioc);

    buffer_init(&vs->tight.gradient, "vnc-tight-gradient/%p", sioc);

#ifdef CONFIG_VNC_JPEG

    buffer_init(&vs->tight.jpeg,     "vnc-tight-jpeg/%p", sioc);

#endif

#ifdef CONFIG_VNC_PNG

    buffer_init(&vs->tight.png,      "vnc-tight-png/%p", sioc);

#endif

    buffer_init(&vs->zlib.zlib,      "vnc-zlib/%p", sioc);

    buffer_init(&vs->zrle.zrle,      "vnc-zrle/%p", sioc);

    buffer_init(&vs->zrle.fb,        "vnc-zrle-fb/%p", sioc);

    buffer_init(&vs->zrle.zlib,      "vnc-zrle-zlib/%p", sioc);

    if (skipauth) {

	vs->auth = VNC_AUTH_NONE;

	vs->subauth = VNC_AUTH_INVALID;

    } else {

        if (websocket) {

            vs->auth = vd->ws_auth;

            vs->subauth = VNC_AUTH_INVALID;

        } else {

            vs->auth = vd->auth;

            vs->subauth = vd->subauth;

        }

    }

    VNC_DEBUG("Client sioc=%p ws=%d auth=%d subauth=%d\n",

              sioc, websocket, vs->auth, vs->subauth);

    vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));

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

        vs->lossy_rect[i] = g_new0(uint8_t, VNC_STAT_COLS);

    }

    VNC_DEBUG("New client on socket %p\n", vs->sioc);

    update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);

    qio_channel_set_blocking(vs->ioc, false, NULL);

    if (websocket) {

        vs->websocket = 1;

        if (vd->ws_tls) {

            vs->ioc_tag = qio_channel_add_watch(

                vs->ioc, G_IO_IN, vncws_tls_handshake_io, vs, NULL);

        } else {

            vs->ioc_tag = qio_channel_add_watch(

                vs->ioc, G_IO_IN, vncws_handshake_io, vs, NULL);

        }

    } else {

        vs->ioc_tag = qio_channel_add_watch(

            vs->ioc, G_IO_IN, vnc_client_io, vs, NULL);

    }

    vnc_client_cache_addr(vs);

    vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);

    vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);

    if (!vs->websocket) {

        vnc_init_state(vs);

    }

    if (vd->num_connecting > vd->connections_limit) {

        QTAILQ_FOREACH(vs, &vd->clients, next) {

            if (vs->share_mode == VNC_SHARE_MODE_CONNECTING) {

                vnc_disconnect_start(vs);

                return;

            }

        }

    }

}


static inline void tlb_reset_dirty_range(CPUTLBEntry *tlb_entry,

                                         unsigned long start, unsigned long length)

{

    unsigned long addr;

    if ((tlb_entry->addr_write & ~TARGET_PAGE_MASK) == io_mem_ram.ram_addr) {

        addr = (tlb_entry->addr_write & TARGET_PAGE_MASK) + tlb_entry->addend;

        if ((addr - start) < length) {

            tlb_entry->addr_write = (tlb_entry->addr_write & TARGET_PAGE_MASK) | TLB_NOTDIRTY;

        }

    }

}


static inline void gen_evmergehi(DisasContext *ctx)

{

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

#if defined(TARGET_PPC64)

    TCGv t0 = tcg_temp_new();

    TCGv t1 = tcg_temp_new();

    tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 32);

    tcg_gen_andi_tl(t1, cpu_gpr[rA(ctx->opcode)], 0xFFFFFFFF0000000ULL);

    tcg_gen_or_tl(cpu_gpr[rD(ctx->opcode)], t0, t1);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

#else

    tcg_gen_mov_i32(cpu_gpr[rD(ctx->opcode)], cpu_gprh[rB(ctx->opcode)]);

    tcg_gen_mov_i32(cpu_gprh[rD(ctx->opcode)], cpu_gprh[rA(ctx->opcode)]);

#endif

}


static void simple_dict(void)

{

    int i;

    struct {

        const char *encoded;

        LiteralQObject decoded;

    } test_cases[] = {

        {

            .encoded = "{\"foo\": 42, \"bar\": \"hello world\"}",

            .decoded = QLIT_QDICT(((LiteralQDictEntry[]){

                        { "foo", QLIT_QINT(42) },

                        { "bar", QLIT_QSTR("hello world") },

                        { }

                    })),

        }, {

            .encoded = "{}",

            .decoded = QLIT_QDICT(((LiteralQDictEntry[]){

                        { }

                    })),

        }, {

            .encoded = "{\"foo\": 43}",

            .decoded = QLIT_QDICT(((LiteralQDictEntry[]){

                        { "foo", QLIT_QINT(43) },

                        { }

                    })),

        },

        { }

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded);

        g_assert(obj != NULL);

        g_assert(qobject_type(obj) == QTYPE_QDICT);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        str = qobject_to_json(obj);

        qobject_decref(obj);

        obj = qobject_from_json(qstring_get_str(str));

        g_assert(obj != NULL);

        g_assert(qobject_type(obj) == QTYPE_QDICT);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        qobject_decref(obj);

        QDECREF(str);

    }

}


static int local_open2(FsContext *fs_ctx, V9fsPath *dir_path, const char *name,

                       int flags, FsCred *credp)

{

    char *path;

    int fd = -1;

    int err = -1;

    int serrno = 0;

    V9fsString fullname;

    char buffer[PATH_MAX];

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    path = fullname.data;

    /* Determine the security model */

    if (fs_ctx->fs_sm == SM_MAPPED) {

        fd = open(rpath(fs_ctx, path, buffer), flags, SM_LOCAL_MODE_BITS);

        if (fd == -1) {

            err = fd;

            goto out;

        }

        credp->fc_mode = credp->fc_mode|S_IFREG;

        /* Set cleint credentials in xattr */

        err = local_set_xattr(rpath(fs_ctx, path, buffer), credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if ((fs_ctx->fs_sm == SM_PASSTHROUGH) ||

               (fs_ctx->fs_sm == SM_NONE)) {

        fd = open(rpath(fs_ctx, path, buffer), flags, credp->fc_mode);

        if (fd == -1) {

            err = fd;

            goto out;

        }

        err = local_post_create_passthrough(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    }

    err = fd;

    goto out;

err_end:

    close(fd);

    remove(rpath(fs_ctx, path, buffer));

    errno = serrno;

out:

    v9fs_string_free(&fullname);

    return err;

}


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

{

    if (argc != 2) {

        help_cmd(argv[0]);

        return;

    }

    if (qemu_savevm(argv[1]) < 0)

        term_printf("I/O error when saving VM to '%s'\n", argv[1]);

}


static void evaluate_flags_writeback(uint32_t flags)

{

	int x;

	/* Extended arithmetics, leave the z flag alone.  */

	x = env->cc_x;

	if ((x || env->cc_op == CC_OP_ADDC)

	    && flags & Z_FLAG)

		env->cc_mask &= ~Z_FLAG;

	/* all insn clear the x-flag except setf or clrf.  */

	env->pregs[PR_CCS] &= ~(env->cc_mask | X_FLAG);

	flags &= env->cc_mask;

	env->pregs[PR_CCS] |= flags;

}


static int epzs_motion_search(MpegEncContext * s,

                             int *mx_ptr, int *my_ptr,

                             int P[5][2], int pred_x, int pred_y,

                             int xmin, int ymin, int xmax, int ymax, uint8_t * ref_picture)

{

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

    int d, dmin;

    UINT8 *new_pic, *old_pic;

    const int pic_stride= s->linesize;

    const int pic_xy= (s->mb_y*pic_stride + s->mb_x)*16;

    UINT16 *mv_penalty= s->mv_penalty[s->f_code] + MAX_MV; // f_code of the prev frame

    int quant= s->qscale; // qscale of the prev frame

    const int shift= 1+s->quarter_sample;

    new_pic = s->new_picture[0] + pic_xy;

    old_pic = ref_picture + pic_xy;

    dmin = pix_abs16x16(new_pic, old_pic, pic_stride);

    if(dmin<Z_THRESHOLD){

        *mx_ptr= 0;

        *my_ptr= 0;

//printf("Z");

        return dmin;

    }

    /* first line */

    if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line)) {

        CHECK_MV(P[1][0]>>shift, P[1][1]>>shift)

    }else{

        CHECK_MV(P[4][0]>>shift, P[4][1]>>shift)

        if(dmin<Z_THRESHOLD){

            *mx_ptr= P[4][0]>>shift;

            *my_ptr= P[4][1]>>shift;

//printf("M\n");

            return dmin;

        }

        CHECK_MV(P[1][0]>>shift, P[1][1]>>shift)

        CHECK_MV(P[2][0]>>shift, P[2][1]>>shift)

        CHECK_MV(P[3][0]>>shift, P[3][1]>>shift)

    }

    CHECK_MV(P[0][0]>>shift, P[0][1]>>shift)

//check(best[0],best[1],0, b0)

    if(s->me_method==ME_EPZS)

        dmin= small_diamond_search(s, best, dmin, new_pic, old_pic, pic_stride,

                                   pred_x, pred_y, mv_penalty, quant, xmin, ymin, xmax, ymax, shift);

    else

        dmin=         snake_search(s, best, dmin, new_pic, old_pic, pic_stride,

                                   pred_x, pred_y, mv_penalty, quant, xmin, ymin, xmax, ymax, shift);

//check(best[0],best[1],0, b1)

    *mx_ptr= best[0];

    *my_ptr= best[1];

//    printf("%d %d %d \n", best[0], best[1], dmin);

    return dmin;

}


static void qemu_laio_process_completion(struct qemu_laiocb *laiocb)

{

    int ret;

    ret = laiocb->ret;

    if (ret != -ECANCELED) {

        if (ret == laiocb->nbytes) {

            ret = 0;

        } else if (ret >= 0) {

            /* Short reads mean EOF, pad with zeros. */

            if (laiocb->is_read) {

                qemu_iovec_memset(laiocb->qiov, ret, 0,

                    laiocb->qiov->size - ret);

            } else {

                ret = -ENOSPC;

            }

        }

    }

    laiocb->ret = ret;

    if (laiocb->co) {

        qemu_coroutine_enter(laiocb->co);

    } else {

        laiocb->common.cb(laiocb->common.opaque, ret);

        qemu_aio_unref(laiocb);

    }

}


static void aio_epoll_disable(AioContext *ctx)

{

    ctx->epoll_available = false;

    if (!ctx->epoll_enabled) {

        return;

    }

    ctx->epoll_enabled = false;

    close(ctx->epollfd);

}


static void pc_machine_initfn(Object *obj)

{

    PCMachineState *pcms = PC_MACHINE(obj);

    object_property_add(obj, PC_MACHINE_MEMHP_REGION_SIZE, "int",

                        pc_machine_get_hotplug_memory_region_size,

                        NULL, NULL, NULL, &error_abort);

    pcms->max_ram_below_4g = 0xe0000000; /* 3.5G */

    object_property_add(obj, PC_MACHINE_MAX_RAM_BELOW_4G, "size",

                        pc_machine_get_max_ram_below_4g,

                        pc_machine_set_max_ram_below_4g,

                        NULL, NULL, &error_abort);

    object_property_set_description(obj, PC_MACHINE_MAX_RAM_BELOW_4G,

                                    "Maximum ram below the 4G boundary (32bit boundary)",

                                    &error_abort);

    pcms->smm = ON_OFF_AUTO_AUTO;

    object_property_add(obj, PC_MACHINE_SMM, "OnOffAuto",

                        pc_machine_get_smm,

                        pc_machine_set_smm,

                        NULL, NULL, &error_abort);

    object_property_set_description(obj, PC_MACHINE_SMM,

                                    "Enable SMM (pc & q35)",

                                    &error_abort);

    pcms->vmport = ON_OFF_AUTO_AUTO;

    object_property_add(obj, PC_MACHINE_VMPORT, "OnOffAuto",

                        pc_machine_get_vmport,

                        pc_machine_set_vmport,

                        NULL, NULL, &error_abort);

    object_property_set_description(obj, PC_MACHINE_VMPORT,

                                    "Enable vmport (pc & q35)",

                                    &error_abort);

    /* nvdimm is disabled on default. */

    pcms->acpi_nvdimm_state.is_enabled = false;

    object_property_add_bool(obj, PC_MACHINE_NVDIMM, pc_machine_get_nvdimm,

                             pc_machine_set_nvdimm, &error_abort);

}


static unsigned int dec_move_rs(DisasContext *dc)

{

	DIS(fprintf (logfile, "move $r%u, $s%u\n", dc->op1, dc->op2));

	cris_cc_mask(dc, 0);

	tcg_gen_helper_0_2(helper_movl_sreg_reg,

			   tcg_const_tl(dc->op2), tcg_const_tl(dc->op1));

	return 2;

}