static void attach(sPAPRDRConnector *drc, DeviceState *d, void *fdt,
                   int fdt_start_offset, bool coldplug, Error **errp)
{
    DPRINTFN("drc: %x, attach", get_index(drc));
    if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {
        error_setg(errp, "an attached device is still awaiting release");
        return;
    if (drc->type == SPAPR_DR_CONNECTOR_TYPE_PCI) {
        g_assert(drc->allocation_state == SPAPR_DR_ALLOCATION_STATE_USABLE);
    g_assert(fdt || coldplug);
    /* NOTE: setting initial isolation state to UNISOLATED means we can't
     * detach unless guest has a userspace/kernel that moves this state
     * back to ISOLATED in response to an unplug event, or this is done
     * manually by the admin prior. if we force things while the guest
     * may be accessing the device, we can easily crash the guest, so we
     * we defer completion of removal in such cases to the reset() hook.
     */
    if (drc->type == SPAPR_DR_CONNECTOR_TYPE_PCI) {
        drc->isolation_state = SPAPR_DR_ISOLATION_STATE_UNISOLATED;
    drc->indicator_state = SPAPR_DR_INDICATOR_STATE_ACTIVE;
    drc->dev = d;
    drc->fdt = fdt;
    drc->fdt_start_offset = fdt_start_offset;
    drc->configured = coldplug;
    /* 'logical' DR resources such as memory/cpus are in some cases treated
     * as a pool of resources from which the guest is free to choose from
     * based on only a count. for resources that can be assigned in this
     * fashion, we must assume the resource is signalled immediately
     * since a single hotplug request might make an arbitrary number of
     * such attached resources available to the guest, as opposed to
     * 'physical' DR resources such as PCI where each device/resource is
     * signalled individually.
     */
    drc->signalled = (drc->type != SPAPR_DR_CONNECTOR_TYPE_PCI)
                     ? true : coldplug;
    object_property_add_link(OBJECT(drc), "device",
                             object_get_typename(OBJECT(drc->dev)),
                             (Object **)(&drc->dev),
                             NULL, 0, NULL);


static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)

{

    BDRVSheepdogState *s = acb->common.bs->opaque;

    struct iovec iov;

    AIOReq *aio_req;

    uint32_t offset, data_len, mn, mx;

    mn = s->min_dirty_data_idx;

    mx = s->max_dirty_data_idx;

    if (mn <= mx) {

        /* we need to update the vdi object. */

        offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +

            mn * sizeof(s->inode.data_vdi_id[0]);

        data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);

        s->min_dirty_data_idx = UINT32_MAX;

        s->max_dirty_data_idx = 0;

        iov.iov_base = &s->inode;

        iov.iov_len = sizeof(s->inode);

        aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),

                                data_len, offset, 0, 0, offset);

        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);

        add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);

        acb->aio_done_func = sd_finish_aiocb;

        acb->aiocb_type = AIOCB_WRITE_UDATA;

        return;

    }

    sd_finish_aiocb(acb);

}


static int execute_code(AVCodecContext * avctx, int c)

{

    AnsiContext *s = avctx->priv_data;

    int ret, i, width, height;

    switch(c) {

    case 'A': //Cursor Up

        s->y = FFMAX(s->y - (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), 0);

        break;

    case 'B': //Cursor Down

        s->y = FFMIN(s->y + (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), avctx->height - s->font_height);

        break;

    case 'C': //Cursor Right

        s->x = FFMIN(s->x + (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), avctx->width  - FONT_WIDTH);

        break;

    case 'D': //Cursor Left

        s->x = FFMAX(s->x - (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), 0);

        break;

    case 'H': //Cursor Position

    case 'f': //Horizontal and Vertical Position

        s->y = s->nb_args > 0 ? av_clip((s->args[0] - 1)*s->font_height, 0, avctx->height - s->font_height) : 0;

        s->x = s->nb_args > 1 ? av_clip((s->args[1] - 1)*FONT_WIDTH,     0, avctx->width  - FONT_WIDTH) : 0;

        break;

    case 'h': //set creen mode

    case 'l': //reset screen mode

        if (s->nb_args < 2)

            s->args[0] = DEFAULT_SCREEN_MODE;

        switch(s->args[0]) {

        case 0: case 1: case 4: case 5: case 13: case 19: //320x200 (25 rows)

            s->font = ff_cga_font;

            s->font_height = 8;

            width  = 40<<3;

            height = 25<<3;

            break;

        case 2: case 3: //640x400 (25 rows)

            s->font = ff_vga16_font;

            s->font_height = 16;

            width  = 80<<3;

            height = 25<<4;

            break;

        case 6: case 14: //640x200 (25 rows)

            s->font = ff_cga_font;

            s->font_height = 8;

            width  = 80<<3;

            height = 25<<3;

            break;

        case 7: //set line wrapping

            break;

        case 15: case 16: //640x350 (43 rows)

            s->font = ff_cga_font;

            s->font_height = 8;

            width  = 80<<3;

            height = 43<<3;

            break;

        case 17: case 18: //640x480 (60 rows)

            s->font = ff_cga_font;

            s->font_height = 8;

            width  = 80<<3;

            height = 60<<4;

            break;

        default:

            avpriv_request_sample(avctx, "Unsupported screen mode");

        }

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

            av_frame_unref(s->frame);

            ret = ff_set_dimensions(avctx, width, height);

            if (ret < 0)

                return ret;

            ret = ff_get_buffer(avctx, s->frame, AV_GET_BUFFER_FLAG_REF);

            if (ret < 0) {

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

                return ret;

            }

            s->frame->pict_type           = AV_PICTURE_TYPE_I;

            s->frame->palette_has_changed = 1;

            memcpy(s->frame->data[1], ff_cga_palette, 16 * 4);

            erase_screen(avctx);

        } else if (c == 'l') {

            erase_screen(avctx);

        }

        break;

    case 'J': //Erase in Page

        switch (s->args[0]) {

        case 0:

            erase_line(avctx, s->x, avctx->width - s->x);

            if (s->y < avctx->height - s->font_height)

                memset(s->frame->data[0] + (s->y + s->font_height)*s->frame->linesize[0],

                    DEFAULT_BG_COLOR, (avctx->height - s->y - s->font_height)*s->frame->linesize[0]);

            break;

        case 1:

            erase_line(avctx, 0, s->x);

            if (s->y > 0)

                memset(s->frame->data[0], DEFAULT_BG_COLOR, s->y * s->frame->linesize[0]);

            break;

        case 2:

            erase_screen(avctx);

        }

        break;

    case 'K': //Erase in Line

        switch(s->args[0]) {

        case 0:

            erase_line(avctx, s->x, avctx->width - s->x);

            break;

        case 1:

            erase_line(avctx, 0, s->x);

            break;

        case 2:

            erase_line(avctx, 0, avctx->width);

        }

        break;

    case 'm': //Select Graphics Rendition

        if (s->nb_args == 0) {

            s->nb_args = 1;

            s->args[0] = 0;

        }

        for (i = 0; i < FFMIN(s->nb_args, MAX_NB_ARGS); i++) {

            int m = s->args[i];

            if (m == 0) {

                s->attributes = 0;

                s->fg = DEFAULT_FG_COLOR;

                s->bg = DEFAULT_BG_COLOR;

            } else if (m == 1 || m == 2 || m == 4 || m == 5 || m == 7 || m == 8) {

                s->attributes |= 1 << (m - 1);

            } else if (m >= 30 && m <= 38) {

                s->fg = ansi_to_cga[m - 30];

            } else if (m == 39) {

                s->fg = ansi_to_cga[DEFAULT_FG_COLOR];

            } else if (m >= 40 && m <= 47) {

                s->bg = ansi_to_cga[m - 40];

            } else if (m == 49) {

                s->fg = ansi_to_cga[DEFAULT_BG_COLOR];

            } else {

                avpriv_request_sample(avctx, "Unsupported rendition parameter");

            }

        }

        break;

    case 'n': //Device Status Report

    case 'R': //report current line and column

        /* ignore */

        break;

    case 's': //Save Cursor Position

        s->sx = s->x;

        s->sy = s->y;

        break;

    case 'u': //Restore Cursor Position

        s->x = av_clip(s->sx, 0, avctx->width  - FONT_WIDTH);

        s->y = av_clip(s->sy, 0, avctx->height - s->font_height);

        break;

    default:

        avpriv_request_sample(avctx, "Unknown escape code");

        break;

    }

    return 0;

}


void migration_bitmap_extend(ram_addr_t old, ram_addr_t new)

{

    /* called in qemu main thread, so there is

     * no writing race against this migration_bitmap

     */

    if (migration_bitmap) {

        unsigned long *old_bitmap = migration_bitmap, *bitmap;

        bitmap = bitmap_new(new);

        /* prevent migration_bitmap content from being set bit

         * by migration_bitmap_sync_range() at the same time.

         * it is safe to migration if migration_bitmap is cleared bit

         * at the same time.

         */

        qemu_mutex_lock(&migration_bitmap_mutex);

        bitmap_copy(bitmap, old_bitmap, old);

        bitmap_set(bitmap, old, new - old);

        atomic_rcu_set(&migration_bitmap, bitmap);

        qemu_mutex_unlock(&migration_bitmap_mutex);

        migration_dirty_pages += new - old;

        synchronize_rcu();

        g_free(old_bitmap);

    }

}


static void coroutine_fn v9fs_walk(void *opaque)

{

    int name_idx;

    V9fsQID *qids = NULL;

    int i, err = 0;

    V9fsPath dpath, path;

    uint16_t nwnames;

    struct stat stbuf;

    size_t offset = 7;

    int32_t fid, newfid;

    V9fsString *wnames = NULL;

    V9fsFidState *fidp;

    V9fsFidState *newfidp = NULL;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    V9fsQID qid;

    err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames);

    if (err < 0) {

        pdu_complete(pdu, err);

        return ;

    }

    offset += err;

    trace_v9fs_walk(pdu->tag, pdu->id, fid, newfid, nwnames);

    if (nwnames && nwnames <= P9_MAXWELEM) {

        wnames = g_malloc0(sizeof(wnames[0]) * nwnames);

        qids   = g_malloc0(sizeof(qids[0]) * nwnames);

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

            err = pdu_unmarshal(pdu, offset, "s", &wnames[i]);

            if (err < 0) {

                goto out_nofid;

            }

            if (name_is_illegal(wnames[i].data)) {

                err = -ENOENT;

                goto out_nofid;

            }

            offset += err;

        }

    } else if (nwnames > P9_MAXWELEM) {

        err = -EINVAL;

        goto out_nofid;

    }

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    v9fs_path_init(&dpath);

    v9fs_path_init(&path);

    err = fid_to_qid(pdu, fidp, &qid);

    if (err < 0) {

        goto out;

    }

    /*

     * Both dpath and path initially poin to fidp.

     * Needed to handle request with nwnames == 0

     */

    v9fs_path_copy(&dpath, &fidp->path);

    v9fs_path_copy(&path, &fidp->path);

    for (name_idx = 0; name_idx < nwnames; name_idx++) {

        if (not_same_qid(&pdu->s->root_qid, &qid) ||

            strcmp("..", wnames[name_idx].data)) {

            err = v9fs_co_name_to_path(pdu, &dpath, wnames[name_idx].data,

                                       &path);

            if (err < 0) {

                goto out;

            }

            err = v9fs_co_lstat(pdu, &path, &stbuf);

            if (err < 0) {

                goto out;

            }

            stat_to_qid(&stbuf, &qid);

            v9fs_path_copy(&dpath, &path);

        }

        memcpy(&qids[name_idx], &qid, sizeof(qid));

    }

    if (fid == newfid) {

        BUG_ON(fidp->fid_type != P9_FID_NONE);

        v9fs_path_copy(&fidp->path, &path);

    } else {

        newfidp = alloc_fid(s, newfid);

        if (newfidp == NULL) {

            err = -EINVAL;

            goto out;

        }

        newfidp->uid = fidp->uid;

        v9fs_path_copy(&newfidp->path, &path);

    }

    err = v9fs_walk_marshal(pdu, nwnames, qids);

    trace_v9fs_walk_return(pdu->tag, pdu->id, nwnames, qids);

