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 the other copies are
       available through the doubly linked circular list. */
    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 (op == INDEX_op_call) {
            int nb_oargs = args[0] >> 16;
            int nb_iargs = args[0] & 0xffff;
            for (i = nb_oargs + 1; i < nb_oargs + nb_iargs + 1; i++) {
                if (temps[args[i]].state == TCG_TEMP_COPY) {
                    args[i] = find_better_copy(s, args[i]);
        } else {
            for (i = def->nb_oargs; i < def->nb_oargs + def->nb_iargs; i++) {
                if (temps[args[i]].state == TCG_TEMP_COPY) {
                    args[i] = find_better_copy(s, args[i]);
        /* For commutative operations make constant second argument */
        CASE_OP_32_64(add):
        CASE_OP_32_64(mul):
        CASE_OP_32_64(and):
        CASE_OP_32_64(or):
        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;
        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]);
        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]);
        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;
        /* Simplify expressions for "shift/rot r, 0, a => movi r, 0" */
        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) {
        /* Simplify expression for "op r, a, 0 => mov r, a" cases */
        CASE_OP_32_64(add):
        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):
            if (temps[args[1]].state == TCG_TEMP_CONST) {
                /* Proceed with possible constant folding. */
            if (temps[args[2]].state == TCG_TEMP_CONST
                && temps[args[2]].val == 0) {
                if (temps_are_copies(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(s, gen_args, args[0], args[1]);
        /* Simplify expression for "op r, a, 0 => movi r, 0" cases */
        CASE_OP_32_64(and):
        CASE_OP_32_64(mul):
            if ((temps[args[2]].state == TCG_TEMP_CONST
                && temps[args[2]].val == 0)) {
        /* Simplify expression for "op r, a, a => mov r, a" cases */
        CASE_OP_32_64(or):
        CASE_OP_32_64(and):
                if (temps_are_copies(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(s, gen_args, args[0], args[1]);
        /* 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. */
        CASE_OP_32_64(mov):
            if (temps_are_copies(args[0], args[1])) {
                args += 2;
                gen_opc_buf[op_index] = INDEX_op_nop;
            if (temps[args[1]].state != TCG_TEMP_CONST) {
                tcg_opt_gen_mov(s, gen_args, args[0], args[1]);
                args += 2;
            /* 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]);
            args += 2;
        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) {
                tmp = do_constant_folding(op, temps[args[1]].val, 0);
                tcg_opt_gen_movi(gen_args, args[0], tmp);
            } else {
                reset_temp(args[0]);
                gen_args[0] = args[0];
                gen_args[1] = args[1];
            args += 2;
        CASE_OP_32_64(add):
        CASE_OP_32_64(mul):
        CASE_OP_32_64(or):
        CASE_OP_32_64(and):
        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) {
                tmp = do_constant_folding(op, temps[args[1]].val,
                                          temps[args[2]].val);
                tcg_opt_gen_movi(gen_args, args[0], tmp);
            } else {
                reset_temp(args[0]);
                gen_args[0] = args[0];
                gen_args[1] = args[1];
                gen_args[2] = args[2];
                gen_args += 3;
        CASE_OP_32_64(setcond):
            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[3]);
                tcg_opt_gen_movi(gen_args, args[0], tmp);
            } else {
                reset_temp(args[0]);
                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;
        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]);
                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;
        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 (temps_are_copies(args[0], args[4-tmp])) {
                    gen_opc_buf[op_index] = INDEX_op_nop;
                } else if (temps[args[4-tmp]].state == TCG_TEMP_CONST) {
                    tcg_opt_gen_movi(gen_args, args[0], temps[args[4-tmp]].val);
                } else {
                    gen_opc_buf[op_index] = op_to_mov(op);
                    tcg_opt_gen_mov(s, gen_args, args[0], args[4-tmp]);
            } else {
                reset_temp(args[0]);
                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;
        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);
            for (i = 0; i < (args[0] >> 16); i++) {
                reset_temp(args[i + 1]);
            i = nb_call_args + 3;
            while (i) {
                *gen_args = *args;
                args++;
                gen_args++;
                i--;
            /* 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]);
            for (i = 0; i < def->nb_args; i++) {
                gen_args[i] = args[i];
            args += def->nb_args;
            gen_args += def->nb_args;
    return gen_args;


static void vnc_connect(VncDisplay *vd, int csock,

                        bool skipauth, bool websocket)

{

    VncState *vs = g_malloc0(sizeof(VncState));

    int i;

    vs->csock = csock;

    vs->vd = vd;

    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 sock=%d ws=%d auth=%d subauth=%d\n",

              csock, 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_malloc0(VNC_STAT_COLS * sizeof (uint8_t));

    }

    VNC_DEBUG("New client on socket %d\n", csock);

    update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);

    qemu_set_nonblock(vs->csock);

    if (websocket) {

        vs->websocket = 1;

        if (vd->ws_tls) {

            qemu_set_fd_handler(vs->csock, vncws_tls_handshake_io, NULL, vs);

        } else {

            qemu_set_fd_handler(vs->csock, vncws_handshake_read, NULL, vs);

        }

    } else

    {

        qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);

    }

    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 int ftp_current_dir(FTPContext *s)

{

    char *res = NULL, *start = NULL, *end = NULL;

    int i;

    const char *command = "PWD\r\n";

    const int pwd_codes[] = {257, 0};

    if (!ftp_send_command(s, command, pwd_codes, &res))

        goto fail;

    for (i = 0; res[i]; ++i) {

        if (res[i] == '"') {

            if (!start) {

                start = res + i + 1;

                continue;

            }

            end = res + i;

            break;

        }

    }

    if (!end)

        goto fail;

    if (end > res && end[-1] == '/') {

        end[-1] = '\0';

    } else

        *end = '\0';

    av_strlcpy(s->path, start, sizeof(s->path));

    av_free(res);

    return 0;

  fail:

    av_free(res);

    return AVERROR(EIO);

}


int qemu_opts_print(QemuOpts *opts, void *dummy)

{

    QemuOpt *opt;

    fprintf(stderr, "%s: %s:", opts->list->name,

            opts->id ? opts->id : "<noid>");

    TAILQ_FOREACH(opt, &opts->head, next) {

        fprintf(stderr, " %s=\"%s\"", opt->name, opt->str);

    }

    fprintf(stderr, "\n");

    return 0;

}


static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,

                                AVFrame *picture)

{

    int compno, reslevelno, bandno;

    int x, y;

    uint8_t *line;

    Jpeg2000T1Context t1;

    /* Loop on tile components */

    for (compno = 0; compno < s->ncomponents; compno++) {

        Jpeg2000Component *comp     = tile->comp + compno;

        Jpeg2000CodingStyle *codsty = tile->codsty + compno;

        /* Loop on resolution levels */

        for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {

            Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

            /* Loop on bands */

            for (bandno = 0; bandno < rlevel->nbands; bandno++) {

                int nb_precincts, precno;

                Jpeg2000Band *band = rlevel->band + bandno;

                int cblkno = 0, bandpos;

                bandpos = bandno + (reslevelno > 0);

                if (band->coord[0][0] == band->coord[0][1] ||

                    band->coord[1][0] == band->coord[1][1])

                    continue;

                nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;

                /* Loop on precincts */

                for (precno = 0; precno < nb_precincts; precno++) {

                    Jpeg2000Prec *prec = band->prec + precno;

                    /* Loop on codeblocks */

                    for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {

                        int x, y;

                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                        decode_cblk(s, codsty, &t1, cblk,

                                    cblk->coord[0][1] - cblk->coord[0][0],

                                    cblk->coord[1][1] - cblk->coord[1][0],

                                    bandpos);

                        x = cblk->coord[0][0];

                        y = cblk->coord[1][0];

                        if (codsty->transform == FF_DWT97)

                            dequantization_float(x, y, cblk, comp, &t1, band);

                        else

                            dequantization_int(x, y, cblk, comp, &t1, band);

                   } /* end cblk */

                } /*end prec */

            } /* end band */

        } /* end reslevel */

        /* inverse DWT */

        ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);

    } /*end comp */

    /* inverse MCT transformation */

    if (tile->codsty[0].mct)

        mct_decode(s, tile);

    if (s->cdef[0] < 0) {

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

            s->cdef[x] = x + 1;

        if ((s->ncomponents & 1) == 0)

            s->cdef[s->ncomponents-1] = 0;

    }

    if (s->precision <= 8) {

        for (compno = 0; compno < s->ncomponents; compno++) {

            Jpeg2000Component *comp = tile->comp + compno;

            Jpeg2000CodingStyle *codsty = tile->codsty + compno;

            float *datap = comp->f_data;

            int32_t *i_datap = comp->i_data;

            int cbps = s->cbps[compno];

            int w = tile->comp[compno].coord[0][1] - s->image_offset_x;

            int planar = !!picture->data[2];

            int pixelsize = planar ? 1 : s->ncomponents;

            int plane = 0;

            if (planar)

                plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);

            y    = tile->comp[compno].coord[1][0] - s->image_offset_y;

            line = picture->data[plane] + y * picture->linesize[plane];

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {

                uint8_t *dst;

                x   = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = line + x * pixelsize + compno*!planar;

                if (codsty->transform == FF_DWT97) {

                    for (; x < w; x += s->cdx[compno]) {

                        int val = lrintf(*datap) + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        *dst = val << (8 - cbps);

                        datap++;

                        dst += pixelsize;

                    }

                } else {

                    for (; x < w; x += s->cdx[compno]) {

                        int val = *i_datap + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        *dst = val << (8 - cbps);

                        i_datap++;

                        dst += pixelsize;

                    }

                }

                line += picture->linesize[plane];

            }

        }

    } else {

        for (compno = 0; compno < s->ncomponents; compno++) {

            Jpeg2000Component *comp = tile->comp + compno;

            Jpeg2000CodingStyle *codsty = tile->codsty + compno;

            float *datap = comp->f_data;

            int32_t *i_datap = comp->i_data;

            uint16_t *linel;

            int cbps = s->cbps[compno];

            int w = tile->comp[compno].coord[0][1] - s->image_offset_x;

            int planar = !!picture->data[2];

            int pixelsize = planar ? 1 : s->ncomponents;

            int plane = 0;

            if (planar)

                plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);

            y     = tile->comp[compno].coord[1][0] - s->image_offset_y;

            linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1);

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {

                uint16_t *dst;

                x   = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = linel + (x * pixelsize + compno*!planar);

                if (codsty->transform == FF_DWT97) {

                    for (; x < w; x += s-> cdx[compno]) {

                        int  val = lrintf(*datap) + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        /* align 12 bit values in little-endian mode */

                        *dst = val << (16 - cbps);

                        datap++;

                        dst += pixelsize;

                    }

                } else {

                    for (; x < w; x += s-> cdx[compno]) {

                        int val = *i_datap + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        /* align 12 bit values in little-endian mode */

                        *dst = val << (16 - cbps);

                        i_datap++;

                        dst += pixelsize;

                    }

                }

                linel += picture->linesize[plane] >> 1;

            }

        }

    }

    return 0;

}


void qemu_run_all_timers(void)

{

    alarm_timer->pending = 0;

    /* rearm timer, if not periodic */

    if (alarm_timer->expired) {

        alarm_timer->expired = 0;

        qemu_rearm_alarm_timer(alarm_timer);

    }

    /* vm time timers */

    qemu_run_timers(vm_clock);

    qemu_run_timers(rt_clock);

    qemu_run_timers(host_clock);

}


static struct XenDevice *xen_be_get_xendev(const char *type, int dom, int dev,

                                           struct XenDevOps *ops)

{

    struct XenDevice *xendev;

    xendev = xen_be_find_xendev(type, dom, dev);

    if (xendev) {

        return xendev;

    }

    /* init new xendev */

    xendev = g_malloc0(ops->size);

    xendev->type  = type;

    xendev->dom   = dom;

    xendev->dev   = dev;

    xendev->ops   = ops;

    snprintf(xendev->be, sizeof(xendev->be), "backend/%s/%d/%d",

             xendev->type, xendev->dom, xendev->dev);

    snprintf(xendev->name, sizeof(xendev->name), "%s-%d",

             xendev->type, xendev->dev);

    xendev->debug      = debug;

    xendev->local_port = -1;

    xendev->evtchndev = xen_xc_evtchn_open(NULL, 0);

    if (xendev->evtchndev == XC_HANDLER_INITIAL_VALUE) {

        xen_be_printf(NULL, 0, "can't open evtchn device\n");

        g_free(xendev);

        return NULL;

    }

    fcntl(xc_evtchn_fd(xendev->evtchndev), F_SETFD, FD_CLOEXEC);

    if (ops->flags & DEVOPS_FLAG_NEED_GNTDEV) {

        xendev->gnttabdev = xen_xc_gnttab_open(NULL, 0);

        if (xendev->gnttabdev == XC_HANDLER_INITIAL_VALUE) {

            xen_be_printf(NULL, 0, "can't open gnttab device\n");

            xc_evtchn_close(xendev->evtchndev);

            g_free(xendev);

            return NULL;

        }

    } else {

        xendev->gnttabdev = XC_HANDLER_INITIAL_VALUE;

    }

    QTAILQ_INSERT_TAIL(&xendevs, xendev, next);

    if (xendev->ops->alloc) {

        xendev->ops->alloc(xendev);

    }

    return xendev;

}


static void json_message_process_token(JSONLexer *lexer, QString *token, JSONTokenType type, int x, int y)

{

    JSONMessageParser *parser = container_of(lexer, JSONMessageParser, lexer);

    QDict *dict;

    if (type == JSON_OPERATOR) {

        switch (qstring_get_str(token)[0]) {

        case '{':

            parser->brace_count++;

            break;

        case '}':

            parser->brace_count--;

            break;

        case '[':

            parser->bracket_count++;

            break;

        case ']':

            parser->bracket_count--;

            break;

        default:

            break;

        }

    }

    dict = qdict_new();

    qdict_put(dict, "type", qint_from_int(type));

    QINCREF(token);

    qdict_put(dict, "token", token);

    qdict_put(dict, "x", qint_from_int(x));

    qdict_put(dict, "y", qint_from_int(y));

    parser->token_size += token->length;

    qlist_append(parser->tokens, dict);

    if (type == JSON_ERROR) {

        goto out_emit_bad;

    } else if (parser->brace_count < 0 ||

        parser->bracket_count < 0 ||

        (parser->brace_count == 0 &&

         parser->bracket_count == 0)) {

        goto out_emit;

    } else if (parser->token_size > MAX_TOKEN_SIZE ||

               parser->bracket_count + parser->brace_count > MAX_NESTING) {

        /* Security consideration, we limit total memory allocated per object

         * and the maximum recursion depth that a message can force.

         */

        goto out_emit_bad;

    }

    return;

out_emit_bad:

    /*

     * Clear out token list and tell the parser to emit an error

     * indication by passing it a NULL list

     */

    QDECREF(parser->tokens);

    parser->tokens = NULL;

out_emit:

    /* send current list of tokens to parser and reset tokenizer */

    parser->brace_count = 0;

    parser->bracket_count = 0;

    parser->emit(parser, parser->tokens);

    if (parser->tokens) {

        QDECREF(parser->tokens);

    }

    parser->tokens = qlist_new();

    parser->token_size = 0;

}


static void set_memory_options(uint64_t *ram_slots, ram_addr_t *maxram_size)

{

    uint64_t sz;

    const char *mem_str;

    const char *maxmem_str, *slots_str;

    const ram_addr_t default_ram_size = (ram_addr_t)DEFAULT_RAM_SIZE *

                                        1024 * 1024;

    QemuOpts *opts = qemu_find_opts_singleton("memory");

    sz = 0;

    mem_str = qemu_opt_get(opts, "size");

    if (mem_str) {

        if (!*mem_str) {

            error_report("missing 'size' option value");

            exit(EXIT_FAILURE);

        }

        sz = qemu_opt_get_size(opts, "size", ram_size);

        /* Fix up legacy suffix-less format */

        if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {

            uint64_t overflow_check = sz;

            sz <<= 20;

            if ((sz >> 20) != overflow_check) {

                error_report("too large 'size' option value");

                exit(EXIT_FAILURE);

            }

        }

    }

    /* backward compatibility behaviour for case "-m 0" */

    if (sz == 0) {

        sz = default_ram_size;

    }

    sz = QEMU_ALIGN_UP(sz, 8192);

    ram_size = sz;

    if (ram_size != sz) {

        error_report("ram size too large");

        exit(EXIT_FAILURE);

    }

    /* store value for the future use */

    qemu_opt_set_number(opts, "size", ram_size, &error_abort);

    *maxram_size = ram_size;

    maxmem_str = qemu_opt_get(opts, "maxmem");

    slots_str = qemu_opt_get(opts, "slots");

    if (maxmem_str && slots_str) {

        uint64_t slots;

        sz = qemu_opt_get_size(opts, "maxmem", 0);

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

        if (sz < ram_size) {

            error_report("invalid value of -m option maxmem: "

                         "maximum memory size (0x%" PRIx64 ") must be at least "

                         "the initial memory size (0x" RAM_ADDR_FMT ")",

                         sz, ram_size);

            exit(EXIT_FAILURE);

        } else if (sz > ram_size) {

            if (!slots) {

                error_report("invalid value of -m option: maxmem was "

                             "specified, but no hotplug slots were specified");

                exit(EXIT_FAILURE);

            }

        } else if (slots) {

            error_report("invalid value of -m option maxmem: "

                         "memory slots were specified but maximum memory size "

                         "(0x%" PRIx64 ") is equal to the initial memory size "

                         "(0x" RAM_ADDR_FMT ")", sz, ram_size);

            exit(EXIT_FAILURE);

        }

        *maxram_size = sz;

        *ram_slots = slots;

    } else if ((!maxmem_str && slots_str) ||

            (maxmem_str && !slots_str)) {

        error_report("invalid -m option value: missing "

                "'%s' option", slots_str ? "maxmem" : "slots");

        exit(EXIT_FAILURE);

    }

}


static void iscsi_refresh_limits(BlockDriverState *bs, Error **errp)

{

    /* We don't actually refresh here, but just return data queried in

     * iscsi_open(): iscsi targets don't change their limits. */

    IscsiLun *iscsilun = bs->opaque;

    uint64_t max_xfer_len = iscsilun->use_16_for_rw ? 0xffffffff : 0xffff;

    bs->request_alignment = iscsilun->block_size;

    if (iscsilun->bl.max_xfer_len) {

        max_xfer_len = MIN(max_xfer_len, iscsilun->bl.max_xfer_len);

    }

    if (max_xfer_len * iscsilun->block_size < INT_MAX) {

        bs->bl.max_transfer = max_xfer_len * iscsilun->block_size;

    }

    if (iscsilun->lbp.lbpu) {

        if (iscsilun->bl.max_unmap < 0xffffffff) {

            bs->bl.max_discard =

                sector_limits_lun2qemu(iscsilun->bl.max_unmap, iscsilun);

        }

        bs->bl.discard_alignment =

            sector_limits_lun2qemu(iscsilun->bl.opt_unmap_gran, iscsilun);

    } else {

        bs->bl.discard_alignment = iscsilun->block_size >> BDRV_SECTOR_BITS;

    }

    if (iscsilun->bl.max_ws_len < 0xffffffff / iscsilun->block_size) {

        bs->bl.max_pwrite_zeroes =

            iscsilun->bl.max_ws_len * iscsilun->block_size;

    }

    if (iscsilun->lbp.lbpws) {

        bs->bl.pwrite_zeroes_alignment =

            iscsilun->bl.opt_unmap_gran * iscsilun->block_size;

    } else {

        bs->bl.pwrite_zeroes_alignment = iscsilun->block_size;

    }

    if (iscsilun->bl.opt_xfer_len &&

        iscsilun->bl.opt_xfer_len < INT_MAX / iscsilun->block_size) {

        bs->bl.opt_transfer = pow2floor(iscsilun->bl.opt_xfer_len *

                                        iscsilun->block_size);

    }

}


static int kvm_set_mce(CPUState *env, struct kvm_x86_mce *m)

{

    return kvm_vcpu_ioctl(env, KVM_X86_SET_MCE, m);

}


void ide_atapi_cmd(IDEState *s)

{

    uint8_t *buf;

    buf = s->io_buffer;

#ifdef DEBUG_IDE_ATAPI

    {

        int i;

        printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));

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

            printf(" %02x", buf[i]);

        }

        printf("\n");

    }

#endif

    /*

     * If there's a UNIT_ATTENTION condition pending, only command flagged with

     * ALLOW_UA are allowed to complete. with other commands getting a CHECK

     * condition response unless a higher priority status, defined by the drive

     * here, is pending.

     */

    if (s->sense_key == UNIT_ATTENTION &&

        !(atapi_cmd_table[s->io_buffer[0]].flags & ALLOW_UA)) {

        ide_atapi_cmd_check_status(s);

        return;

    }

    /*

     * When a CD gets changed, we have to report an ejected state and

     * then a loaded state to guests so that they detect tray

     * open/close and media change events.  Guests that do not use

     * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close

     * states rely on this behavior.

     */

    if (!(atapi_cmd_table[s->io_buffer[0]].flags & ALLOW_UA) &&

        !s->tray_open && bdrv_is_inserted(s->bs) && s->cdrom_changed) {

        if (s->cdrom_changed == 1) {

            ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);

            s->cdrom_changed = 2;

        } else {

            ide_atapi_cmd_error(s, UNIT_ATTENTION, ASC_MEDIUM_MAY_HAVE_CHANGED);

            s->cdrom_changed = 0;

        }

        return;

    }

    /* Report a Not Ready condition if appropriate for the command */

    if ((atapi_cmd_table[s->io_buffer[0]].flags & CHECK_READY) &&

        (!media_present(s) || !bdrv_is_inserted(s->bs)))

    {

        ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);

        return;

    }

    /* Execute the command */

    if (atapi_cmd_table[s->io_buffer[0]].handler) {

        atapi_cmd_table[s->io_buffer[0]].handler(s, buf);

        return;

    }

    ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_ILLEGAL_OPCODE);

}