out:

    put_fid(pdu, fidp);

    if (newfidp) {

        put_fid(pdu, newfidp);

    }

    v9fs_path_free(&dpath);

    v9fs_path_free(&path);

out_nofid:

    pdu_complete(pdu, err);

    if (nwnames && nwnames <= P9_MAXWELEM) {

        for (name_idx = 0; name_idx < nwnames; name_idx++) {

            v9fs_string_free(&wnames[name_idx]);

        }

        g_free(wnames);

        g_free(qids);

    }

}


int avpicture_layout(const AVPicture* src, int pix_fmt, int width, int height,

                     unsigned char *dest, int dest_size)

{

    PixFmtInfo* pf = &pix_fmt_info[pix_fmt];

    int i, j, w, h, data_planes;

    const unsigned char* s;

    int size = avpicture_get_size(pix_fmt, width, height);

    if (size > dest_size)

        return -1;

    if (pf->pixel_type == FF_PIXEL_PACKED || pf->pixel_type == FF_PIXEL_PALETTE) {

        if (pix_fmt == PIX_FMT_YUV422 ||

            pix_fmt == PIX_FMT_UYVY422 ||

            pix_fmt == PIX_FMT_RGB565 ||

            pix_fmt == PIX_FMT_RGB555)

            w = width * 2;

	else if (pix_fmt == PIX_FMT_UYVY411)

	  w = width + width/2;

	else if (pix_fmt == PIX_FMT_PAL8)

	  w = width;

	else

	  w = width * (pf->depth * pf->nb_channels / 8);

	data_planes = 1;

	h = height;

    } else {

        data_planes = pf->nb_channels;

	w = (width*pf->depth + 7)/8;

	h = height;

    }

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

         if (i == 1) {

	     w = width >> pf->x_chroma_shift;

	     h = height >> pf->y_chroma_shift;

	 }

         s = src->data[i];

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

	     memcpy(dest, s, w);

	     dest += w;

	     s += src->linesize[i];

	 }

    }

    if (pf->pixel_type == FF_PIXEL_PALETTE)

	memcpy((unsigned char *)(((size_t)dest + 3) & ~3), src->data[1], 256 * 4);

    return size;

}


static int vnc_update_stats(VncDisplay *vd,  struct timeval * tv)

{

    int width = pixman_image_get_width(vd->guest.fb);

    int height = pixman_image_get_height(vd->guest.fb);

    int x, y;

    struct timeval res;

    int has_dirty = 0;

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

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

            VncRectStat *rect = vnc_stat_rect(vd, x, y);

            rect->updated = false;

        }

    }

    qemu_timersub(tv, &VNC_REFRESH_STATS, &res);

    if (timercmp(&vd->guest.last_freq_check, &res, >)) {

        return has_dirty;

    }

    vd->guest.last_freq_check = *tv;

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

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

            VncRectStat *rect= vnc_stat_rect(vd, x, y);

            int count = ARRAY_SIZE(rect->times);

            struct timeval min, max;

            if (!timerisset(&rect->times[count - 1])) {

                continue ;

            }

            max = rect->times[(rect->idx + count - 1) % count];

            qemu_timersub(tv, &max, &res);

            if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {

                rect->freq = 0;

                has_dirty += vnc_refresh_lossy_rect(vd, x, y);

                memset(rect->times, 0, sizeof (rect->times));

                continue ;

            }

            min = rect->times[rect->idx];

            max = rect->times[(rect->idx + count - 1) % count];

            qemu_timersub(&max, &min, &res);

            rect->freq = res.tv_sec + res.tv_usec / 1000000.;

            rect->freq /= count;

            rect->freq = 1. / rect->freq;

        }

    }

    return has_dirty;

}


static void iscsi_readcapacity_sync(IscsiLun *iscsilun, Error **errp)

{

    struct scsi_task *task = NULL;

    struct scsi_readcapacity10 *rc10 = NULL;

    struct scsi_readcapacity16 *rc16 = NULL;

    int retries = ISCSI_CMD_RETRIES;

    do {

        if (task != NULL) {

            scsi_free_scsi_task(task);

            task = NULL;

        }

        switch (iscsilun->type) {

        case TYPE_DISK:

            task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);

            if (task != NULL && task->status == SCSI_STATUS_GOOD) {

                rc16 = scsi_datain_unmarshall(task);

                if (rc16 == NULL) {

                    error_setg(errp, "iSCSI: Failed to unmarshall readcapacity16 data.");

                } else {

                    iscsilun->block_size = rc16->block_length;

                    iscsilun->num_blocks = rc16->returned_lba + 1;

                    iscsilun->lbpme = !!rc16->lbpme;

                    iscsilun->lbprz = !!rc16->lbprz;

                    iscsilun->use_16_for_rw = (rc16->returned_lba > 0xffffffff);

                }

            }

            break;

        case TYPE_ROM:

            task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);

            if (task != NULL && task->status == SCSI_STATUS_GOOD) {

                rc10 = scsi_datain_unmarshall(task);

                if (rc10 == NULL) {

                    error_setg(errp, "iSCSI: Failed to unmarshall readcapacity10 data.");

                } else {

                    iscsilun->block_size = rc10->block_size;

                    if (rc10->lba == 0) {

                        /* blank disk loaded */

                        iscsilun->num_blocks = 0;

                    } else {

                        iscsilun->num_blocks = rc10->lba + 1;

                    }

                }

            }

            break;

        default:

            return;

        }

    } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION

             && task->sense.key == SCSI_SENSE_UNIT_ATTENTION

             && retries-- > 0);

    if (task == NULL || task->status != SCSI_STATUS_GOOD) {

        error_setg(errp, "iSCSI: failed to send readcapacity10 command.");

    }

    if (task) {

        scsi_free_scsi_task(task);

    }

}


static int read_access_unit(AVCodecContext *avctx, void* data,
                            int *got_frame_ptr, 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;
    int ret;
    if (buf_size < 4)
        return AVERROR_INVALIDDATA;
    length = (AV_RB16(buf) & 0xfff) * 2;
    if (length < 4 || length > buf_size)
        return AVERROR_INVALIDDATA;
    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)
        m->is_major_sync_unit = 1;
        header_size += m->major_sync_header_size;
    if (!m->params_valid) {
        av_log(m->avctx, AV_LOG_WARNING,
               "Stream parameters not seen; skipping frame.\n");
        *got_frame_ptr = 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 == AV_CODEC_ID_MLP) {
                av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
            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");
        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);
        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");
    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 {
            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 (!s->restart_seen)
                goto next_substr;
            if ((ret = read_block_data(m, &gb, substr)) < 0)
                return ret;
            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 AVERROR_INVALIDDATA;
            shorten_by = get_bits(&gb, 16);
            if      (m->avctx->codec_id == AV_CODEC_ID_TRUEHD && shorten_by  & 0x2000)
                s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
            else if (m->avctx->codec_id == AV_CODEC_ID_MLP    && shorten_by != 0xD234)
                return AVERROR_INVALIDDATA;
            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];
    if ((ret = output_data(m, m->max_decoded_substream, data, got_frame_ptr)) < 0)
        return ret;
    return length;
substream_length_mismatch:
    av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
    return AVERROR_INVALIDDATA;
error:
    m->params_valid = 0;
    return AVERROR_INVALIDDATA;


enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,

                              const char *filename, const char *mime_type,

                              enum AVMediaType type)

{

    if (av_match_name("segment", fmt->name) || av_match_name("ssegment", fmt->name)) {

        fmt = av_guess_format(NULL, filename, NULL);

    }

    if (type == AVMEDIA_TYPE_VIDEO) {

        enum AVCodecID codec_id = AV_CODEC_ID_NONE;

#if CONFIG_IMAGE2_MUXER

        if (!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")) {

            codec_id = ff_guess_image2_codec(filename);

        }

#endif

        if (codec_id == AV_CODEC_ID_NONE)

            codec_id = fmt->video_codec;

        return codec_id;

    } else if (type == AVMEDIA_TYPE_AUDIO)

        return fmt->audio_codec;

    else if (type == AVMEDIA_TYPE_SUBTITLE)

        return fmt->subtitle_codec;

    else

        return AV_CODEC_ID_NONE;

}


static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)

{

    AVIOContext *pb = s->pb;

    int ret;

    /* parse fmt header */

    *st = av_new_stream(s, 0);

    if (!*st)

        return AVERROR(ENOMEM);

    ff_get_wav_header(pb, (*st)->codec, size);

    if (ret < 0)

        return ret;

    (*st)->need_parsing = AVSTREAM_PARSE_FULL;

    av_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);

    return 0;

}


static int get_float64(QEMUFile *f, void *pv, size_t size)

{

    float64 *v = pv;

    *v = make_float64(qemu_get_be64(f));

    return 0;

}


static int chunk_mux_init(AVFormatContext *s)

{

    WebMChunkContext *wc = s->priv_data;

    AVFormatContext *oc;

    int ret;

    ret = avformat_alloc_output_context2(&wc->avf, wc->oformat, NULL, NULL);

    if (ret < 0)

        return ret;

    oc = wc->avf;

    oc->interrupt_callback = s->interrupt_callback;

    oc->max_delay          = s->max_delay;

    av_dict_copy(&oc->metadata, s->metadata, 0);

    oc->priv_data = av_mallocz(oc->oformat->priv_data_size);

    if (!oc->priv_data) {

        avio_close(oc->pb);

        return AVERROR(ENOMEM);

    }

    *(const AVClass**)oc->priv_data = oc->oformat->priv_class;

    av_opt_set_defaults(oc->priv_data);

    av_opt_set_int(oc->priv_data, "dash", 1, 0);

    av_opt_set_int(oc->priv_data, "cluster_time_limit", wc->chunk_duration, 0);

    av_opt_set_int(oc->priv_data, "live", 1, 0);

    oc->streams = s->streams;

    oc->nb_streams = s->nb_streams;

    return 0;

}


void commit_active_start(const char *job_id, BlockDriverState *bs,

                         BlockDriverState *base, int64_t speed,

                         BlockdevOnError on_error,

                         BlockCompletionFunc *cb,

                         void *opaque, Error **errp)

{

    int64_t length, base_length;

    int orig_base_flags;

    int ret;

    Error *local_err = NULL;

    orig_base_flags = bdrv_get_flags(base);

    if (bdrv_reopen(base, bs->open_flags, errp)) {

        return;

    }

    length = bdrv_getlength(bs);

    if (length < 0) {

        error_setg_errno(errp, -length,

                         "Unable to determine length of %s", bs->filename);

        goto error_restore_flags;

    }

    base_length = bdrv_getlength(base);

    if (base_length < 0) {

        error_setg_errno(errp, -base_length,

                         "Unable to determine length of %s", base->filename);

        goto error_restore_flags;

    }

    if (length > base_length) {

        ret = bdrv_truncate(base, length);

        if (ret < 0) {

            error_setg_errno(errp, -ret,

                            "Top image %s is larger than base image %s, and "

                             "resize of base image failed",

                             bs->filename, base->filename);

            goto error_restore_flags;

        }

    }

    mirror_start_job(job_id, bs, base, NULL, speed, 0, 0,

                     MIRROR_LEAVE_BACKING_CHAIN,

                     on_error, on_error, false, cb, opaque, &local_err,

                     &commit_active_job_driver, false, base);

    if (local_err) {

        error_propagate(errp, local_err);

        goto error_restore_flags;

    }

    return;

error_restore_flags:

    /* ignore error and errp for bdrv_reopen, because we want to propagate

     * the original error */

    bdrv_reopen(base, orig_base_flags, NULL);

    return;

}


static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)

{

    block_acct_start(bdrv_get_stats(req->dev->bs), &req->acct, 0,

                     BLOCK_ACCT_FLUSH);

    /*

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

     */

    virtio_submit_multiwrite(req->dev->bs, mrb);

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

}


static void gen_store_exclusive(DisasContext *s, int rd, int rt, int rt2,

                                TCGv_i64 addr, int size, int is_pair)

{

    /* if (env->exclusive_addr == addr && env->exclusive_val == [addr]

     *     && (!is_pair || env->exclusive_high == [addr + datasize])) {

     *     [addr] = {Rt};

     *     if (is_pair) {

     *         [addr + datasize] = {Rt2};

     *     }

     *     {Rd} = 0;

     * } else {

     *     {Rd} = 1;

     * }

     * env->exclusive_addr = -1;

     */

    TCGLabel *fail_label = gen_new_label();

    TCGLabel *done_label = gen_new_label();

    TCGv_i64 tmp;

    tcg_gen_brcond_i64(TCG_COND_NE, addr, cpu_exclusive_addr, fail_label);

    tmp = tcg_temp_new_i64();

    if (is_pair) {

        if (size == 2) {

            if (s->be_data == MO_LE) {

                tcg_gen_concat32_i64(tmp, cpu_reg(s, rt), cpu_reg(s, rt2));

            } else {

                tcg_gen_concat32_i64(tmp, cpu_reg(s, rt2), cpu_reg(s, rt));

            }

            tcg_gen_atomic_cmpxchg_i64(tmp, cpu_exclusive_addr,

                                       cpu_exclusive_val, tmp,

                                       get_mem_index(s),

                                       MO_64 | MO_ALIGN | s->be_data);

            tcg_gen_setcond_i64(TCG_COND_NE, tmp, tmp, cpu_exclusive_val);

        } else if (s->be_data == MO_LE) {

            gen_helper_paired_cmpxchg64_le(tmp, cpu_env, cpu_exclusive_addr,

                                           cpu_reg(s, rt), cpu_reg(s, rt2));

        } else {

            gen_helper_paired_cmpxchg64_be(tmp, cpu_env, cpu_exclusive_addr,

                                           cpu_reg(s, rt), cpu_reg(s, rt2));

        }

    } else {

        tcg_gen_atomic_cmpxchg_i64(tmp, cpu_exclusive_addr, cpu_exclusive_val,

                                   cpu_reg(s, rt), get_mem_index(s),

                                   size | MO_ALIGN | s->be_data);

        tcg_gen_setcond_i64(TCG_COND_NE, tmp, tmp, cpu_exclusive_val);

    }

    tcg_gen_mov_i64(cpu_reg(s, rd), tmp);

    tcg_temp_free_i64(tmp);

    tcg_gen_br(done_label);

    gen_set_label(fail_label);

    tcg_gen_movi_i64(cpu_reg(s, rd), 1);

    gen_set_label(done_label);

    tcg_gen_movi_i64(cpu_exclusive_addr, -1);

}


void virt_acpi_build(VirtMachineState *vms, AcpiBuildTables *tables)

{

    VirtMachineClass *vmc = VIRT_MACHINE_GET_CLASS(vms);

    GArray *table_offsets;

    unsigned dsdt, rsdt;

    GArray *tables_blob = tables->table_data;

    table_offsets = g_array_new(false, true /* clear */,

                                        sizeof(uint32_t));

    bios_linker_loader_alloc(tables->linker,

                             ACPI_BUILD_TABLE_FILE, tables_blob,

                             64, false /* high memory */);

    /* DSDT is pointed to by FADT */

    dsdt = tables_blob->len;

    build_dsdt(tables_blob, tables->linker, vms);

    /* FADT MADT GTDT MCFG SPCR pointed to by RSDT */

    acpi_add_table(table_offsets, tables_blob);

    build_fadt(tables_blob, tables->linker, vms, dsdt);

    acpi_add_table(table_offsets, tables_blob);

    build_madt(tables_blob, tables->linker, vms);

    acpi_add_table(table_offsets, tables_blob);

    build_gtdt(tables_blob, tables->linker, vms);

    acpi_add_table(table_offsets, tables_blob);

    build_mcfg(tables_blob, tables->linker, vms);

    acpi_add_table(table_offsets, tables_blob);

    build_spcr(tables_blob, tables->linker, vms);

    if (nb_numa_nodes > 0) {

        acpi_add_table(table_offsets, tables_blob);

        build_srat(tables_blob, tables->linker, vms);

    }

    if (its_class_name() && !vmc->no_its) {

        acpi_add_table(table_offsets, tables_blob);

        build_iort(tables_blob, tables->linker);

    }

    /* RSDT is pointed to by RSDP */

    rsdt = tables_blob->len;

    build_rsdt(tables_blob, tables->linker, table_offsets, NULL, NULL);

    /* RSDP is in FSEG memory, so allocate it separately */

    build_rsdp(tables->rsdp, tables->linker, rsdt);

    /* Cleanup memory that's no longer used. */

    g_array_free(table_offsets, true);

}


static void versatile_init(QEMUMachineInitArgs *args, int board_id)

{

    ARMCPU *cpu;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    qemu_irq *cpu_pic;

    qemu_irq pic[32];

    qemu_irq sic[32];

    DeviceState *dev, *sysctl;

    SysBusDevice *busdev;

    DeviceState *pl041;

    PCIBus *pci_bus;

    NICInfo *nd;

    i2c_bus *i2c;

    int n;

    int done_smc = 0;

    DriveInfo *dinfo;

    if (!args->cpu_model) {

        args->cpu_model = "arm926";

    }

    cpu = cpu_arm_init(args->cpu_model);

    if (!cpu) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    memory_region_init_ram(ram, "versatile.ram", args->ram_size);

    vmstate_register_ram_global(ram);

    /* ??? RAM should repeat to fill physical memory space.  */

    /* SDRAM at address zero.  */

    memory_region_add_subregion(sysmem, 0, ram);

    sysctl = qdev_create(NULL, "realview_sysctl");

    qdev_prop_set_uint32(sysctl, "sys_id", 0x41007004);

    qdev_prop_set_uint32(sysctl, "proc_id", 0x02000000);

    qdev_init_nofail(sysctl);

    sysbus_mmio_map(SYS_BUS_DEVICE(sysctl), 0, 0x10000000);

    cpu_pic = arm_pic_init_cpu(cpu);

    dev = sysbus_create_varargs("pl190", 0x10140000,

                                cpu_pic[ARM_PIC_CPU_IRQ],

                                cpu_pic[ARM_PIC_CPU_FIQ], NULL);

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

        pic[n] = qdev_get_gpio_in(dev, n);

    }

    dev = sysbus_create_simple("versatilepb_sic", 0x10003000, NULL);

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

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), n, pic[n]);

        sic[n] = qdev_get_gpio_in(dev, n);

    }

    sysbus_create_simple("pl050_keyboard", 0x10006000, sic[3]);

    sysbus_create_simple("pl050_mouse", 0x10007000, sic[4]);

    dev = qdev_create(NULL, "versatile_pci");

    busdev = SYS_BUS_DEVICE(dev);

    qdev_init_nofail(dev);

    sysbus_mmio_map(busdev, 0, 0x41000000); /* PCI self-config */

    sysbus_mmio_map(busdev, 1, 0x42000000); /* PCI config */

    sysbus_connect_irq(busdev, 0, sic[27]);

    sysbus_connect_irq(busdev, 1, sic[28]);

    sysbus_connect_irq(busdev, 2, sic[29]);

    sysbus_connect_irq(busdev, 3, sic[30]);

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci");

    /* The Versatile PCI bridge does not provide access to PCI IO space,

       so many of the qemu PCI devices are not useable.  */

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

        nd = &nd_table[n];

        if (!done_smc && (!nd->model || strcmp(nd->model, "smc91c111") == 0)) {

            smc91c111_init(nd, 0x10010000, sic[25]);

            done_smc = 1;

        } else {

            pci_nic_init_nofail(nd, "rtl8139", NULL);

        }

    }

    if (usb_enabled(false)) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

    }

    n = drive_get_max_bus(IF_SCSI);

    while (n >= 0) {

        pci_create_simple(pci_bus, -1, "lsi53c895a");

        n--;

    }

    sysbus_create_simple("pl011", 0x101f1000, pic[12]);

    sysbus_create_simple("pl011", 0x101f2000, pic[13]);

    sysbus_create_simple("pl011", 0x101f3000, pic[14]);

    sysbus_create_simple("pl011", 0x10009000, sic[6]);

    sysbus_create_simple("pl080", 0x10130000, pic[17]);

    sysbus_create_simple("sp804", 0x101e2000, pic[4]);

    sysbus_create_simple("sp804", 0x101e3000, pic[5]);

    sysbus_create_simple("pl061", 0x101e4000, pic[6]);

    sysbus_create_simple("pl061", 0x101e5000, pic[7]);

    sysbus_create_simple("pl061", 0x101e6000, pic[8]);

    sysbus_create_simple("pl061", 0x101e7000, pic[9]);

    /* The versatile/PB actually has a modified Color LCD controller

       that includes hardware cursor support from the PL111.  */

    dev = sysbus_create_simple("pl110_versatile", 0x10120000, pic[16]);

    /* Wire up the mux control signals from the SYS_CLCD register */

    qdev_connect_gpio_out(sysctl, 0, qdev_get_gpio_in(dev, 0));

    sysbus_create_varargs("pl181", 0x10005000, sic[22], sic[1], NULL);

    sysbus_create_varargs("pl181", 0x1000b000, sic[23], sic[2], NULL);

    /* Add PL031 Real Time Clock. */

    sysbus_create_simple("pl031", 0x101e8000, pic[10]);

    dev = sysbus_create_simple("versatile_i2c", 0x10002000, NULL);

    i2c = (i2c_bus *)qdev_get_child_bus(dev, "i2c");

    i2c_create_slave(i2c, "ds1338", 0x68);

    /* Add PL041 AACI Interface to the LM4549 codec */

    pl041 = qdev_create(NULL, "pl041");

    qdev_prop_set_uint32(pl041, "nc_fifo_depth", 512);

    qdev_init_nofail(pl041);

    sysbus_mmio_map(SYS_BUS_DEVICE(pl041), 0, 0x10004000);

    sysbus_connect_irq(SYS_BUS_DEVICE(pl041), 0, sic[24]);

    /* Memory map for Versatile/PB:  */

    /* 0x10000000 System registers.  */

    /* 0x10001000 PCI controller config registers.  */

    /* 0x10002000 Serial bus interface.  */

    /*  0x10003000 Secondary interrupt controller.  */

    /* 0x10004000 AACI (audio).  */

    /*  0x10005000 MMCI0.  */

    /*  0x10006000 KMI0 (keyboard).  */

    /*  0x10007000 KMI1 (mouse).  */

    /* 0x10008000 Character LCD Interface.  */

    /*  0x10009000 UART3.  */

    /* 0x1000a000 Smart card 1.  */

    /*  0x1000b000 MMCI1.  */

    /*  0x10010000 Ethernet.  */

    /* 0x10020000 USB.  */

    /* 0x10100000 SSMC.  */

    /* 0x10110000 MPMC.  */

    /*  0x10120000 CLCD Controller.  */

    /*  0x10130000 DMA Controller.  */

    /*  0x10140000 Vectored interrupt controller.  */

    /* 0x101d0000 AHB Monitor Interface.  */

    /* 0x101e0000 System Controller.  */

    /* 0x101e1000 Watchdog Interface.  */

    /* 0x101e2000 Timer 0/1.  */

    /* 0x101e3000 Timer 2/3.  */

    /* 0x101e4000 GPIO port 0.  */

    /* 0x101e5000 GPIO port 1.  */

    /* 0x101e6000 GPIO port 2.  */

    /* 0x101e7000 GPIO port 3.  */

    /* 0x101e8000 RTC.  */

    /* 0x101f0000 Smart card 0.  */

    /*  0x101f1000 UART0.  */

    /*  0x101f2000 UART1.  */

    /*  0x101f3000 UART2.  */

    /* 0x101f4000 SSPI.  */

    /* 0x34000000 NOR Flash */

    dinfo = drive_get(IF_PFLASH, 0, 0);

    if (!pflash_cfi01_register(VERSATILE_FLASH_ADDR, NULL, "versatile.flash",

                          VERSATILE_FLASH_SIZE, dinfo ? dinfo->bdrv : NULL,

                          VERSATILE_FLASH_SECT_SIZE,

                          VERSATILE_FLASH_SIZE / VERSATILE_FLASH_SECT_SIZE,

                          4, 0x0089, 0x0018, 0x0000, 0x0, 0)) {

        fprintf(stderr, "qemu: Error registering flash memory.\n");

    }

    versatile_binfo.ram_size = args->ram_size;

    versatile_binfo.kernel_filename = args->kernel_filename;

    versatile_binfo.kernel_cmdline = args->kernel_cmdline;

    versatile_binfo.initrd_filename = args->initrd_filename;

    versatile_binfo.board_id = board_id;

    arm_load_kernel(cpu, &versatile_binfo);

}