void ff_hevc_luma_mv_merge_mode(HEVCContext *s, int x0, int y0, int nPbW,

                                int nPbH, int log2_cb_size, int part_idx,

                                int merge_idx, MvField *mv)

{

    int singleMCLFlag = 0;

    int nCS = 1 << log2_cb_size;

    LOCAL_ALIGNED(4, MvField, mergecand_list, [MRG_MAX_NUM_CANDS]);

    int nPbW2 = nPbW;

    int nPbH2 = nPbH;

    HEVCLocalContext *lc = &s->HEVClc;

    memset(mergecand_list, 0, MRG_MAX_NUM_CANDS * sizeof(*mergecand_list));

    if (s->pps->log2_parallel_merge_level > 2 && nCS == 8) {

        singleMCLFlag = 1;

        x0            = lc->cu.x;

        y0            = lc->cu.y;

        nPbW          = nCS;

        nPbH          = nCS;

        part_idx      = 0;

    }

    ff_hevc_set_neighbour_available(s, x0, y0, nPbW, nPbH);

    derive_spatial_merge_candidates(s, x0, y0, nPbW, nPbH, log2_cb_size,

                                    singleMCLFlag, part_idx,

                                    merge_idx, mergecand_list);

    if (mergecand_list[merge_idx].pred_flag[0] == 1 &&

        mergecand_list[merge_idx].pred_flag[1] == 1 &&

        (nPbW2 + nPbH2) == 12) {

        mergecand_list[merge_idx].ref_idx[1]   = -1;

        mergecand_list[merge_idx].pred_flag[1] = 0;

    }

    *mv = mergecand_list[merge_idx];

}