static int interp(RA144Context *ractx, int16_t *out, int block_num,

                  int copyold, int energy)

{

    int work[10];

    int a = block_num + 1;

    int b = NBLOCKS - a;

    int x;

    // Interpolate block coefficients from the this frame forth block and

    // last frame forth block

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

        out[x] = (a * ractx->lpc_coef[0][x] + b * ractx->lpc_coef[1][x])>> 2;

    if (eval_refl(work, out, ractx)) {

        // The interpolated coefficients are unstable, copy either new or old

        // coefficients

        int_to_int16(out, ractx->lpc_coef[copyold]);

        return rescale_rms(ractx->lpc_refl_rms[copyold], energy);

    } else {

        return rescale_rms(rms(work), energy);

    }

}


sorecvfrom(so)

	struct socket *so;

{

	struct sockaddr_in addr;

	int addrlen = sizeof(struct sockaddr_in);

	DEBUG_CALL("sorecvfrom");

	DEBUG_ARG("so = %lx", (long)so);

	if (so->so_type == IPPROTO_ICMP) {   /* This is a "ping" reply */

	  char buff[256];

	  int len;

	  len = recvfrom(so->s, buff, 256, 0,

			 (struct sockaddr *)&addr, &addrlen);

	  /* XXX Check if reply is "correct"? */

	  if(len == -1 || len == 0) {

	    u_char code=ICMP_UNREACH_PORT;

	    if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;

	    else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;

	    DEBUG_MISC((dfd," udp icmp rx errno = %d-%s\n",

			errno,strerror(errno)));

	    icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));

	  } else {

	    icmp_reflect(so->so_m);

	    so->so_m = 0; /* Don't m_free() it again! */

	  }

	  /* No need for this socket anymore, udp_detach it */

	  udp_detach(so);

	} else {                            	/* A "normal" UDP packet */

	  struct mbuf *m;

	  int len, n;

	  if (!(m = m_get())) return;

	  m->m_data += IF_MAXLINKHDR;

	  /*

	   * XXX Shouldn't FIONREAD packets destined for port 53,

	   * but I don't know the max packet size for DNS lookups

	   */

	  len = M_FREEROOM(m);

	  /* if (so->so_fport != htons(53)) { */

	  ioctlsocket(so->s, FIONREAD, &n);

	  if (n > len) {

	    n = (m->m_data - m->m_dat) + m->m_len + n + 1;

	    m_inc(m, n);

	    len = M_FREEROOM(m);

	  }

	  /* } */

	  m->m_len = recvfrom(so->s, m->m_data, len, 0,

			      (struct sockaddr *)&addr, &addrlen);

	  DEBUG_MISC((dfd, " did recvfrom %d, errno = %d-%s\n",

		      m->m_len, errno,strerror(errno)));

	  if(m->m_len<0) {

	    u_char code=ICMP_UNREACH_PORT;

	    if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;

	    else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;

	    DEBUG_MISC((dfd," rx error, tx icmp ICMP_UNREACH:%i\n", code));

	    icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));

	    m_free(m);

	  } else {

	  /*

	   * Hack: domain name lookup will be used the most for UDP,

	   * and since they'll only be used once there's no need

	   * for the 4 minute (or whatever) timeout... So we time them

	   * out much quicker (10 seconds  for now...)

	   */

	    if (so->so_expire) {

	      if (so->so_fport == htons(53))

		so->so_expire = curtime + SO_EXPIREFAST;

	      else

		so->so_expire = curtime + SO_EXPIRE;

	    }

	    /*		if (m->m_len == len) {

	     *			m_inc(m, MINCSIZE);

	     *			m->m_len = 0;

	     *		}

	     */

	    /*

	     * If this packet was destined for CTL_ADDR,

	     * make it look like that's where it came from, done by udp_output

	     */

	    udp_output(so, m, &addr);

	  } /* rx error */

	} /* if ping packet */

}


char *qmp_human_monitor_command(const char *command_line, bool has_cpu_index,

                                int64_t cpu_index, Error **errp)

{

    char *output = NULL;

    Monitor *old_mon, hmp;

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

    hmp.outbuf = qstring_new();

    hmp.skip_flush = true;

    old_mon = cur_mon;

    cur_mon = &hmp;

    if (has_cpu_index) {

        int ret = monitor_set_cpu(cpu_index);

        if (ret < 0) {

            cur_mon = old_mon;

            error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",

                      "a CPU number");

            goto out;

        }

    }

    handle_user_command(&hmp, command_line);

    cur_mon = old_mon;

    if (qstring_get_length(hmp.outbuf) > 0) {

        output = g_strdup(qstring_get_str(hmp.outbuf));

    } else {

        output = g_strdup("");

    }

out:

    QDECREF(hmp.outbuf);

    return output;

}


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

{

    if (argc != 2) {

        help_cmd(argv[0]);

        return;

    }

    vga_screen_dump(argv[1]);

}


static int rndis_get_response(USBNetState *s, uint8_t *buf)

{

    int ret = 0;

    struct rndis_response *r = s->rndis_resp.tqh_first;

    if (!r)

        return ret;

    TAILQ_REMOVE(&s->rndis_resp, r, entries);

    ret = r->length;

    memcpy(buf, r->buf, r->length);

    qemu_free(r);

    return ret;

}


START_TEST(single_quote_string)

{

    int i;

    struct {

        const char *encoded;

        const char *decoded;

    } test_cases[] = {

        { "'hello world'", "hello world" },

        { "'the quick brown fox \\' jumped over the fence'",

          "the quick brown fox ' jumped over the fence" },

        {}

    };

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

        QObject *obj;

        QString *str;

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

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QSTRING);

        str = qobject_to_qstring(obj);

        fail_unless(strcmp(qstring_get_str(str), test_cases[i].decoded) == 0);

        QDECREF(str);

    }

}


static inline void compute_hflags(CPUMIPSState *env)

{

    env->hflags &= ~(MIPS_HFLAG_COP1X | MIPS_HFLAG_64 | MIPS_HFLAG_CP0 |

                     MIPS_HFLAG_F64 | MIPS_HFLAG_FPU | MIPS_HFLAG_KSU |

                     MIPS_HFLAG_UX);

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

        !(env->CP0_Status & (1 << CP0St_ERL)) &&

        !(env->hflags & MIPS_HFLAG_DM)) {

        env->hflags |= (env->CP0_Status >> CP0St_KSU) & MIPS_HFLAG_KSU;

    }

#if defined(TARGET_MIPS64)

    if (((env->hflags & MIPS_HFLAG_KSU) != MIPS_HFLAG_UM) ||

        (env->CP0_Status & (1 << CP0St_PX)) ||

        (env->CP0_Status & (1 << CP0St_UX))) {

        env->hflags |= MIPS_HFLAG_64;

    }

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

        env->hflags |= MIPS_HFLAG_UX;

    }

#endif

    if ((env->CP0_Status & (1 << CP0St_CU0)) ||

        !(env->hflags & MIPS_HFLAG_KSU)) {

        env->hflags |= MIPS_HFLAG_CP0;

    }

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

        env->hflags |= MIPS_HFLAG_FPU;

    }

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

        env->hflags |= MIPS_HFLAG_F64;

    }

    if (env->insn_flags & ISA_MIPS32R2) {

        if (env->active_fpu.fcr0 & (1 << FCR0_F64)) {

            env->hflags |= MIPS_HFLAG_COP1X;

        }

    } else if (env->insn_flags & ISA_MIPS32) {

        if (env->hflags & MIPS_HFLAG_64) {

            env->hflags |= MIPS_HFLAG_COP1X;

        }

    } else if (env->insn_flags & ISA_MIPS4) {

        /* All supported MIPS IV CPUs use the XX (CU3) to enable

           and disable the MIPS IV extensions to the MIPS III ISA.

           Some other MIPS IV CPUs ignore the bit, so the check here

           would be too restrictive for them.  */

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

            env->hflags |= MIPS_HFLAG_COP1X;

        }

    }

}


static void handle_9p_output(VirtIODevice *vdev, VirtQueue *vq)

{

    V9fsVirtioState *v = (V9fsVirtioState *)vdev;

    V9fsState *s = &v->state;

    V9fsPDU *pdu;

    ssize_t len;

    while ((pdu = pdu_alloc(s))) {

        struct {

            uint32_t size_le;

            uint8_t id;

            uint16_t tag_le;

        } QEMU_PACKED out;

        VirtQueueElement *elem = &v->elems[pdu->idx];

        len = virtqueue_pop(vq, elem);

        if (!len) {

            pdu_free(pdu);

            break;

        }

        BUG_ON(elem->out_num == 0 || elem->in_num == 0);

        QEMU_BUILD_BUG_ON(sizeof out != 7);

        len = iov_to_buf(elem->out_sg, elem->out_num, 0,

                         &out, sizeof out);

        BUG_ON(len != sizeof out);

        pdu->size = le32_to_cpu(out.size_le);

        pdu->id = out.id;

        pdu->tag = le16_to_cpu(out.tag_le);

        qemu_co_queue_init(&pdu->complete);

        pdu_submit(pdu);

    }

}


hwaddr ppc_hash64_get_phys_page_debug(CPUPPCState *env, target_ulong addr)

{

    struct mmu_ctx_hash64 ctx;

    if (unlikely(ppc_hash64_get_physical_address(env, &ctx, addr, 0, ACCESS_INT)

                 != 0)) {

        return -1;

    }

    return ctx.raddr & TARGET_PAGE_MASK;

}


int ff_framesync_request_frame(FFFrameSync *fs, AVFilterLink *outlink)

{

    AVFilterContext *ctx = outlink->src;

    int input, ret;

    if ((ret = ff_framesync_process_frame(fs, 0)) < 0)

        return ret;

    if (ret > 0)

        return 0;

    if (fs->eof)

        return AVERROR_EOF;

    input = fs->in_request;

    ret = ff_request_frame(ctx->inputs[input]);

    if (ret == AVERROR_EOF) {

        if ((ret = ff_framesync_add_frame(fs, input, NULL)) < 0)

            return ret;

        if ((ret = ff_framesync_process_frame(fs, 0)) < 0)

            return ret;

        ret = 0;

    }

    return ret;

}


int pcilg_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2)

{

    CPUS390XState *env = &cpu->env;

    S390PCIBusDevice *pbdev;

    uint64_t offset;

    uint64_t data;

    uint8_t len;

    uint32_t fh;

    uint8_t pcias;

    cpu_synchronize_state(CPU(cpu));

    if (env->psw.mask & PSW_MASK_PSTATE) {

        program_interrupt(env, PGM_PRIVILEGED, 4);

        return 0;

    }

    if (r2 & 0x1) {

        program_interrupt(env, PGM_SPECIFICATION, 4);

        return 0;

    }

    fh = env->regs[r2] >> 32;

    pcias = (env->regs[r2] >> 16) & 0xf;

    len = env->regs[r2] & 0xf;

    offset = env->regs[r2 + 1];

    pbdev = s390_pci_find_dev_by_fh(fh);

    if (!pbdev || !(pbdev->fh & FH_MASK_ENABLE)) {

        DPRINTF("pcilg no pci dev\n");

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    }

    if (pbdev->lgstg_blocked) {

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r2, ZPCI_PCI_ST_BLOCKED);

        return 0;

    }

    if (pcias < 6) {

        if ((8 - (offset & 0x7)) < len) {

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

        MemoryRegion *mr = pbdev->pdev->io_regions[pcias].memory;

        memory_region_dispatch_read(mr, offset, &data, len,

                                    MEMTXATTRS_UNSPECIFIED);

    } else if (pcias == 15) {

        if ((4 - (offset & 0x3)) < len) {

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

        data =  pci_host_config_read_common(

                   pbdev->pdev, offset, pci_config_size(pbdev->pdev), len);

        switch (len) {

        case 1:

            break;

        case 2:

            data = bswap16(data);

            break;

        case 4:

            data = bswap32(data);

            break;

        case 8:

            data = bswap64(data);

            break;

        default:

            program_interrupt(env, PGM_OPERAND, 4);

            return 0;

        }

    } else {

        DPRINTF("invalid space\n");

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r2, ZPCI_PCI_ST_INVAL_AS);

        return 0;

    }

    env->regs[r1] = data;

    setcc(cpu, ZPCI_PCI_LS_OK);

    return 0;

}


static Jpeg2000TgtNode *ff_jpeg2000_tag_tree_init(int w, int h)

{

    int pw = w, ph = h;

    Jpeg2000TgtNode *res, *t, *t2;

    int32_t tt_size;

    tt_size = tag_tree_size(w, h);

    if (tt_size == -1)

        return NULL;

    t = res = av_mallocz_array(tt_size, sizeof(*t));

    if (!res)

        return NULL;

    while (w > 1 || h > 1) {

        int i, j;

        pw = w;

        ph = h;

        w  = (w + 1) >> 1;

        h  = (h + 1) >> 1;

        t2 = t + pw * ph;

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

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

                t[i * pw + j].parent = &t2[(i >> 1) * w + (j >> 1)];

        t = t2;

    }

    t[0].parent = NULL;

    return res;

}


int kvm_arch_put_registers(CPUState *cs, int level)

{

    struct kvm_one_reg reg;

    uint32_t fpr;

    uint64_t val;

    int i;

    int ret;

    ARMCPU *cpu = ARM_CPU(cs);

    CPUARMState *env = &cpu->env;

    /* If we are in AArch32 mode then we need to copy the AArch32 regs to the

     * AArch64 registers before pushing them out to 64-bit KVM.

     */

    if (!is_a64(env)) {

        aarch64_sync_32_to_64(env);

    }

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

        reg.id = AARCH64_CORE_REG(regs.regs[i]);

        reg.addr = (uintptr_t) &env->xregs[i];

        ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

        if (ret) {

            return ret;

        }

    }

    /* KVM puts SP_EL0 in regs.sp and SP_EL1 in regs.sp_el1. On the

     * QEMU side we keep the current SP in xregs[31] as well.

     */

    aarch64_save_sp(env, 1);

    reg.id = AARCH64_CORE_REG(regs.sp);

    reg.addr = (uintptr_t) &env->sp_el[0];

    ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

    if (ret) {

        return ret;

    }

    reg.id = AARCH64_CORE_REG(sp_el1);

    reg.addr = (uintptr_t) &env->sp_el[1];

    ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

    if (ret) {

        return ret;

    }

    /* Note that KVM thinks pstate is 64 bit but we use a uint32_t */

    if (is_a64(env)) {

        val = pstate_read(env);

    } else {

        val = cpsr_read(env);

    }

    reg.id = AARCH64_CORE_REG(regs.pstate);

    reg.addr = (uintptr_t) &val;

    ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

    if (ret) {

        return ret;

    }

    reg.id = AARCH64_CORE_REG(regs.pc);

    reg.addr = (uintptr_t) &env->pc;

    ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

    if (ret) {

        return ret;

    }

    reg.id = AARCH64_CORE_REG(elr_el1);

    reg.addr = (uintptr_t) &env->elr_el[1];

    ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

    if (ret) {

        return ret;

    }

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

        reg.id = AARCH64_CORE_REG(spsr[i]);

        reg.addr = (uintptr_t) &env->banked_spsr[i - 1];

        ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

        if (ret) {

            return ret;

        }

    }

    /* Advanced SIMD and FP registers

     * We map Qn = regs[2n+1]:regs[2n]

     */

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

        int rd = i << 1;

        uint64_t fp_val[2];

#ifdef HOST_WORDS_BIGENDIAN

        fp_val[0] = env->vfp.regs[rd + 1];

        fp_val[1] = env->vfp.regs[rd];

#else

        fp_val[1] = env->vfp.regs[rd + 1];

        fp_val[0] = env->vfp.regs[rd];

#endif

        reg.id = AARCH64_SIMD_CORE_REG(fp_regs.vregs[i]);

        reg.addr = (uintptr_t)(&fp_val);

        ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

        if (ret) {

            return ret;

        }

    }

    reg.addr = (uintptr_t)(&fpr);

    fpr = vfp_get_fpsr(env);

    reg.id = AARCH64_SIMD_CTRL_REG(fp_regs.fpsr);

    ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

    if (ret) {

        return ret;

    }

    fpr = vfp_get_fpcr(env);

    reg.id = AARCH64_SIMD_CTRL_REG(fp_regs.fpcr);

    ret = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);

    if (ret) {

        return ret;

    }

    if (!write_list_to_kvmstate(cpu)) {

        return EINVAL;

    }

    kvm_arm_sync_mpstate_to_kvm(cpu);

    return ret;

}


static void sdl_refresh(DisplayState *ds)

{

    SDL_Event ev1, *ev = &ev1;

    int mod_state;

    int buttonstate = SDL_GetMouseState(NULL, NULL);

    if (last_vm_running != vm_running) {

        last_vm_running = vm_running;

        sdl_update_caption();

    }

    vga_hw_update();

    SDL_EnableUNICODE(!is_graphic_console());

    while (SDL_PollEvent(ev)) {

        switch (ev->type) {

        case SDL_VIDEOEXPOSE:

            sdl_update(ds, 0, 0, screen->w, screen->h);

            break;

        case SDL_KEYDOWN:

        case SDL_KEYUP:

            if (ev->type == SDL_KEYDOWN) {

                if (!alt_grab) {

                    mod_state = (SDL_GetModState() & gui_grab_code) ==

                                gui_grab_code;

                } else {

                    mod_state = (SDL_GetModState() & (gui_grab_code | KMOD_LSHIFT)) ==

                                (gui_grab_code | KMOD_LSHIFT);

                }

                gui_key_modifier_pressed = mod_state;

                if (gui_key_modifier_pressed) {

                    int keycode;

                    keycode = sdl_keyevent_to_keycode(&ev->key);

                    switch(keycode) {

                    case 0x21: /* 'f' key on US keyboard */

                        toggle_full_screen(ds);

                        gui_keysym = 1;

                        break;

                    case 0x02 ... 0x0a: /* '1' to '9' keys */

                        /* Reset the modifiers sent to the current console */

                        reset_keys();

                        console_select(keycode - 0x02);

                        if (!is_graphic_console()) {

                            /* display grab if going to a text console */

                            if (gui_grab)

                                sdl_grab_end();

                        }

                        gui_keysym = 1;

                        break;

                    default:

                        break;

                    }

                } else if (!is_graphic_console()) {

                    int keysym;

                    keysym = 0;

                    if (ev->key.keysym.mod & (KMOD_LCTRL | KMOD_RCTRL)) {

                        switch(ev->key.keysym.sym) {

                        case SDLK_UP: keysym = QEMU_KEY_CTRL_UP; break;

                        case SDLK_DOWN: keysym = QEMU_KEY_CTRL_DOWN; break;

                        case SDLK_LEFT: keysym = QEMU_KEY_CTRL_LEFT; break;

                        case SDLK_RIGHT: keysym = QEMU_KEY_CTRL_RIGHT; break;

                        case SDLK_HOME: keysym = QEMU_KEY_CTRL_HOME; break;

                        case SDLK_END: keysym = QEMU_KEY_CTRL_END; break;

                        case SDLK_PAGEUP: keysym = QEMU_KEY_CTRL_PAGEUP; break;

                        case SDLK_PAGEDOWN: keysym = QEMU_KEY_CTRL_PAGEDOWN; break;

                        default: break;

                        }

                    } else {

                        switch(ev->key.keysym.sym) {

                        case SDLK_UP: keysym = QEMU_KEY_UP; break;

                        case SDLK_DOWN: keysym = QEMU_KEY_DOWN; break;

                        case SDLK_LEFT: keysym = QEMU_KEY_LEFT; break;

                        case SDLK_RIGHT: keysym = QEMU_KEY_RIGHT; break;

                        case SDLK_HOME: keysym = QEMU_KEY_HOME; break;

                        case SDLK_END: keysym = QEMU_KEY_END; break;

                        case SDLK_PAGEUP: keysym = QEMU_KEY_PAGEUP; break;

                        case SDLK_PAGEDOWN: keysym = QEMU_KEY_PAGEDOWN; break;

                        case SDLK_BACKSPACE: keysym = QEMU_KEY_BACKSPACE; break;

                        case SDLK_DELETE: keysym = QEMU_KEY_DELETE; break;

                        default: break;

                        }

                    }

                    if (keysym) {

                        kbd_put_keysym(keysym);

                    } else if (ev->key.keysym.unicode != 0) {

                        kbd_put_keysym(ev->key.keysym.unicode);

                    }

                }

            } else if (ev->type == SDL_KEYUP) {

                if (!alt_grab) {

                    mod_state = (ev->key.keysym.mod & gui_grab_code);

                } else {

                    mod_state = (ev->key.keysym.mod &

                                 (gui_grab_code | KMOD_LSHIFT));

                }

                if (!mod_state) {

                    if (gui_key_modifier_pressed) {

                        gui_key_modifier_pressed = 0;

                        if (gui_keysym == 0) {

                            /* exit/enter grab if pressing Ctrl-Alt */

                            if (!gui_grab) {

                                /* if the application is not active,

                                   do not try to enter grab state. It

                                   prevents

                                   'SDL_WM_GrabInput(SDL_GRAB_ON)'

                                   from blocking all the application

                                   (SDL bug). */

                                if (SDL_GetAppState() & SDL_APPACTIVE)

                                    sdl_grab_start();

                            } else {

                                sdl_grab_end();

                            }

                            /* SDL does not send back all the

                               modifiers key, so we must correct it */

                            reset_keys();

                            break;

                        }

                        gui_keysym = 0;

                    }

                }

            }

            if (is_graphic_console() && !gui_keysym)

                sdl_process_key(&ev->key);

            break;

        case SDL_QUIT:

            if (!no_quit) {

                qemu_system_shutdown_request();

                vm_start();	/* In case we're paused */

            }

            break;

        case SDL_MOUSEMOTION:

            if (gui_grab || kbd_mouse_is_absolute() ||

                absolute_enabled) {

                sdl_send_mouse_event(ev->motion.xrel, ev->motion.yrel, 0,

                       ev->motion.x, ev->motion.y, ev->motion.state);

            }

            break;

        case SDL_MOUSEBUTTONDOWN:

        case SDL_MOUSEBUTTONUP:

            {

                SDL_MouseButtonEvent *bev = &ev->button;

                if (!gui_grab && !kbd_mouse_is_absolute()) {

                    if (ev->type == SDL_MOUSEBUTTONDOWN &&

                        (bev->button == SDL_BUTTON_LEFT)) {

                        /* start grabbing all events */

                        sdl_grab_start();

                    }

                } else {

                    int dz;

                    dz = 0;

                    if (ev->type == SDL_MOUSEBUTTONDOWN) {

                        buttonstate |= SDL_BUTTON(bev->button);

                    } else {

                        buttonstate &= ~SDL_BUTTON(bev->button);

                    }

#ifdef SDL_BUTTON_WHEELUP

                    if (bev->button == SDL_BUTTON_WHEELUP && ev->type == SDL_MOUSEBUTTONDOWN) {

                        dz = -1;

                    } else if (bev->button == SDL_BUTTON_WHEELDOWN && ev->type == SDL_MOUSEBUTTONDOWN) {

                        dz = 1;

                    }

#endif

                    sdl_send_mouse_event(0, 0, dz, bev->x, bev->y, buttonstate);

                }

            }

            break;

        case SDL_ACTIVEEVENT:

            if (gui_grab && ev->active.state == SDL_APPINPUTFOCUS &&

                !ev->active.gain && !gui_fullscreen_initial_grab) {

                sdl_grab_end();

            }

            if (ev->active.state & SDL_APPACTIVE) {

                if (ev->active.gain) {

                    /* Back to default interval */

                    ds->gui_timer_interval = 0;

                } else {

                    /* Sleeping interval */

                    ds->gui_timer_interval = 500;

                }

            }

            break;

        default:

            break;

        }

    }

}