int s390_cpu_write_elf64_note(WriteCoreDumpFunction f, CPUState *cs,

                              int cpuid, void *opaque)

{

    S390CPU *cpu = S390_CPU(cs);

    return s390x_write_all_elf64_notes("CORE", f, cpu, cpuid, opaque);

}


static void encode_clnpass(Jpeg2000T1Context *t1, int width, int height, int bandno, int *nmsedec, int bpno)

{

    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);

    for (y0 = 0; y0 < height; y0 += 4)

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

            if (y0 + 3 < height && !(

            (t1->flags[y0+1][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||

            (t1->flags[y0+2][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||

            (t1->flags[y0+3][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||

            (t1->flags[y0+4][x+1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG))))

            {

                // aggregation mode

                int rlen;

                for (rlen = 0; rlen < 4; rlen++)

                    if (t1->data[y0+rlen][x] & mask)

                        break;

                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL, rlen != 4);

                if (rlen == 4)

                    continue;

                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen >> 1);

                ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI, rlen & 1);

                for (y = y0 + rlen; y < y0 + 4; y++){

                    if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){

                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1], bandno);

                        if (y > y0 + rlen)

                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);

                        if (t1->data[y][x] & mask){ // newly significant

                            int xorbit;

                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);

                            *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);

                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);

                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[y+1][x+1] >> 15);

                        }

                    }

                    t1->flags[y+1][x+1] &= ~JPEG2000_T1_VIS;

                }

            } else{

                for (y = y0; y < y0 + 4 && y < height; y++){

                    if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))){

                        int ctxno = ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1], bandno);

                        ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);

                        if (t1->data[y][x] & mask){ // newly significant

                            int xorbit;

                            int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);

                            *nmsedec += getnmsedec_sig(t1->data[y][x], bpno + NMSEDEC_FRACBITS);

                            ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, (t1->flags[y+1][x+1] >> 15) ^ xorbit);

                            ff_jpeg2000_set_significance(t1, x, y, t1->flags[y+1][x+1] >> 15);

                        }

                    }

                    t1->flags[y+1][x+1] &= ~JPEG2000_T1_VIS;

                }

            }

        }

}


static int ppc_hash64_pte_update_flags(struct mmu_ctx_hash64 *ctx,

                                       target_ulong *pte1p,

                                       int ret, int rw)

{

    int store = 0;

    /* Update page flags */

    if (!(*pte1p & HPTE64_R_R)) {

        /* Update accessed flag */

        *pte1p |= HPTE64_R_R;

        store = 1;

    }

    if (!(*pte1p & HPTE64_R_C)) {

        if (rw == 1 && ret == 0) {

            /* Update changed flag */

            *pte1p |= HPTE64_R_C;

            store = 1;

        } else {

            /* Force page fault for first write access */

            ctx->prot &= ~PAGE_WRITE;

        }

    }

    return store;

}


BlockAIOCB *dma_bdrv_write(BlockDriverState *bs,

                           QEMUSGList *sg, uint64_t sector,

                           void (*cb)(void *opaque, int ret), void *opaque)

{

    return dma_bdrv_io(bs, sg, sector, bdrv_aio_writev, cb, opaque,

                       DMA_DIRECTION_TO_DEVICE);

}


static int discard_single_l2(BlockDriverState *bs, uint64_t offset,

    unsigned int nb_clusters, enum qcow2_discard_type type, bool full_discard)

{

    BDRVQcow2State *s = bs->opaque;

    uint64_t *l2_table;

    int l2_index;

    int ret;

    int i;

    ret = get_cluster_table(bs, offset, &l2_table, &l2_index);

    if (ret < 0) {

        return ret;

    }

    /* Limit nb_clusters to one L2 table */

    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);

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

        uint64_t old_l2_entry;

        old_l2_entry = be64_to_cpu(l2_table[l2_index + i]);

        /*

         * If full_discard is false, make sure that a discarded area reads back

         * as zeroes for v3 images (we cannot do it for v2 without actually

         * writing a zero-filled buffer). We can skip the operation if the

         * cluster is already marked as zero, or if it's unallocated and we

         * don't have a backing file.

         *

         * TODO We might want to use bdrv_get_block_status(bs) here, but we're

         * holding s->lock, so that doesn't work today.

         *

         * If full_discard is true, the sector should not read back as zeroes,

         * but rather fall through to the backing file.

         */

        switch (qcow2_get_cluster_type(old_l2_entry)) {

            case QCOW2_CLUSTER_UNALLOCATED:

                if (full_discard || !bs->backing_hd) {

                    continue;

                }

                break;

            case QCOW2_CLUSTER_ZERO:

                if (!full_discard) {

                    continue;

                }

                break;

            case QCOW2_CLUSTER_NORMAL:

            case QCOW2_CLUSTER_COMPRESSED:

                break;

            default:

                abort();

        }

        /* First remove L2 entries */

        qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);

        if (!full_discard && s->qcow_version >= 3) {

            l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);

        } else {

            l2_table[l2_index + i] = cpu_to_be64(0);

        }

        /* Then decrease the refcount */

        qcow2_free_any_clusters(bs, old_l2_entry, 1, type);

    }

    qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);

    return nb_clusters;

}


static int64_t qemu_archipelago_getlength(BlockDriverState *bs)

{

    int64_t ret;

    BDRVArchipelagoState *s = bs->opaque;

    ret = archipelago_volume_info(s);

    return ret;

}


static void rtas_ibm_set_eeh_option(PowerPCCPU *cpu,

                                    sPAPRMachineState *spapr,

                                    uint32_t token, uint32_t nargs,

                                    target_ulong args, uint32_t nret,

                                    target_ulong rets)