static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,

                                   size_t size)

{

    int64_t len;

    if (size > INT_MAX) {

        return -EIO;

    }

    if (!bdrv_is_inserted(bs))

        return -ENOMEDIUM;

    if (bs->growable)

        return 0;

    len = bdrv_getlength(bs);

    if (offset < 0)

        return -EIO;

    if ((offset > len) || (len - offset < size))

        return -EIO;

    return 0;

}


static int planarRgb16ToRgb16Wrapper(SwsContext *c, const uint8_t *src[],

                                     int srcStride[], int srcSliceY, int srcSliceH,

                                     uint8_t *dst[], int dstStride[])

{

    const uint16_t *src102[] = { (uint16_t *)src[1], (uint16_t *)src[0], (uint16_t *)src[2] };

    const uint16_t *src201[] = { (uint16_t *)src[2], (uint16_t *)src[0], (uint16_t *)src[1] };

    int stride102[] = { srcStride[1], srcStride[0], srcStride[2] };

    int stride201[] = { srcStride[2], srcStride[0], srcStride[1] };

    const AVPixFmtDescriptor *src_format = av_pix_fmt_desc_get(c->srcFormat);

    const AVPixFmtDescriptor *dst_format = av_pix_fmt_desc_get(c->dstFormat);

    int bits_per_sample = src_format->comp[0].depth_minus1 + 1;

    int swap = 0;

    if ( HAVE_BIGENDIAN && !(src_format->flags & AV_PIX_FMT_FLAG_BE) ||

        !HAVE_BIGENDIAN &&   src_format->flags & AV_PIX_FMT_FLAG_BE)

        swap++;

    if ( HAVE_BIGENDIAN && !(dst_format->flags & AV_PIX_FMT_FLAG_BE) ||

        !HAVE_BIGENDIAN &&   dst_format->flags & AV_PIX_FMT_FLAG_BE)

        swap += 2;

    if ((src_format->flags & (AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB)) !=

        (AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB)) {

        av_log(c, AV_LOG_ERROR, "unsupported planar RGB conversion %s -> %s\n",

               src_format->name, dst_format->name);

        return srcSliceH;

    }

    switch (c->dstFormat) {

    case AV_PIX_FMT_BGR48LE:

    case AV_PIX_FMT_BGR48BE:

        gbr16ptopacked16(src102, stride102,

                         dst[0] + srcSliceY * dstStride[0], dstStride[0],

                         srcSliceH, 0, swap, bits_per_sample, c->srcW);

        break;

    case AV_PIX_FMT_RGB48LE:

    case AV_PIX_FMT_RGB48BE:

        gbr16ptopacked16(src201, stride201,

                         dst[0] + srcSliceY * dstStride[0], dstStride[0],

                         srcSliceH, 0, swap, bits_per_sample, c->srcW);

        break;

    case AV_PIX_FMT_RGBA64LE:

    case AV_PIX_FMT_RGBA64BE:

         gbr16ptopacked16(src201, stride201,

                          dst[0] + srcSliceY * dstStride[0], dstStride[0],

                          srcSliceH, 1, swap, bits_per_sample, c->srcW);

        break;

    case AV_PIX_FMT_BGRA64LE:

    case AV_PIX_FMT_BGRA64BE:

        gbr16ptopacked16(src102, stride102,

                         dst[0] + srcSliceY * dstStride[0], dstStride[0],

                         srcSliceH, 1, swap, bits_per_sample, c->srcW);

        break;

    default:

        av_log(c, AV_LOG_ERROR,

               "unsupported planar RGB conversion %s -> %s\n",

               src_format->name, dst_format->name);

    }

    return srcSliceH;

}


void put_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h)

{

POWERPC_TBL_DECLARE(altivec_put_pixels16_num, 1);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

    int i;

POWERPC_TBL_START_COUNT(altivec_put_pixels16_num, 1);

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

      *((uint32_t*)(block )) = (((const struct unaligned_32 *) (pixels))->l);

      *((uint32_t*)(block+4)) = (((const struct unaligned_32 *) (pixels+4))->l);

      *((uint32_t*)(block+8)) = (((const struct unaligned_32 *) (pixels+8))->l);

      *((uint32_t*)(block+12)) = (((const struct unaligned_32 *) (pixels+12))->l);

      pixels+=line_size;

      block +=line_size;

    }

POWERPC_TBL_STOP_COUNT(altivec_put_pixels16_num, 1);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

    register vector unsigned char pixelsv1, pixelsv2;

    register vector unsigned char perm = vec_lvsl(0, pixels);

    int i;

POWERPC_TBL_START_COUNT(altivec_put_pixels16_num, 1);

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

      pixelsv1 = vec_ld(0, (unsigned char*)pixels);

      pixelsv2 = vec_ld(16, (unsigned char*)pixels);

      vec_st(vec_perm(pixelsv1, pixelsv2, perm),

             0, (unsigned char*)block);

      pixels+=line_size;

      block +=line_size;

    }

POWERPC_TBL_STOP_COUNT(altivec_put_pixels16_num, 1);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


static ssize_t vnc_tls_pull(gnutls_transport_ptr_t transport,

                            void *data,

                            size_t len) {

    struct VncState *vs = (struct VncState *)transport;

    int ret;

 retry:

    ret = recv(vs->csock, data, len, 0);

    if (ret < 0) {

	if (errno == EINTR)

	    goto retry;

	return -1;

    }

    return ret;

}


static bool pcie_aer_msg_root_port(PCIDevice *dev, const PCIEAERMsg *msg)

{

    bool msg_sent;

    uint16_t cmd;

    uint8_t *aer_cap;

    uint32_t root_cmd;

    uint32_t root_status;

    bool msi_trigger;

    msg_sent = false;

    cmd = pci_get_word(dev->config + PCI_COMMAND);

    aer_cap = dev->config + dev->exp.aer_cap;

    root_cmd = pci_get_long(aer_cap + PCI_ERR_ROOT_COMMAND);

    root_status = pci_get_long(aer_cap + PCI_ERR_ROOT_STATUS);

    msi_trigger = false;

    if (cmd & PCI_COMMAND_SERR) {

        /* System Error.

         *

         * The way to report System Error is platform specific and

         * it isn't implemented in qemu right now.

         * So just discard the error for now.

         * OS which cares of aer would receive errors via

         * native aer mechanims, so this wouldn't matter.

         */

    }

    /* Errro Message Received: Root Error Status register */

    switch (msg->severity) {

    case PCI_ERR_ROOT_CMD_COR_EN:

        if (root_status & PCI_ERR_ROOT_COR_RCV) {

            root_status |= PCI_ERR_ROOT_MULTI_COR_RCV;

        } else {

            if (root_cmd & PCI_ERR_ROOT_CMD_COR_EN) {

                msi_trigger = true;

            }

            pci_set_word(aer_cap + PCI_ERR_ROOT_COR_SRC, msg->source_id);

        }

        root_status |= PCI_ERR_ROOT_COR_RCV;

        break;

    case PCI_ERR_ROOT_CMD_NONFATAL_EN:

        if (!(root_status & PCI_ERR_ROOT_NONFATAL_RCV) &&

            root_cmd & PCI_ERR_ROOT_CMD_NONFATAL_EN) {

            msi_trigger = true;

        }

        root_status |= PCI_ERR_ROOT_NONFATAL_RCV;

        break;

    case PCI_ERR_ROOT_CMD_FATAL_EN:

        if (!(root_status & PCI_ERR_ROOT_FATAL_RCV) &&

            root_cmd & PCI_ERR_ROOT_CMD_FATAL_EN) {

            msi_trigger = true;

        }

        if (!(root_status & PCI_ERR_ROOT_UNCOR_RCV)) {

            root_status |= PCI_ERR_ROOT_FIRST_FATAL;

        }

        root_status |= PCI_ERR_ROOT_FATAL_RCV;

        break;

    default:

        abort();

        break;

    }

    if (pcie_aer_msg_is_uncor(msg)) {

        if (root_status & PCI_ERR_ROOT_UNCOR_RCV) {

            root_status |= PCI_ERR_ROOT_MULTI_UNCOR_RCV;

        } else {

            pci_set_word(aer_cap + PCI_ERR_ROOT_SRC, msg->source_id);

        }

        root_status |= PCI_ERR_ROOT_UNCOR_RCV;

    }

    pci_set_long(aer_cap + PCI_ERR_ROOT_STATUS, root_status);

    if (root_cmd & msg->severity) {

        /* 6.2.4.1.2 Interrupt Generation */

        if (msix_enabled(dev)) {

            if (msi_trigger) {

                msix_notify(dev, pcie_aer_root_get_vector(dev));

            }

        } else if (msi_enabled(dev)) {

            if (msi_trigger) {

                msi_notify(dev, pcie_aer_root_get_vector(dev));

            }

        } else {

            qemu_set_irq(dev->irq[dev->exp.aer_intx], 1);

        }

        msg_sent = true;

    }

    return msg_sent;

}


static void put_pci_irq_state(QEMUFile *f, void *pv, size_t size)

{

    int i;

    PCIDevice *s = container_of(pv, PCIDevice, config);

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

        qemu_put_be32(f, pci_irq_state(s, i));

    }

}


static void data_plane_blk_remove_notifier(Notifier *n, void *data)

{

    VirtIOBlockDataPlane *s = container_of(n, VirtIOBlockDataPlane,

                                           remove_notifier);

    assert(s->conf->conf.blk == data);

    data_plane_remove_op_blockers(s);

}


static int nbd_co_send_request(NbdClientSession *s,

    struct nbd_request *request,

    QEMUIOVector *qiov, int offset)