{

    sPAPRPHBState *sphb;

    sPAPRPHBClass *spc;

    PCIDevice *pdev;

    uint32_t addr, option;

    uint64_t buid;

    int ret;

    if ((nargs != 4) || (nret != 1)) {

        goto param_error_exit;

    }

    buid = rtas_ldq(args, 1);

    addr = rtas_ld(args, 0);

    option = rtas_ld(args, 3);

    sphb = spapr_pci_find_phb(spapr, buid);

    if (!sphb) {

        goto param_error_exit;

    }

    pdev = pci_find_device(PCI_HOST_BRIDGE(sphb)->bus,

                           (addr >> 16) & 0xFF, (addr >> 8) & 0xFF);

    if (!pdev || !object_dynamic_cast(OBJECT(pdev), "vfio-pci")) {

        goto param_error_exit;

    }

    spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);

    if (!spc->eeh_set_option) {

        goto param_error_exit;

    }

    ret = spc->eeh_set_option(sphb, addr, option);

    rtas_st(rets, 0, ret);

    return;

param_error_exit:

    rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

}


int qemu_acl_remove(qemu_acl *acl,

                    const char *match)

{

    qemu_acl_entry *entry;

    int i = 0;

    TAILQ_FOREACH(entry, &acl->entries, next) {

        i++;

        if (strcmp(entry->match, match) == 0) {

            TAILQ_REMOVE(&acl->entries, entry, next);

            return i;

        }

    }

    return -1;

}


static void ac97_initfn (PCIDevice *dev)

{

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

    AC97LinkState *s = &d->ac97;

    uint8_t *c = d->dev.config;

    s->pci_dev = &d->dev;

    pci_config_set_vendor_id (c, PCI_VENDOR_ID_INTEL); /* ro */

    pci_config_set_device_id (c, PCI_DEVICE_ID_INTEL_82801AA_5); /* ro */

    c[0x04] = 0x00;      /* pcicmd pci command rw, ro */

    c[0x05] = 0x00;

    c[0x06] = 0x80;      /* pcists pci status rwc, ro */

    c[0x07] = 0x02;

    c[0x08] = 0x01;      /* rid revision ro */

    c[0x09] = 0x00;      /* pi programming interface ro */

    pci_config_set_class (c, PCI_CLASS_MULTIMEDIA_AUDIO); /* ro */

    c[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL; /* headtyp header type ro */

    c[0x10] = 0x01;      /* nabmar native audio mixer base

                            address rw */

    c[0x11] = 0x00;

    c[0x12] = 0x00;

    c[0x13] = 0x00;

    c[0x14] = 0x01;      /* nabmbar native audio bus mastering

                            base address rw */

    c[0x15] = 0x00;

    c[0x16] = 0x00;

    c[0x17] = 0x00;

    c[0x2c] = 0x86;      /* svid subsystem vendor id rwo */

    c[0x2d] = 0x80;

    c[0x2e] = 0x00;      /* sid subsystem id rwo */

    c[0x2f] = 0x00;

    c[0x3c] = 0x00;      /* intr_ln interrupt line rw */

    c[0x3d] = 0x01;      /* intr_pn interrupt pin ro */

    pci_register_bar (&d->dev, 0, 256 * 4, PCI_ADDRESS_SPACE_IO, ac97_map);

    pci_register_bar (&d->dev, 1, 64 * 4, PCI_ADDRESS_SPACE_IO, ac97_map);

    register_savevm ("ac97", 0, 2, ac97_save, ac97_load, s);

    qemu_register_reset (ac97_on_reset, s);

    AUD_register_card ("ac97", &s->card);

    ac97_on_reset (s);

}


static int cook_parse(AVCodecParserContext *s1, AVCodecContext *avctx,

                      const uint8_t **poutbuf, int *poutbuf_size,

                      const uint8_t *buf, int buf_size)

{

    CookParseContext *s = s1->priv_data;

    if (s->duration)

        s1->duration = s->duration;

    else if (avctx->extradata && avctx->extradata_size >= 8 && avctx->channels)

        s->duration = AV_RB16(avctx->extradata + 4) / avctx->channels;

    /* always return the full packet. this parser isn't doing any splitting or

       combining, only setting packet duration */

    *poutbuf      = buf;

    *poutbuf_size = buf_size;

    return buf_size;

}


static void add_codec(FFServerStream *stream, AVCodecContext *av,

                      FFServerConfig *config)

{

    AVStream *st;

    AVDictionary **opts, *recommended = NULL;

    char *enc_config;

    if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))

        return;

    opts = av->codec_type == AVMEDIA_TYPE_AUDIO ?

           &config->audio_opts : &config->video_opts;

    av_dict_copy(&recommended, *opts, 0);

    av_opt_set_dict2(av->priv_data, opts, AV_OPT_SEARCH_CHILDREN);

    av_opt_set_dict2(av, opts, AV_OPT_SEARCH_CHILDREN);

    if (av_dict_count(*opts))

        av_log(NULL, AV_LOG_WARNING,

               "Something is wrong, %d options are not set!\n", av_dict_count(*opts));

    if (config->stream_use_defaults) {

    //TODO: reident

    /* compute default parameters */

    switch(av->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        if (av->bit_rate == 0) {

            av->bit_rate = 64000;

            av_dict_set_int(&recommended, "ab", av->bit_rate, 0);

        }

        if (av->sample_rate == 0) {

            av->sample_rate = 22050;

            av_dict_set_int(&recommended, "ar", av->sample_rate, 0);

        }

        if (av->channels == 0) {

            av->channels = 1;

            av_dict_set_int(&recommended, "ac", av->channels, 0);

        }

        break;

    case AVMEDIA_TYPE_VIDEO:

        if (av->bit_rate == 0) {

            av->bit_rate = 64000;

            av_dict_set_int(&recommended, "b", av->bit_rate, 0);

        }

        if (av->time_base.num == 0){

            av->time_base.den = 5;

            av->time_base.num = 1;

            av_dict_set(&recommended, "time_base", "1/5", 0);

        }

        if (av->width == 0 || av->height == 0) {

            av->width = 160;

            av->height = 128;

            av_dict_set(&recommended, "video_size", "160x128", 0);

        }

        /* Bitrate tolerance is less for streaming */

        if (av->bit_rate_tolerance == 0) {

            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,

                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);

            av_dict_set_int(&recommended, "bt", av->bit_rate_tolerance, 0);

        }

        if (!av->rc_eq) {

            av->rc_eq = av_strdup("tex^qComp");

            av_dict_set(&recommended, "rc_eq", "tex^qComp", 0);

        }

        if (!av->rc_max_rate) {

            av->rc_max_rate = av->bit_rate * 2;

            av_dict_set_int(&recommended, "maxrate", av->rc_max_rate, 0);

        }

        if (av->rc_max_rate && !av->rc_buffer_size) {

            av->rc_buffer_size = av->rc_max_rate;

            av_dict_set_int(&recommended, "bufsize", av->rc_buffer_size, 0);

        }

        break;

    default:

        abort();

    }

    } else {

        switch(av->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            if (av->bit_rate == 0)

                report_config_error(config->filename, config->line_num, AV_LOG_ERROR,

                                    &config->errors, "audio bit rate is not set\n");

            if (av->sample_rate == 0)

                report_config_error(config->filename, config->line_num, AV_LOG_ERROR,

                                    &config->errors, "audio sample rate is not set\n");

            break;

        case AVMEDIA_TYPE_VIDEO:

            if (av->width == 0 || av->height == 0)

                report_config_error(config->filename, config->line_num, AV_LOG_ERROR,

                                    &config->errors, "video size is not set\n");

            break;

        default:

            av_assert0(0);

        }

    }

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        return;

    av_dict_get_string(recommended, &enc_config, '=', ',');

    av_dict_free(&recommended);

    av_stream_set_recommended_encoder_configuration(st, enc_config);

    st->codec = av;

    stream->streams[stream->nb_streams++] = st;

}


static void qmp_output_end_struct(Visitor *v, Error **errp)

{

    QmpOutputVisitor *qov = to_qov(v);

    QObject *value = qmp_output_pop(qov);

    assert(qobject_type(value) == QTYPE_QDICT);

}


void compute_images_mse_16bit(PSNRContext *s,

                        const uint8_t *main_data[4], const int main_linesizes[4],

                        const uint8_t *ref_data[4], const int ref_linesizes[4],

                        int w, int h, double mse[4])

{

    int i, c, j;

    for (c = 0; c < s->nb_components; c++) {

        const int outw = s->planewidth[c];

        const int outh = s->planeheight[c];

        const uint16_t *main_line = (uint16_t *)main_data[c];

        const uint16_t *ref_line = (uint16_t *)ref_data[c];

        const int ref_linesize = ref_linesizes[c] / 2;

        const int main_linesize = main_linesizes[c] / 2;

        uint64_t m = 0;

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

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

                m += pow2(main_line[j] - ref_line[j]);

            ref_line += ref_linesize;

            main_line += main_linesize;

        }

        mse[c] = m / (double)(outw * outh);

    }

}


putsum(uint8_t *data, uint32_t n, uint32_t sloc, uint32_t css, uint32_t cse)

{

    uint32_t sum;

    if (cse && cse < n)

        n = cse + 1;

    if (sloc < n-1) {

        sum = net_checksum_add(n-css, data+css);

        stw_be_p(data + sloc, net_checksum_finish(sum));

    }

}


uint32_t HELPER(clcle)(CPUS390XState *env, uint32_t r1, uint64_t a2,

                       uint32_t r3)