{

    AioContext *aio_context;

    int rc, ret;

    qemu_co_mutex_lock(&s->send_mutex);

    s->send_coroutine = qemu_coroutine_self();

    aio_context = bdrv_get_aio_context(s->bs);

    aio_set_fd_handler(aio_context, s->sock,

                       nbd_reply_ready, nbd_restart_write, s);

    if (qiov) {

        if (!s->is_unix) {

            socket_set_cork(s->sock, 1);

        }

        rc = nbd_send_request(s->sock, request);

        if (rc >= 0) {

            ret = qemu_co_sendv(s->sock, qiov->iov, qiov->niov,

                                offset, request->len);

            if (ret != request->len) {

                rc = -EIO;

            }

        }

        if (!s->is_unix) {

            socket_set_cork(s->sock, 0);

        }

    } else {

        rc = nbd_send_request(s->sock, request);

    }

    aio_set_fd_handler(aio_context, s->sock, nbd_reply_ready, NULL, s);

    s->send_coroutine = NULL;

    qemu_co_mutex_unlock(&s->send_mutex);

    return rc;

}


static uint64_t ac97_read(void *opaque, target_phys_addr_t addr,

                          unsigned size)

{

    MilkymistAC97State *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_AC97_CTRL:

    case R_AC97_ADDR:

    case R_AC97_DATAOUT:

    case R_AC97_DATAIN:

    case R_D_CTRL:

    case R_D_ADDR:

    case R_D_REMAINING:

    case R_U_CTRL:

    case R_U_ADDR:

    case R_U_REMAINING:

        r = s->regs[addr];

        break;

    default:

        error_report("milkymist_ac97: read access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_milkymist_ac97_memory_read(addr << 2, r);

    return r;

}


static void spr_write_ibatu_h (void *opaque, int sprn)

{

    DisasContext *ctx = opaque;

    gen_op_store_ibatu((sprn - SPR_IBAT4U) / 2);

    RET_STOP(ctx);

}


static int find_partition(BlockBackend *blk, int partition,

                          off_t *offset, off_t *size)

{

    struct partition_record mbr[4];

    uint8_t data[512];

    int i;

    int ext_partnum = 4;

    int ret;

    if ((ret = blk_read(blk, 0, data, 1)) < 0) {

        error_report("error while reading: %s", strerror(-ret));

        exit(EXIT_FAILURE);

    }

    if (data[510] != 0x55 || data[511] != 0xaa) {

        return -EINVAL;

    }

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

        read_partition(&data[446 + 16 * i], &mbr[i]);

        if (!mbr[i].system || !mbr[i].nb_sectors_abs) {

            continue;

        }

        if (mbr[i].system == 0xF || mbr[i].system == 0x5) {

            struct partition_record ext[4];

            uint8_t data1[512];

            int j;

            if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {

                error_report("error while reading: %s", strerror(-ret));

                exit(EXIT_FAILURE);

            }

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

                read_partition(&data1[446 + 16 * j], &ext[j]);

                if (!ext[j].system || !ext[j].nb_sectors_abs) {

                    continue;

                }

                if ((ext_partnum + j + 1) == partition) {

                    *offset = (uint64_t)ext[j].start_sector_abs << 9;

                    *size = (uint64_t)ext[j].nb_sectors_abs << 9;

                    return 0;

                }

            }

            ext_partnum += 4;

        } else if ((i + 1) == partition) {

            *offset = (uint64_t)mbr[i].start_sector_abs << 9;

            *size = (uint64_t)mbr[i].nb_sectors_abs << 9;

            return 0;

        }

    }

    return -ENOENT;

}


static void sun4m_common_init(int ram_size, int boot_device, DisplayState *ds,

                              const char *kernel_filename, const char *kernel_cmdline,

                              const char *initrd_filename, const char *cpu_model,

                              unsigned int machine, int max_ram)

{

    if ((unsigned int)ram_size > (unsigned int)max_ram) {

        fprintf(stderr, "qemu: Too much memory for this machine: %d, maximum %d\n",

                (unsigned int)ram_size / (1024 * 1024),

                (unsigned int)max_ram / (1024 * 1024));

        exit(1);

    }

    sun4m_hw_init(&hwdefs[machine], ram_size, ds, cpu_model);

    sun4m_load_kernel(hwdefs[machine].vram_size, ram_size, boot_device,

                      kernel_filename, kernel_cmdline, initrd_filename,

                      hwdefs[machine].machine_id);

}


static always_inline void _cpu_ppc_store_hdecr (CPUState *env, uint32_t hdecr,

                                                uint32_t value, int is_excp)

{

    ppc_tb_t *tb_env = env->tb_env;

    __cpu_ppc_store_decr(env, &tb_env->hdecr_next, tb_env->hdecr_timer,

                         &cpu_ppc_hdecr_excp, hdecr, value, is_excp);

}


static int nvdec_vp9_start_frame(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)

{

    VP9SharedContext *h = avctx->priv_data;

    const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);

    NVDECContext      *ctx = avctx->internal->hwaccel_priv_data;

    CUVIDPICPARAMS     *pp = &ctx->pic_params;

    CUVIDVP9PICPARAMS *ppc = &pp->CodecSpecific.vp9;

    FrameDecodeData *fdd;

    NVDECFrame *cf;

    AVFrame *cur_frame = h->frames[CUR_FRAME].tf.f;

    int ret, i;

    ret = ff_nvdec_start_frame(avctx, cur_frame);

    if (ret < 0)

        return ret;

    fdd = (FrameDecodeData*)cur_frame->private_ref->data;

    cf  = (NVDECFrame*)fdd->hwaccel_priv;

    *pp = (CUVIDPICPARAMS) {

        .PicWidthInMbs     = (cur_frame->width  + 15) / 16,

        .FrameHeightInMbs  = (cur_frame->height + 15) / 16,

        .CurrPicIdx        = cf->idx,

        .CodecSpecific.vp9 = {

            .width                    = cur_frame->width,

            .height                   = cur_frame->height,

            .LastRefIdx               = get_ref_idx(h->refs[h->h.refidx[0]].f),

            .GoldenRefIdx             = get_ref_idx(h->refs[h->h.refidx[1]].f),

            .AltRefIdx                = get_ref_idx(h->refs[h->h.refidx[2]].f),

            .profile                  = h->h.profile,

            .frameContextIdx          = h->h.framectxid,

            .frameType                = !h->h.keyframe,

            .showFrame                = !h->h.invisible,

            .errorResilient           = h->h.errorres,

            .frameParallelDecoding    = h->h.parallelmode,

            .subSamplingX             = pixdesc->log2_chroma_w,

            .subSamplingY             = pixdesc->log2_chroma_h,

            .intraOnly                = h->h.intraonly,

            .allow_high_precision_mv  = h->h.keyframe ? 0 : h->h.highprecisionmvs,

            .refreshEntropyProbs      = h->h.refreshctx,

            .bitDepthMinus8Luma       = pixdesc->comp[0].depth - 8,

            .bitDepthMinus8Chroma     = pixdesc->comp[1].depth - 8,

            .loopFilterLevel          = h->h.filter.level,

            .loopFilterSharpness      = h->h.filter.sharpness,

            .modeRefLfEnabled         = h->h.lf_delta.enabled,

            .log2_tile_columns        = h->h.tiling.log2_tile_cols,

            .log2_tile_rows           = h->h.tiling.log2_tile_rows,

            .segmentEnabled           = h->h.segmentation.enabled,

            .segmentMapUpdate         = h->h.segmentation.update_map,

            .segmentMapTemporalUpdate = h->h.segmentation.temporal,

            .segmentFeatureMode       = h->h.segmentation.absolute_vals,

            .qpYAc                    = h->h.yac_qi,

            .qpYDc                    = h->h.ydc_qdelta,

            .qpChDc                   = h->h.uvdc_qdelta,

            .qpChAc                   = h->h.uvac_qdelta,

            .resetFrameContext        = h->h.resetctx,

            .mcomp_filter_type        = h->h.filtermode ^ (h->h.filtermode <= 1),

            .frameTagSize             = h->h.uncompressed_header_size,

            .offsetToDctParts         = h->h.compressed_header_size,

            .refFrameSignBias[0]      = 0,

        }

    };

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

        ppc->mbModeLfDelta[i] = h->h.lf_delta.mode[i];

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

        ppc->mbRefLfDelta[i] = h->h.lf_delta.ref[i];

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

        ppc->mb_segment_tree_probs[i] = h->h.segmentation.prob[i];

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

        ppc->activeRefIdx[i] = h->h.refidx[i];

        ppc->segment_pred_probs[i] = h->h.segmentation.pred_prob[i];

        ppc->refFrameSignBias[i + 1] = h->h.signbias[i];

    }

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

        ppc->segmentFeatureEnable[i][0] = h->h.segmentation.feat[i].q_enabled;

        ppc->segmentFeatureEnable[i][1] = h->h.segmentation.feat[i].lf_enabled;

        ppc->segmentFeatureEnable[i][2] = h->h.segmentation.feat[i].ref_enabled;

        ppc->segmentFeatureEnable[i][3] = h->h.segmentation.feat[i].skip_enabled;

        ppc->segmentFeatureData[i][0] = h->h.segmentation.feat[i].q_val;

        ppc->segmentFeatureData[i][1] = h->h.segmentation.feat[i].lf_val;

        ppc->segmentFeatureData[i][2] = h->h.segmentation.feat[i].ref_val;

        ppc->segmentFeatureData[i][3] = 0;

    }

    switch (avctx->colorspace) {

    default:

    case AVCOL_SPC_UNSPECIFIED:

        ppc->colorSpace = 0;

        break;

    case AVCOL_SPC_BT470BG:

        ppc->colorSpace = 1;

        break;

    case AVCOL_SPC_BT709:

        ppc->colorSpace = 2;

        break;

    case AVCOL_SPC_SMPTE170M:

        ppc->colorSpace = 3;

        break;

    case AVCOL_SPC_SMPTE240M:

        ppc->colorSpace = 4;

        break;

    case AVCOL_SPC_BT2020_NCL:

        ppc->colorSpace = 5;

        break;

    case AVCOL_SPC_RESERVED:

        ppc->colorSpace = 6;

        break;

    case AVCOL_SPC_RGB:

        ppc->colorSpace = 7;

        break;

    }

    return 0;

}


void qmp_disable_command(const char *name)

{

    QmpCommand *cmd;

    QTAILQ_FOREACH(cmd, &qmp_commands, node) {

        if (strcmp(cmd->name, name) == 0) {

            cmd->enabled = false;

            return;

        }

    }

}


static void ref405ep_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    char *filename;

    ppc4xx_bd_info_t bd;

    CPUPPCState *env;

    qemu_irq *pic;

    MemoryRegion *bios;

    MemoryRegion *sram = g_new(MemoryRegion, 1);

    ram_addr_t bdloc;

    MemoryRegion *ram_memories = g_malloc(2 * sizeof(*ram_memories));

    hwaddr ram_bases[2], ram_sizes[2];

    target_ulong sram_size;

    long bios_size;

    //int phy_addr = 0;

    //static int phy_addr = 1;

    target_ulong kernel_base, initrd_base;

    long kernel_size, initrd_size;

    int linux_boot;

    int fl_idx, fl_sectors, len;

    DriveInfo *dinfo;

    MemoryRegion *sysmem = get_system_memory();

    /* XXX: fix this */

    memory_region_allocate_system_memory(&ram_memories[0], NULL, "ef405ep.ram",

                                         0x08000000);

    ram_bases[0] = 0;

    ram_sizes[0] = 0x08000000;

    memory_region_init(&ram_memories[1], NULL, "ef405ep.ram1", 0);

    ram_bases[1] = 0x00000000;

    ram_sizes[1] = 0x00000000;

    ram_size = 128 * 1024 * 1024;

#ifdef DEBUG_BOARD_INIT

    printf("%s: register cpu\n", __func__);

#endif

    env = ppc405ep_init(sysmem, ram_memories, ram_bases, ram_sizes,

                        33333333, &pic, kernel_filename == NULL ? 0 : 1);

    /* allocate SRAM */

    sram_size = 512 * 1024;

    memory_region_init_ram(sram, NULL, "ef405ep.sram", sram_size, &error_abort);

    vmstate_register_ram_global(sram);

    memory_region_add_subregion(sysmem, 0xFFF00000, sram);

    /* allocate and load BIOS */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register BIOS\n", __func__);