{

    uintptr_t ra = GETPC();

    uint64_t destlen = get_length(env, r1 + 1);

    uint64_t dest = get_address(env, r1);

    uint64_t srclen = get_length(env, r3 + 1);

    uint64_t src = get_address(env, r3);

    uint8_t pad = a2 & 0xff;

    uint32_t cc = 0;

    if (!(destlen || srclen)) {

        return cc;

    }

    if (srclen > destlen) {

        srclen = destlen;

    }

    for (; destlen || srclen; src++, dest++, destlen--, srclen--) {

        uint8_t v1 = srclen ? cpu_ldub_data_ra(env, src, ra) : pad;

        uint8_t v2 = destlen ? cpu_ldub_data_ra(env, dest, ra) : pad;

        if (v1 != v2) {

            cc = (v1 < v2) ? 1 : 2;

            break;

        }

    }

    set_length(env, r1 + 1, destlen);

    /* can't use srclen here, we trunc'ed it */

    set_length(env, r3 + 1, env->regs[r3 + 1] - src - env->regs[r3]);

    set_address(env, r1, dest);

    set_address(env, r3, src);

    return cc;

}


void *bios_linker_loader_cleanup(GArray *linker)

{

    return g_array_free(linker, false);

}


const ppc_hash_pte64_t *ppc_hash64_map_hptes(PowerPCCPU *cpu,

                                             hwaddr ptex, int n)

{

    ppc_hash_pte64_t *hptes = NULL;

    hwaddr pte_offset = ptex * HASH_PTE_SIZE_64;

    if (cpu->env.external_htab == MMU_HASH64_KVM_MANAGED_HPT) {

        /*

         * HTAB is controlled by KVM. Fetch into temporary buffer

         */

        hptes = g_malloc(HASH_PTEG_SIZE_64);

        kvmppc_read_hptes(hptes, ptex, n);

    } else if (cpu->env.external_htab) {

        /*

         * HTAB is controlled by QEMU. Just point to the internally

         * accessible PTEG.

         */

        hptes = (ppc_hash_pte64_t *)(cpu->env.external_htab + pte_offset);

    } else if (cpu->env.htab_base) {

        hwaddr plen = n * HASH_PTE_SIZE_64;

        hptes = address_space_map(CPU(cpu)->as, cpu->env.htab_base + pte_offset,

                                 &plen, false);

        if (plen < (n * HASH_PTE_SIZE_64)) {

            hw_error("%s: Unable to map all requested HPTEs\n", __func__);

        }

    }

    return hptes;

}


static inline bool regime_translation_disabled(CPUARMState *env,

                                               ARMMMUIdx mmu_idx)

{

    if (arm_feature(env, ARM_FEATURE_M)) {

        switch (env->v7m.mpu_ctrl &

                (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {

        case R_V7M_MPU_CTRL_ENABLE_MASK:

            /* Enabled, but not for HardFault and NMI */

            return mmu_idx == ARMMMUIdx_MNegPri ||

                mmu_idx == ARMMMUIdx_MSNegPri;

        case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:

            /* Enabled for all cases */

            return false;

        case 0:

        default:

            /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but

             * we warned about that in armv7m_nvic.c when the guest set it.

             */

            return true;

        }

    }

    if (mmu_idx == ARMMMUIdx_S2NS) {

        return (env->cp15.hcr_el2 & HCR_VM) == 0;

    }

    return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;

}


static void build_processor_devices(Aml *sb_scope, unsigned acpi_cpus,

                                    AcpiCpuInfo *cpu, AcpiPmInfo *pm)

{

    int i;

    Aml *dev;

    Aml *crs;

    Aml *pkg;

    Aml *field;

    Aml *ifctx;

    Aml *method;

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

     * inclusive, for VCPU hotplug. */

    QEMU_BUILD_BUG_ON(ACPI_CPU_HOTPLUG_ID_LIMIT > 256);

    g_assert(acpi_cpus <= ACPI_CPU_HOTPLUG_ID_LIMIT);

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

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

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

    aml_append(dev,

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

    );

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

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

    crs = aml_resource_template();

    aml_append(crs,

        aml_io(AML_DECODE16, pm->cpu_hp_io_base, pm->cpu_hp_io_base, 1,

               pm->cpu_hp_io_len)

    );

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

    aml_append(sb_scope, dev);

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

    aml_append(sb_scope, aml_operation_region(

        "PRST", AML_SYSTEM_IO, aml_int(pm->cpu_hp_io_base), pm->cpu_hp_io_len));

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

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

    aml_append(sb_scope, field);

    /* build Processor object for each processor */

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

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

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

        aml_append(method,

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

        aml_append(dev, method);

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

        aml_append(method,

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

        aml_append(dev, method);

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

        aml_append(method,

            aml_return(aml_call2(CPU_EJECT_METHOD, aml_int(i), aml_arg(0)))

        );

        aml_append(dev, method);

        aml_append(sb_scope, dev);

    }

    /* build this code:

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

     */

    /* Arg0 = Processor ID = APIC ID */

    method = aml_method(AML_NOTIFY_METHOD, 2, AML_NOTSERIALIZED);

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

        ifctx = aml_if(aml_equal(aml_arg(0), aml_int(i)));

        aml_append(ifctx,

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

        );

        aml_append(method, ifctx);

    }

    aml_append(sb_scope, method);

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

     *

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

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

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

     * VarPackageOp is used.

     */

    pkg = acpi_cpus <= 255 ? aml_package(acpi_cpus) :

                             aml_varpackage(acpi_cpus);

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

        uint8_t b = test_bit(i, cpu->found_cpus) ? 0x01 : 0x00;

        aml_append(pkg, aml_int(b));

    }

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

}


e1000_mmio_read(void *opaque, target_phys_addr_t addr, unsigned size)

{

    E1000State *s = opaque;

    unsigned int index = (addr & 0x1ffff) >> 2;

    if (index < NREADOPS && macreg_readops[index])

    {

        return macreg_readops[index](s, index);

    }

    DBGOUT(UNKNOWN, "MMIO unknown read addr=0x%08x\n", index<<2);

    return 0;

}


static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)

{

    uint32_t len;

    if (ccid_card_status(s) != ICC_STATUS_PRESENT_ACTIVE) {

        DPRINTF(s, 1,

                "usb-ccid: not sending apdu to client, no card connected\n");

        ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);

        return;

    }

    len = le32_to_cpu(recv->hdr.dwLength);

    DPRINTF(s, 1, "%s: seq %d, len %d\n", __func__,

                recv->hdr.bSeq, len);

    ccid_add_pending_answer(s, (CCID_Header *)recv);

    if (s->card) {

        ccid_card_apdu_from_guest(s->card, recv->abData, len);

    } else {

        DPRINTF(s, D_WARN, "warning: discarded apdu\n");

    }

}


void ff_h264_pred_init_x86(H264PredContext *h, int codec_id)

{

    mm_flags = mm_support();

#if HAVE_YASM

    if (mm_flags & FF_MM_MMX) {

        h->pred16x16[VERT_PRED8x8] = ff_pred16x16_vertical_mmx;

        h->pred16x16[HOR_PRED8x8 ] = ff_pred16x16_horizontal_mmx;

        h->pred8x8  [VERT_PRED8x8] = ff_pred8x8_vertical_mmx;

        h->pred8x8  [HOR_PRED8x8 ] = ff_pred8x8_horizontal_mmx;

        if (codec_id == CODEC_ID_VP8) {

            h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_tm_vp8_mmx;

            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_mmx;

            h->pred4x4  [TM_VP8_PRED  ] = ff_pred4x4_tm_vp8_mmx;

        }

    }

    if (mm_flags & FF_MM_MMX2) {

        h->pred16x16[HOR_PRED8x8 ] = ff_pred16x16_horizontal_mmxext;

        h->pred16x16[DC_PRED8x8  ] = ff_pred16x16_dc_mmxext;

        h->pred8x8  [HOR_PRED8x8 ] = ff_pred8x8_horizontal_mmxext;

        h->pred4x4  [DC_PRED     ] = ff_pred4x4_dc_mmxext;

        if (codec_id == CODEC_ID_VP8) {

            h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_tm_vp8_mmxext;

            h->pred8x8  [DC_PRED8x8   ] = ff_pred8x8_dc_rv40_mmxext;

            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_mmxext;

            h->pred4x4  [TM_VP8_PRED  ] = ff_pred4x4_tm_vp8_mmxext;

            h->pred4x4  [VERT_PRED    ] = ff_pred4x4_vertical_vp8_mmxext;

        }

    }

    if (mm_flags & FF_MM_SSE) {

        h->pred16x16[VERT_PRED8x8] = ff_pred16x16_vertical_sse;

        h->pred16x16[DC_PRED8x8  ] = ff_pred16x16_dc_sse;

    }

    if (mm_flags & FF_MM_SSE2) {

        h->pred16x16[DC_PRED8x8  ] = ff_pred16x16_dc_sse2;

        if (codec_id == CODEC_ID_VP8) {

            h->pred16x16[PLANE_PRED8x8] = ff_pred16x16_tm_vp8_sse2;

            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_sse2;

        }

    }

    if (mm_flags & FF_MM_SSSE3) {

        h->pred16x16[HOR_PRED8x8 ] = ff_pred16x16_horizontal_ssse3;

        h->pred16x16[DC_PRED8x8  ] = ff_pred16x16_dc_ssse3;

        h->pred8x8  [HOR_PRED8x8 ] = ff_pred8x8_horizontal_ssse3;

        if (codec_id == CODEC_ID_VP8) {

            h->pred8x8  [PLANE_PRED8x8] = ff_pred8x8_tm_vp8_ssse3;

            h->pred4x4  [TM_VP8_PRED  ] = ff_pred4x4_tm_vp8_ssse3;

        }

    }

#endif

}


static inline abi_long target_to_host_timespec(struct timespec *host_ts,

                                               abi_ulong target_addr)

{

    struct target_timespec *target_ts;

    if (!lock_user_struct(VERIFY_READ, target_ts, target_addr, 1))

        return -TARGET_EFAULT;

    host_ts->tv_sec = tswapal(target_ts->tv_sec);

    host_ts->tv_nsec = tswapal(target_ts->tv_nsec);

    unlock_user_struct(target_ts, target_addr, 0);

    return 0;

}


void DMA_init(int high_page_enable, qemu_irq *cpu_request_exit)

{

}


static void decode_delta_l(uint8_t *dst,

                           const uint8_t *buf, const uint8_t *buf_end,

                           int w, int flag, int bpp, int dst_size)

{

    GetByteContext off0, off1, dgb, ogb;

    PutByteContext pb;

    unsigned poff0, poff1;

    int i, k, dstpitch;

    int planepitch_byte = (w + 7) / 8;

    int planepitch = ((w + 15) / 16) * 2;

    int pitch = planepitch * bpp;

    if (buf_end - buf <= 64)

        return;

    bytestream2_init(&off0, buf, buf_end - buf);

    bytestream2_init(&off1, buf + 32, buf_end - (buf + 32));

    bytestream2_init_writer(&pb, dst, dst_size);

    dstpitch = flag ? (((w + 7) / 8) * bpp): 2;

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

        poff0 = bytestream2_get_be32(&off0);

        poff1 = bytestream2_get_be32(&off1);

        if (!poff0)

            continue;

        if (2LL * poff0 >= buf_end - buf)

            return;

        if (2LL * poff1 >= buf_end - buf)

            return;

        bytestream2_init(&dgb, buf + 2 * poff0, buf_end - (buf + 2 * poff0));

        bytestream2_init(&ogb, buf + 2 * poff1, buf_end - (buf + 2 * poff1));

        while ((bytestream2_peek_be16(&ogb)) != 0xFFFF) {

            uint32_t offset = bytestream2_get_be16(&ogb);

            int16_t cnt = bytestream2_get_be16(&ogb);

            uint16_t data;

            offset = ((2 * offset) / planepitch_byte) * pitch + ((2 * offset) % planepitch_byte) + k * planepitch;

            if (cnt < 0) {

                bytestream2_seek_p(&pb, offset, SEEK_SET);

                cnt = -cnt;

                data = bytestream2_get_be16(&dgb);

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

                    bytestream2_put_be16(&pb, data);

                    bytestream2_skip_p(&pb, dstpitch - 2);

                }

            } else {

                bytestream2_seek_p(&pb, offset, SEEK_SET);

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

                    data = bytestream2_get_be16(&dgb);

                    bytestream2_put_be16(&pb, data);

                    bytestream2_skip_p(&pb, dstpitch - 2);

                }

            }

        }

    }

}


static void intel_hda_mmio_writeb(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    IntelHDAState *d = opaque;

    const IntelHDAReg *reg = intel_hda_reg_find(d, addr);

    intel_hda_reg_write(d, reg, val, 0xff);

}


void serial_realize_core(SerialState *s, Error **errp)

{

    if (!qemu_chr_fe_backend_connected(&s->chr)) {

        error_setg(errp, "Can't create serial device, empty char device");

        return;

    }

    s->modem_status_poll = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) serial_update_msl, s);

    s->fifo_timeout_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, (QEMUTimerCB *) fifo_timeout_int, s);

    qemu_register_reset(serial_reset, s);

    qemu_chr_fe_set_handlers(&s->chr, serial_can_receive1, serial_receive1,

                             serial_event, NULL, s, NULL, true);

    fifo8_create(&s->recv_fifo, UART_FIFO_LENGTH);

    fifo8_create(&s->xmit_fifo, UART_FIFO_LENGTH);

    serial_reset(s);

}


static int get_physical_address(CPUPPCState *env, mmu_ctx_t *ctx,

                                target_ulong eaddr, int rw, int access_type)

{

    int ret;

#if 0

    qemu_log("%s\n", __func__);

#endif

    if ((access_type == ACCESS_CODE && msr_ir == 0) ||

        (access_type != ACCESS_CODE && msr_dr == 0)) {

        if (env->mmu_model == POWERPC_MMU_BOOKE) {

            /* The BookE MMU always performs address translation. The

               IS and DS bits only affect the address space.  */

            ret = mmubooke_get_physical_address(env, ctx, eaddr,

                                                rw, access_type);

        } else if (env->mmu_model == POWERPC_MMU_BOOKE206) {

            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,

                                                   access_type);

        } else {

            /* No address translation.  */

            ret = check_physical(env, ctx, eaddr, rw);

        }

    } else {

        ret = -1;

        switch (env->mmu_model) {

        case POWERPC_MMU_32B:

        case POWERPC_MMU_601:

            /* Try to find a BAT */

            if (env->nb_BATs != 0) {

                ret = get_bat(env, ctx, eaddr, rw, access_type);

            }

            if (ret < 0) {

                /* We didn't match any BAT entry or don't have BATs */

                ret = get_segment32(env, ctx, eaddr, rw, access_type);

            }

            break;

        case POWERPC_MMU_SOFT_6xx:

        case POWERPC_MMU_SOFT_74xx:

            /* Try to find a BAT */

            if (env->nb_BATs != 0) {

                ret = get_bat(env, ctx, eaddr, rw, access_type);

            }

            if (ret < 0) {

                /* We didn't match any BAT entry or don't have BATs */

                ret = get_segment_6xx_tlb(env, ctx, eaddr, rw, access_type);

            }

            break;

#if defined(TARGET_PPC64)

        case POWERPC_MMU_64B:

        case POWERPC_MMU_2_06:

        case POWERPC_MMU_2_06d:

            ret = get_segment64(env, ctx, eaddr, rw, access_type);

            break;

#endif

        case POWERPC_MMU_SOFT_4xx:

        case POWERPC_MMU_SOFT_4xx_Z:

            ret = mmu40x_get_physical_address(env, ctx, eaddr,

                                              rw, access_type);

            break;

        case POWERPC_MMU_BOOKE:

            ret = mmubooke_get_physical_address(env, ctx, eaddr,

                                                rw, access_type);

            break;

        case POWERPC_MMU_BOOKE206:

            ret = mmubooke206_get_physical_address(env, ctx, eaddr, rw,

                                               access_type);

            break;

        case POWERPC_MMU_MPC8xx:

            /* XXX: TODO */

            cpu_abort(env, "MPC8xx MMU model is not implemented\n");

            break;

        case POWERPC_MMU_REAL:

            cpu_abort(env, "PowerPC in real mode do not do any translation\n");

            return -1;

        default:

            cpu_abort(env, "Unknown or invalid MMU model\n");

            return -1;

        }

    }

#if 0

    qemu_log("%s address " TARGET_FMT_lx " => %d " TARGET_FMT_plx "\n",

             __func__, eaddr, ret, ctx->raddr);

#endif

    return ret;

}


static uint8_t eeprom24c0x_read(void)

{

    logout("%u: scl = %u, sda = %u, data = 0x%02x\n",

        eeprom.tick, eeprom.scl, eeprom.sda, eeprom.data);

    return eeprom.sda;

}


static void blockdev_do_action(int kind, void *data, Error **errp)

{

    TransactionAction action;

    TransactionActionList list;

    action.kind = kind;

    action.data = data;

    list.value = &action;

    list.next = NULL;

    qmp_transaction(&list, errp);

}


static void h263_h_loop_filter_mmx(uint8_t *src, int stride, int qscale)

{

    if (CONFIG_H263_DECODER || CONFIG_H263_ENCODER) {

        const int strength = ff_h263_loop_filter_strength[qscale];

        DECLARE_ALIGNED(8, uint64_t, temp)[4];

        uint8_t *btemp = (uint8_t*)temp;

        src -= 2;

        transpose4x4(btemp,     src,              8, stride);

        transpose4x4(btemp + 4, src + 4 * stride, 8, stride);

        __asm__ volatile (

            H263_LOOP_FILTER // 5 3 4 6

            : "+m"(temp[0]),

              "+m"(temp[1]),

              "+m"(temp[2]),

              "+m"(temp[3])

            : "g"(2 * strength), "m"(ff_pb_FC)

            );

        __asm__ volatile (

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

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

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

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

            "punpckhbw %%mm3, %%mm1         \n\t"

            "punpckhbw %%mm6, %%mm0         \n\t"

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

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

            "punpcklwd %%mm4, %%mm5         \n\t"

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

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

            "punpckhwd %%mm0, %%mm6         \n\t"

            "movd      %%mm5, (%0)          \n\t"

            "punpckhdq %%mm5, %%mm5         \n\t"

            "movd      %%mm5, (%0, %2)      \n\t"

            "movd      %%mm3, (%0, %2, 2)   \n\t"

            "punpckhdq %%mm3, %%mm3         \n\t"

            "movd      %%mm3, (%0, %3)      \n\t"

            "movd      %%mm1, (%1)          \n\t"

            "punpckhdq %%mm1, %%mm1         \n\t"

            "movd      %%mm1, (%1, %2)      \n\t"

            "movd      %%mm6, (%1, %2, 2)   \n\t"

            "punpckhdq %%mm6, %%mm6         \n\t"

            "movd      %%mm6, (%1, %3)      \n\t"

            :: "r"(src),

               "r"(src + 4 * stride),

               "r"((x86_reg)stride),

               "r"((x86_reg)(3 * stride))

            );

    }

}


static void bootp_reply(struct bootp_t *bp)