#endif

    fl_idx = 0;

#ifdef USE_FLASH_BIOS

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        BlockDriverState *bs = blk_bs(blk_by_legacy_dinfo(dinfo));

        bios_size = bdrv_getlength(bs);

        fl_sectors = (bios_size + 65535) >> 16;

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size %lx"

               " at addr %lx '%s' %d\n",

               fl_idx, bios_size, -bios_size,

               bdrv_get_device_name(bs), fl_sectors);

#endif

        pflash_cfi02_register((uint32_t)(-bios_size),

                              NULL, "ef405ep.bios", bios_size,

                              bs, 65536, fl_sectors, 1,

                              2, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    } else

#endif

    {

#ifdef DEBUG_BOARD_INIT

        printf("Load BIOS from file\n");

#endif

        bios = g_new(MemoryRegion, 1);

        memory_region_init_ram(bios, NULL, "ef405ep.bios", BIOS_SIZE,

                               &error_abort);

        vmstate_register_ram_global(bios);

        if (bios_name == NULL)

            bios_name = BIOS_FILENAME;

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (filename) {

            bios_size = load_image(filename, memory_region_get_ram_ptr(bios));

            g_free(filename);

            if (bios_size < 0 || bios_size > BIOS_SIZE) {

                error_report("Could not load PowerPC BIOS '%s'", bios_name);

                exit(1);

            }

            bios_size = (bios_size + 0xfff) & ~0xfff;

            memory_region_add_subregion(sysmem, (uint32_t)(-bios_size), bios);

        } else if (!qtest_enabled() || kernel_filename != NULL) {

            error_report("Could not load PowerPC BIOS '%s'", bios_name);

            exit(1);

        } else {

            /* Avoid an uninitialized variable warning */

            bios_size = -1;

        }

        memory_region_set_readonly(bios, true);

    }

    /* Register FPGA */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register FPGA\n", __func__);

#endif

    ref405ep_fpga_init(sysmem, 0xF0300000);

    /* Register NVRAM */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register NVRAM\n", __func__);

#endif

    m48t59_init(NULL, 0xF0000000, 0, 8192, 8);

    /* Load kernel */

    linux_boot = (kernel_filename != NULL);

    if (linux_boot) {

#ifdef DEBUG_BOARD_INIT

        printf("%s: load kernel\n", __func__);

#endif

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

        bd.bi_memstart = 0x00000000;

        bd.bi_memsize = ram_size;

        bd.bi_flashstart = -bios_size;

        bd.bi_flashsize = -bios_size;

        bd.bi_flashoffset = 0;

        bd.bi_sramstart = 0xFFF00000;

        bd.bi_sramsize = sram_size;

        bd.bi_bootflags = 0;

        bd.bi_intfreq = 133333333;

        bd.bi_busfreq = 33333333;

        bd.bi_baudrate = 115200;

        bd.bi_s_version[0] = 'Q';

        bd.bi_s_version[1] = 'M';

        bd.bi_s_version[2] = 'U';

        bd.bi_s_version[3] = '\0';

        bd.bi_r_version[0] = 'Q';

        bd.bi_r_version[1] = 'E';

        bd.bi_r_version[2] = 'M';

        bd.bi_r_version[3] = 'U';

        bd.bi_r_version[4] = '\0';

        bd.bi_procfreq = 133333333;

        bd.bi_plb_busfreq = 33333333;

        bd.bi_pci_busfreq = 33333333;

        bd.bi_opbfreq = 33333333;

        bdloc = ppc405_set_bootinfo(env, &bd, 0x00000001);

        env->gpr[3] = bdloc;

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

        printf("Load kernel size %ld at " TARGET_FMT_lx,

               kernel_size, kernel_base);

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                        initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        env->gpr[4] = initrd_base;

        env->gpr[5] = initrd_size;

        if (kernel_cmdline != NULL) {

            len = strlen(kernel_cmdline);

            bdloc -= ((len + 255) & ~255);

            cpu_physical_memory_write(bdloc, kernel_cmdline, len + 1);

            env->gpr[6] = bdloc;

            env->gpr[7] = bdloc + len;

        } else {

            env->gpr[6] = 0;

            env->gpr[7] = 0;

        }

        env->nip = KERNEL_LOAD_ADDR;

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        bdloc = 0;

    }

#ifdef DEBUG_BOARD_INIT

    printf("bdloc " RAM_ADDR_FMT "\n", bdloc);

    printf("%s: Done\n", __func__);

#endif

}


static int v9fs_synth_opendir(FsContext *ctx,

                             V9fsPath *fs_path, V9fsFidOpenState *fs)

{

    V9fsSynthOpenState *synth_open;

    V9fsSynthNode *node = *(V9fsSynthNode **)fs_path->data;

    synth_open = g_malloc(sizeof(*synth_open));

    synth_open->node = node;

    node->open_count++;

    fs->private = synth_open;

    return 0;

}


static void raw_reopen_commit(BDRVReopenState *state)

{

    BDRVRawState *new_s = state->opaque;

    BDRVRawState *s = state->bs->opaque;

    memcpy(s, new_s, sizeof(BDRVRawState));

    g_free(state->opaque);

    state->opaque = NULL;

}


static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,

                     int width, int height)

{

    DrawTextContext *dtext = ctx->priv;

    uint32_t code = 0, prev_code = 0;

    int x = 0, y = 0, i = 0, ret;

    int max_text_line_w = 0, len;

    int box_w, box_h;

    char *text = dtext->text;

    uint8_t *p;

    int y_min = 32000, y_max = -32000;

    int x_min = 32000, x_max = -32000;

    FT_Vector delta;

    Glyph *glyph = NULL, *prev_glyph = NULL;

    Glyph dummy = { 0 };

    time_t now = time(0);

    struct tm ltime;

    uint8_t *buf = dtext->expanded_text;

    int buf_size = dtext->expanded_text_size;

    if(dtext->basetime != AV_NOPTS_VALUE)

        now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;

    if (!buf) {

        buf_size = 2*strlen(dtext->text)+1;

        buf = av_malloc(buf_size);

    }

#if HAVE_LOCALTIME_R

    localtime_r(&now, &ltime);

#else

    if(strchr(dtext->text, '%'))

        ltime= *localtime(&now);

#endif

    do {

        *buf = 1;

        if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)

            break;

        buf_size *= 2;

    } while ((buf = av_realloc(buf, buf_size)));

    if (dtext->tc_opt_string) {

        char tcbuf[AV_TIMECODE_STR_SIZE];

        av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);

        buf = av_asprintf("%s%s", dtext->text, tcbuf);

    }

    if (!buf)

        return AVERROR(ENOMEM);

    text = dtext->expanded_text = buf;

    dtext->expanded_text_size = buf_size;

    if ((len = strlen(text)) > dtext->nb_positions) {

        if (!(dtext->positions =

              av_realloc(dtext->positions, len*sizeof(*dtext->positions))))

            return AVERROR(ENOMEM);

        dtext->nb_positions = len;

    }

    x = 0;

    y = 0;

    /* load and cache glyphs */

    for (i = 0, p = text; *p; i++) {

        GET_UTF8(code, *p++, continue;);

        /* get glyph */

        dummy.code = code;

        glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);

        if (!glyph) {

            load_glyph(ctx, &glyph, code);

        }

        y_min = FFMIN(glyph->bbox.yMin, y_min);

        y_max = FFMAX(glyph->bbox.yMax, y_max);

        x_min = FFMIN(glyph->bbox.xMin, x_min);

        x_max = FFMAX(glyph->bbox.xMax, x_max);

    }

    dtext->max_glyph_h = y_max - y_min;

    dtext->max_glyph_w = x_max - x_min;

    /* compute and save position for each glyph */

    glyph = NULL;

    for (i = 0, p = text; *p; i++) {

        GET_UTF8(code, *p++, continue;);

        /* skip the \n in the sequence \r\n */

        if (prev_code == '\r' && code == '\n')

            continue;

        prev_code = code;

        if (is_newline(code)) {

            max_text_line_w = FFMAX(max_text_line_w, x);

            y += dtext->max_glyph_h;

            x = 0;

            continue;

        }

        /* get glyph */

        prev_glyph = glyph;

        dummy.code = code;

        glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);

        /* kerning */

        if (dtext->use_kerning && prev_glyph && glyph->code) {

            FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,

                           ft_kerning_default, &delta);

            x += delta.x >> 6;

        }

        /* save position */

        dtext->positions[i].x = x + glyph->bitmap_left;

        dtext->positions[i].y = y - glyph->bitmap_top + y_max;

        if (code == '\t') x  = (x / dtext->tabsize + 1)*dtext->tabsize;

        else              x += glyph->advance;

    }

    max_text_line_w = FFMAX(x, max_text_line_w);

    dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;

    dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;

    dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;

    dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;

    dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;

    dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;

    dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;

    dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);

    dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);

    dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);

    dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);

    if(!dtext->draw)

        return 0;

    box_w = FFMIN(width - 1 , max_text_line_w);

    box_h = FFMIN(height - 1, y + dtext->max_glyph_h);

    /* draw box */

    if (dtext->draw_box)

        ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,

                           picref->data, picref->linesize, width, height,

                           dtext->x, dtext->y, box_w, box_h);

    if (dtext->shadowx || dtext->shadowy) {

        if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor.rgba,

                               &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)

            return ret;

    }

    if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor.rgba,

                           &dtext->fontcolor, 0, 0)) < 0)

        return ret;

    return 0;

}


static int av_thread_message_queue_recv_locked(AVThreadMessageQueue *mq,

                                               void *msg,

                                               unsigned flags)

{

    while (!mq->err_recv && av_fifo_size(mq->fifo) < mq->elsize) {

        if ((flags & AV_THREAD_MESSAGE_NONBLOCK))

            return AVERROR(EAGAIN);

        pthread_cond_wait(&mq->cond, &mq->lock);

    }

    if (av_fifo_size(mq->fifo) < mq->elsize)

        return mq->err_recv;

    av_fifo_generic_read(mq->fifo, msg, mq->elsize, NULL);

    pthread_cond_signal(&mq->cond);

    return 0;

}


static int blkdebug_debug_resume(BlockDriverState *bs, const char *tag)

{

    BDRVBlkdebugState *s = bs->opaque;

    BlkdebugSuspendedReq *r;

    QLIST_FOREACH(r, &s->suspended_reqs, next) {

        if (!strcmp(r->tag, tag)) {

            qemu_coroutine_enter(r->co, NULL);

            return 0;

        }

    }

    return -ENOENT;

}


static void virtio_blk_handle_write(VirtIOBlockReq *req, MultiReqBuffer *mrb)

{

    BlockRequest *blkreq;

    uint64_t sector;

    sector = virtio_ldq_p(VIRTIO_DEVICE(req->dev), &req->out.sector);

    bdrv_acct_start(req->dev->bs, &req->acct, req->qiov.size, BDRV_ACCT_WRITE);

    trace_virtio_blk_handle_write(req, sector, req->qiov.size / 512);

    if (!virtio_blk_sect_range_ok(req->dev, sector, req->qiov.size)) {

        virtio_blk_rw_complete(req, -EIO);

        return;

    }

    if (mrb->num_writes == 32) {

        virtio_submit_multiwrite(req->dev->bs, mrb);

    }

    blkreq = &mrb->blkreq[mrb->num_writes];

    blkreq->sector = sector;

    blkreq->nb_sectors = req->qiov.size / BDRV_SECTOR_SIZE;

    blkreq->qiov = &req->qiov;

    blkreq->cb = virtio_blk_rw_complete;

    blkreq->opaque = req;

    blkreq->error = 0;

    mrb->num_writes++;

}