{

    BOOTPClient *bc;

    struct mbuf *m;

    struct bootp_t *rbp;

    struct sockaddr_in saddr, daddr;

    struct in_addr dns_addr;

    int dhcp_msg_type, val;

    uint8_t *q;

    /* extract exact DHCP msg type */

    dhcp_decode(bp->bp_vend, DHCP_OPT_LEN, &dhcp_msg_type);

    dprintf("bootp packet op=%d msgtype=%d\n", bp->bp_op, dhcp_msg_type);

    if (dhcp_msg_type == 0)

        dhcp_msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */

    if (dhcp_msg_type != DHCPDISCOVER &&

        dhcp_msg_type != DHCPREQUEST)

        return;

    /* XXX: this is a hack to get the client mac address */

    memcpy(client_ethaddr, bp->bp_hwaddr, 6);

    if ((m = m_get()) == NULL)

        return;

    m->m_data += IF_MAXLINKHDR;

    rbp = (struct bootp_t *)m->m_data;

    m->m_data += sizeof(struct udpiphdr);

    memset(rbp, 0, sizeof(struct bootp_t));

    if (dhcp_msg_type == DHCPDISCOVER) {

    new_addr:

        bc = get_new_addr(&daddr.sin_addr);

        if (!bc) {

            dprintf("no address left\n");

            return;

        }

        memcpy(bc->macaddr, client_ethaddr, 6);

    } else {

        bc = find_addr(&daddr.sin_addr, bp->bp_hwaddr);

        if (!bc) {

            /* if never assigned, behaves as if it was already

               assigned (windows fix because it remembers its address) */

            goto new_addr;

        }

    }

    if (bootp_filename)

        snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), "%s",

                 bootp_filename);

    dprintf("offered addr=%08x\n", ntohl(daddr.sin_addr.s_addr));

    saddr.sin_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_ALIAS);

    saddr.sin_port = htons(BOOTP_SERVER);

    daddr.sin_port = htons(BOOTP_CLIENT);

    rbp->bp_op = BOOTP_REPLY;

    rbp->bp_xid = bp->bp_xid;

    rbp->bp_htype = 1;

    rbp->bp_hlen = 6;

    memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, 6);

    rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */

    rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */

    daddr.sin_addr.s_addr = 0xffffffffu;

    q = rbp->bp_vend;

    memcpy(q, rfc1533_cookie, 4);

    q += 4;

    if (dhcp_msg_type == DHCPDISCOVER) {

        *q++ = RFC2132_MSG_TYPE;

        *q++ = 1;

        *q++ = DHCPOFFER;

    } else if (dhcp_msg_type == DHCPREQUEST) {

        *q++ = RFC2132_MSG_TYPE;

        *q++ = 1;

        *q++ = DHCPACK;

    }

    if (dhcp_msg_type == DHCPDISCOVER ||

        dhcp_msg_type == DHCPREQUEST) {

        *q++ = RFC2132_SRV_ID;

        *q++ = 4;

        memcpy(q, &saddr.sin_addr, 4);

        q += 4;

        *q++ = RFC1533_NETMASK;

        *q++ = 4;

        *q++ = 0xff;

        *q++ = 0xff;

        *q++ = 0xff;

        *q++ = 0x00;

        if (!slirp_restrict) {

            *q++ = RFC1533_GATEWAY;

            *q++ = 4;

            memcpy(q, &saddr.sin_addr, 4);

            q += 4;

            *q++ = RFC1533_DNS;

            *q++ = 4;

            dns_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_DNS);

            memcpy(q, &dns_addr, 4);

            q += 4;

        }

        *q++ = RFC2132_LEASE_TIME;

        *q++ = 4;

        val = htonl(LEASE_TIME);

        memcpy(q, &val, 4);

        q += 4;

        if (*slirp_hostname) {

            val = strlen(slirp_hostname);

            *q++ = RFC1533_HOSTNAME;

            *q++ = val;

            memcpy(q, slirp_hostname, val);

            q += val;

        }

    }

    *q++ = RFC1533_END;

    m->m_len = sizeof(struct bootp_t) -

        sizeof(struct ip) - sizeof(struct udphdr);

    udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY);

}


static uint32_t drc_isolate_physical(sPAPRDRConnector *drc)

{

    switch (drc->state) {

    case SPAPR_DRC_STATE_PHYSICAL_POWERON:

        return RTAS_OUT_SUCCESS; /* Nothing to do */

    case SPAPR_DRC_STATE_PHYSICAL_CONFIGURED:

        break; /* see below */

    case SPAPR_DRC_STATE_PHYSICAL_UNISOLATE:

        return RTAS_OUT_PARAM_ERROR; /* not allowed */

    default:

        g_assert_not_reached();

    }

    /* if the guest is configuring a device attached to this DRC, we

     * should reset the configuration state at this point since it may

     * no longer be reliable (guest released device and needs to start

     * over, or unplug occurred so the FDT is no longer valid)

     */

    g_free(drc->ccs);

    drc->ccs = NULL;

    drc->state = SPAPR_DRC_STATE_PHYSICAL_POWERON;

    if (drc->unplug_requested) {

        uint32_t drc_index = spapr_drc_index(drc);

        trace_spapr_drc_set_isolation_state_finalizing(drc_index);

        spapr_drc_detach(drc);

    }

    return RTAS_OUT_SUCCESS;

}


static void input_linux_event_mouse(void *opaque)

{

    InputLinux *il = opaque;

    struct input_event event;

    int rc;

    for (;;) {

        rc = read(il->fd, &event, sizeof(event));

        if (rc != sizeof(event)) {

            if (rc < 0 && errno != EAGAIN) {

                fprintf(stderr, "%s: read: %s\n", __func__, strerror(errno));

                qemu_set_fd_handler(il->fd, NULL, NULL, NULL);

                close(il->fd);

            }

            break;

        }

        input_linux_handle_mouse(il, &event);

    }

}


int float64_eq( float64 a, float64 b STATUS_PARAM )

{

    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )

         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )

       ) {

        if ( float64_is_signaling_nan( a ) || float64_is_signaling_nan( b ) ) {

            float_raise( float_flag_invalid STATUS_VAR);

        }

        return 0;

    }

    return ( a == b ) || ( (bits64) ( ( a | b )<<1 ) == 0 );

}


static always_inline void gen_cmp(TCGCond cond,

                                  int ra, int rb, int rc,

                                  int islit, uint8_t lit)

{

    int l1, l2;

    TCGv tmp;

    if (unlikely(rc == 31))

    return;

    l1 = gen_new_label();

    l2 = gen_new_label();

    if (ra != 31) {

        tmp = tcg_temp_new(TCG_TYPE_I64);

        tcg_gen_mov_i64(tmp, cpu_ir[ra]);

    } else

        tmp = tcg_const_i64(0);

    if (islit)

        tcg_gen_brcondi_i64(cond, tmp, lit, l1);

    else

        tcg_gen_brcond_i64(cond, tmp, cpu_ir[rb], l1);

    tcg_gen_movi_i64(cpu_ir[rc], 0);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_movi_i64(cpu_ir[rc], 1);

    gen_set_label(l2);

}


static int virtio_scsi_device_exit(DeviceState *qdev)

{

    VirtIOSCSI *s = VIRTIO_SCSI(qdev);

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(qdev);

    unregister_savevm(qdev, "virtio-scsi", s);

    return virtio_scsi_common_exit(vs);

}


static int pci_vpb_init(SysBusDevice *dev)

{

    PCIVPBState *s = FROM_SYSBUS(PCIVPBState, dev);

    PCIBus *bus;

    int i;

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

        sysbus_init_irq(dev, &s->irq[i]);

    }

    bus = pci_register_bus(&dev->qdev, "pci",

                           pci_vpb_set_irq, pci_vpb_map_irq, s->irq,

                           get_system_memory(), get_system_io(),

                           PCI_DEVFN(11, 0), 4);

    /* ??? Register memory space.  */

    memory_region_init_io(&s->mem_config, &pci_vpb_config_ops, bus,

                          "pci-vpb-selfconfig", 0x1000000);

    memory_region_init_io(&s->mem_config2, &pci_vpb_config_ops, bus,

                          "pci-vpb-config", 0x1000000);

    if (s->realview) {

        isa_mmio_setup(&s->isa, 0x0100000);

    }

    sysbus_init_mmio_cb2(dev, pci_vpb_map, pci_vpb_unmap);

    pci_create_simple(bus, -1, "versatile_pci_host");

    return 0;

}


static void rng_random_set_filename(Object *obj, const char *filename,

                                 Error **errp)

{

    RngBackend *b = RNG_BACKEND(obj);

    RndRandom *s = RNG_RANDOM(obj);

    if (b->opened) {

        error_set(errp, QERR_PERMISSION_DENIED);

        return;

    }

    if (s->filename) {

        g_free(s->filename);

    }

    s->filename = g_strdup(filename);

}


static void rtas_ibm_get_config_addr_info2(PowerPCCPU *cpu,

                                           sPAPRMachineState *spapr,

                                           uint32_t token, uint32_t nargs,

                                           target_ulong args, uint32_t nret,

                                           target_ulong rets)

{

    sPAPRPHBState *sphb;

    PCIDevice *pdev;

    uint32_t addr, option;

    uint64_t buid;

    if ((nargs != 4) || (nret != 2)) {

        goto param_error_exit;

    }

    buid = rtas_ldq(args, 1);

    sphb = spapr_pci_find_phb(spapr, buid);

    if (!sphb) {

        goto param_error_exit;

    }

    if (!spapr_phb_eeh_available(sphb)) {

        goto param_error_exit;

    }

    /*

     * We always have PE address of form "00BB0001". "BB"

     * represents the bus number of PE's primary bus.

     */

    option = rtas_ld(args, 3);

    switch (option) {

    case RTAS_GET_PE_ADDR:

        addr = rtas_ld(args, 0);

        pdev = spapr_pci_find_dev(spapr, buid, addr);

        if (!pdev) {

            goto param_error_exit;

        }

        rtas_st(rets, 1, (pci_bus_num(pdev->bus) << 16) + 1);

        break;

    case RTAS_GET_PE_MODE:

        rtas_st(rets, 1, RTAS_PE_MODE_SHARED);

        break;

    default:

        goto param_error_exit;

    }

    rtas_st(rets, 0, RTAS_OUT_SUCCESS);

    return;

param_error_exit:

    rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

}


static void migrate_fd_completed(MigrationState *s)

{

    DPRINTF("setting completed state\n");

    migrate_fd_cleanup(s);

    if (s->state == MIG_STATE_ACTIVE) {

        s->state = MIG_STATE_COMPLETED;

        runstate_set(RUN_STATE_POSTMIGRATE);

    }

    notifier_list_notify(&migration_state_notifiers, s);

}


static unsigned int dec_adds_r(DisasContext *dc)

{

	TCGv t0;

	int size = memsize_z(dc);

	DIS(fprintf (logfile, "adds.%c $r%u, $r%u\n",

		    memsize_char(size),

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

	cris_cc_mask(dc, CC_MASK_NZVC);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	/* Size can only be qi or hi.  */

	t_gen_sext(t0, cpu_R[dc->op1], size);

	cris_alu(dc, CC_OP_ADD,

		    cpu_R[dc->op2], cpu_R[dc->op2], t0, 4);

	tcg_temp_free(t0);

	return 2;

}


static void create_map(vorbis_context *vc, unsigned floor_number)

{

    vorbis_floor *floors = vc->floors;

    vorbis_floor0 *vf;

    int idx;

    int blockflag, n;

    int32_t *map;

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

        n = vc->blocksize[blockflag] / 2;

        floors[floor_number].data.t0.map[blockflag] =

            av_malloc((n + 1) * sizeof(int32_t)); // n + sentinel

        map =  floors[floor_number].data.t0.map[blockflag];

        vf  = &floors[floor_number].data.t0;

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

            map[idx] = floor(BARK((vf->rate * idx) / (2.0f * n)) *

                             (vf->bark_map_size / BARK(vf->rate / 2.0f)));

            if (vf->bark_map_size-1 < map[idx])

                map[idx] = vf->bark_map_size - 1;

        }

        map[n] = -1;

        vf->map_size[blockflag] = n;

    }

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

        av_dlog(NULL, "floor0 map: map at pos %d is %d\n", idx, map[idx]);

    }

}


static void virtio_scsi_parse_req(VirtIOSCSI *s, VirtQueue *vq,

                                  VirtIOSCSIReq *req)

{

    assert(req->elem.out_num && req->elem.in_num);

    req->vq = vq;

    req->dev = s;

    req->sreq = NULL;

    req->req.buf = req->elem.out_sg[0].iov_base;

    req->resp.buf = req->elem.in_sg[0].iov_base;

    if (req->elem.out_num > 1) {

        qemu_sgl_init_external(&req->qsgl, &req->elem.out_sg[1],

                               &req->elem.out_addr[1],

                               req->elem.out_num - 1);

    } else {

        qemu_sgl_init_external(&req->qsgl, &req->elem.in_sg[1],

                               &req->elem.in_addr[1],

                               req->elem.in_num - 1);

    }

}


static void usb_uas_task(UASDevice *uas, uas_ui *ui)

{

    uint16_t tag = be16_to_cpu(ui->hdr.tag);

    uint64_t lun64 = be64_to_cpu(ui->task.lun);

    SCSIDevice *dev = usb_uas_get_dev(uas, lun64);

    int lun = usb_uas_get_lun(lun64);

    UASRequest *req;

    uint16_t task_tag;

    req = usb_uas_find_request(uas, be16_to_cpu(ui->hdr.tag));

    if (req) {

        goto overlapped_tag;

    }

    switch (ui->task.function) {

    case UAS_TMF_ABORT_TASK:

        task_tag = be16_to_cpu(ui->task.task_tag);

        trace_usb_uas_tmf_abort_task(uas->dev.addr, tag, task_tag);

        if (dev == NULL) {

            goto bad_target;

        }

        if (dev->lun != lun) {

            goto incorrect_lun;

        }

        req = usb_uas_find_request(uas, task_tag);

        if (req && req->dev == dev) {

            scsi_req_cancel(req->req);

        }

        usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);

        break;

    case UAS_TMF_LOGICAL_UNIT_RESET:

        trace_usb_uas_tmf_logical_unit_reset(uas->dev.addr, tag, lun);

        if (dev == NULL) {

            goto bad_target;

        }

        if (dev->lun != lun) {

            goto incorrect_lun;

        }

        qdev_reset_all(&dev->qdev);

        usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);

        break;

    default:

        trace_usb_uas_tmf_unsupported(uas->dev.addr, tag, ui->task.function);

        usb_uas_queue_response(uas, tag, UAS_RC_TMF_NOT_SUPPORTED, 0);

        break;

    }

    return;

overlapped_tag:

    usb_uas_queue_response(uas, req->tag, UAS_RC_OVERLAPPED_TAG, 0);

    return;

bad_target:

    /* FIXME: correct?  [see long comment in usb_uas_command()] */

    usb_uas_queue_response(uas, tag, UAS_RC_INVALID_INFO_UNIT, 0);

    return;

incorrect_lun:

    usb_uas_queue_response(uas, tag, UAS_RC_INCORRECT_LUN, 0);

}


static int ide_qdev_init(DeviceState *qdev, DeviceInfo *base)

{

    IDEDevice *dev = DO_UPCAST(IDEDevice, qdev, qdev);

    IDEDeviceInfo *info = DO_UPCAST(IDEDeviceInfo, qdev, base);

    IDEBus *bus = DO_UPCAST(IDEBus, qbus, qdev->parent_bus);

    if (!dev->conf.dinfo) {

        fprintf(stderr, "%s: no drive specified\n", qdev->info->name);

        goto err;

    }

    if (dev->unit == -1) {

        dev->unit = bus->master ? 1 : 0;

    }

    switch (dev->unit) {

    case 0:

        if (bus->master) {

            fprintf(stderr, "ide: tried to assign master twice\n");

            goto err;

        }

        bus->master = dev;

        break;

    case 1:

        if (bus->slave) {

            fprintf(stderr, "ide: tried to assign slave twice\n");

            goto err;

        }

        bus->slave = dev;

        break;

    default:

        goto err;

    }

    return info->init(dev);

err:

    return -1;

}


static int tcg_match_ori(TCGType type, tcg_target_long val)

{

    if (facilities & FACILITY_EXT_IMM) {

        if (type == TCG_TYPE_I32) {

            /* All 32-bit ORs can be performed with 1 48-bit insn.  */

            return 1;

        }

    }

    /* Look for negative values.  These are best to load with LGHI.  */

    if (val < 0) {

        if (val == (int16_t)val) {

            return 0;

        }

        if (facilities & FACILITY_EXT_IMM) {

            if (val == (int32_t)val) {

                return 0;

            }

        }

    }

    return 1;

}


void OPPROTO op_addq_EDI_T0(void)

{

    EDI = (EDI + T0);

}


static void hypercall_register_types(void)

{

    /* hcall-pft */

    spapr_register_hypercall(H_ENTER, h_enter);

    spapr_register_hypercall(H_REMOVE, h_remove);

    spapr_register_hypercall(H_PROTECT, h_protect);

    spapr_register_hypercall(H_READ, h_read);

    /* hcall-bulk */

    spapr_register_hypercall(H_BULK_REMOVE, h_bulk_remove);

    /* hcall-dabr */

    spapr_register_hypercall(H_SET_DABR, h_set_dabr);

    /* hcall-splpar */

    spapr_register_hypercall(H_REGISTER_VPA, h_register_vpa);

    spapr_register_hypercall(H_CEDE, h_cede);

    /* processor register resource access h-calls */

    spapr_register_hypercall(H_SET_SPRG0, h_set_sprg0);

    spapr_register_hypercall(H_SET_MODE, h_set_mode);

    /* "debugger" hcalls (also used by SLOF). Note: We do -not- differenciate

     * here between the "CI" and the "CACHE" variants, they will use whatever

     * mapping attributes qemu is using. When using KVM, the kernel will

     * enforce the attributes more strongly

     */

    spapr_register_hypercall(H_LOGICAL_CI_LOAD, h_logical_load);

    spapr_register_hypercall(H_LOGICAL_CI_STORE, h_logical_store);

    spapr_register_hypercall(H_LOGICAL_CACHE_LOAD, h_logical_load);

    spapr_register_hypercall(H_LOGICAL_CACHE_STORE, h_logical_store);

    spapr_register_hypercall(H_LOGICAL_ICBI, h_logical_icbi);

    spapr_register_hypercall(H_LOGICAL_DCBF, h_logical_dcbf);

    spapr_register_hypercall(KVMPPC_H_LOGICAL_MEMOP, h_logical_memop);

    /* qemu/KVM-PPC specific hcalls */

    spapr_register_hypercall(KVMPPC_H_RTAS, h_rtas);

    /* ibm,client-architecture-support support */

    spapr_register_hypercall(KVMPPC_H_CAS, h_client_architecture_support);

}


static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)

{

    VirtIOBlock *s = VIRTIO_BLK(vdev);

    BlockConf *conf = &s->conf.conf;

    struct virtio_blk_config blkcfg;

    uint64_t capacity;

    int blk_size = conf->logical_block_size;

    bdrv_get_geometry(s->bs, &capacity);

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

    virtio_stq_p(vdev, &blkcfg.capacity, capacity);

    virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);

    virtio_stw_p(vdev, &blkcfg.cylinders, conf->cyls);

    virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);

    virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);

    virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);

    blkcfg.heads = conf->heads;

    /*

     * We must ensure that the block device capacity is a multiple of

     * the logical block size. If that is not the case, let's use

     * sector_mask to adopt the geometry to have a correct picture.

     * For those devices where the capacity is ok for the given geometry

     * we don't touch the sector value of the geometry, since some devices

     * (like s390 dasd) need a specific value. Here the capacity is already

     * cyls*heads*secs*blk_size and the sector value is not block size

     * divided by 512 - instead it is the amount of blk_size blocks

     * per track (cylinder).

     */

    if (bdrv_getlength(s->bs) /  conf->heads / conf->secs % blk_size) {

        blkcfg.sectors = conf->secs & ~s->sector_mask;

    } else {

        blkcfg.sectors = conf->secs;

    }

    blkcfg.size_max = 0;

    blkcfg.physical_block_exp = get_physical_block_exp(conf);

    blkcfg.alignment_offset = 0;

    blkcfg.wce = bdrv_enable_write_cache(s->bs);

    memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));

}