static int encode_hq_slice(AVCodecContext *avctx, void *arg)

{

    SliceArgs *slice_dat = arg;

    VC2EncContext *s = slice_dat->ctx;

    PutBitContext *pb = &slice_dat->pb;

    const int slice_x = slice_dat->x;

    const int slice_y = slice_dat->y;

    const int quant_idx = slice_dat->quant_idx;

    const int slice_bytes_max = slice_dat->bytes;

    uint8_t quants[MAX_DWT_LEVELS][4];

    int p, level, orientation;

    avpriv_align_put_bits(pb);

    skip_put_bytes(pb, s->prefix_bytes);

    put_bits(pb, 8, quant_idx);

    /* Slice quantization (slice_quantizers() in the specs) */

    for (level = 0; level < s->wavelet_depth; level++)

        for (orientation = !!level; orientation < 4; orientation++)

            quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);

    /* Luma + 2 Chroma planes */

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

        int bytes_start, bytes_len, pad_s, pad_c;

        bytes_start = put_bits_count(pb) >> 3;

        put_bits(pb, 8, 0);

        for (level = 0; level < s->wavelet_depth; level++) {

            for (orientation = !!level; orientation < 4; orientation++) {

                encode_subband(s, pb, slice_x, slice_y,

                               &s->plane[p].band[level][orientation],

                               quants[level][orientation]);

            }

        }

        avpriv_align_put_bits(pb);

        bytes_len = (put_bits_count(pb) >> 3) - bytes_start - 1;

        if (p == 2) {

            int len_diff = slice_bytes_max - (put_bits_count(pb) >> 3);

            pad_s = FFALIGN((bytes_len + len_diff), s->size_scaler)/s->size_scaler;

            pad_c = (pad_s*s->size_scaler) - bytes_len;

        } else {

            pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;

            pad_c = (pad_s*s->size_scaler) - bytes_len;

        }

        pb->buf[bytes_start] = pad_s;

        flush_put_bits(pb);

        skip_put_bytes(pb, pad_c);

    }

    return 0;

}


static void do_info_commands(Monitor *mon, QObject **ret_data)

{

    QList *cmd_list;

    const mon_cmd_t *cmd;

    cmd_list = qlist_new();

    for (cmd = qmp_cmds; cmd->name != NULL; cmd++) {

        if (monitor_handler_ported(cmd) && !monitor_cmd_user_only(cmd) &&

            !compare_cmd(cmd->name, "info")) {

            qlist_append_obj(cmd_list, get_cmd_dict(cmd->name));

        }

    }

    for (cmd = qmp_query_cmds; cmd->name != NULL; cmd++) {

        if (monitor_handler_ported(cmd) && !monitor_cmd_user_only(cmd)) {

            char buf[128];

            snprintf(buf, sizeof(buf), "query-%s", cmd->name);

            qlist_append_obj(cmd_list, get_cmd_dict(buf));

        }

    }

    *ret_data = QOBJECT(cmd_list);

}


static void spapr_msi_write(void *opaque, hwaddr addr,

                            uint64_t data, unsigned size)

{

    sPAPRPHBState *phb = opaque;

    int ndev = addr >> 16;

    int vec = ((addr & 0xFFFF) >> 2) | data;

    uint32_t irq = phb->msi_table[ndev].irq + vec;

    trace_spapr_pci_msi_write(addr, data, irq);

    qemu_irq_pulse(xics_get_qirq(spapr->icp, irq));

}


static void pxa2xx_pm_write(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

    struct pxa2xx_state_s *s = (struct pxa2xx_state_s *) opaque;

    if (addr > s->pm_base + PCMD31) {

        /* Special case: PWRI2C registers appear in the same range.  */

        pxa2xx_i2c_write(s->i2c[1], addr, value);

        return;

    }

    addr -= s->pm_base;

    switch (addr) {

    case PMCR:

        s->pm_regs[addr >> 2] &= 0x15 & ~(value & 0x2a);

        s->pm_regs[addr >> 2] |= value & 0x15;

        break;

    case PSSR:	/* Read-clean registers */

    case RCSR:

    case PKSR:

        s->pm_regs[addr >> 2] &= ~value;

        break;

    default:	/* Read-write registers */

        if (addr >= PMCR && addr <= PCMD31 && !(addr & 3)) {

            s->pm_regs[addr >> 2] = value;

            break;

        }

        printf("%s: Bad register " REG_FMT "\n", __FUNCTION__, addr);

        break;

    }

}


CPUX86State *cpu_x86_init(void)

{

    CPUX86State *env;

    int i;

    static int inited;

    cpu_x86_tblocks_init();

    env = malloc(sizeof(CPUX86State));

    if (!env)

        return NULL;

    memset(env, 0, sizeof(CPUX86State));

    /* basic FPU init */

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

        env->fptags[i] = 1;

    env->fpuc = 0x37f;

    /* flags setup */

    env->eflags = 0;

    /* init various static tables */

    if (!inited) {

        inited = 1;

        optimize_flags_init();

    }

    return env;

}


void readline_show_prompt(ReadLineState *rs)

{

    monitor_printf(rs->mon, "%s", rs->prompt);

    monitor_flush(rs->mon);

    rs->last_cmd_buf_index = 0;

    rs->last_cmd_buf_size = 0;

    rs->esc_state = IS_NORM;

}


static int parallel_parse(const char *devname)

{

    static int index = 0;

    char label[32];

    if (strcmp(devname, "none") == 0)

        return 0;

    if (index == MAX_PARALLEL_PORTS) {

        fprintf(stderr, "qemu: too many parallel ports\n");

        exit(1);

    }

    snprintf(label, sizeof(label), "parallel%d", index);

    parallel_hds[index] = qemu_chr_new(label, devname, NULL);

    if (!parallel_hds[index]) {

        fprintf(stderr, "qemu: could not connect parallel device"

                " to character backend '%s'\n", devname);

        return -1;

    }

    index++;

    return 0;

}


START_TEST(qfloat_destroy_test)

{

    QFloat *qf = qfloat_from_double(0.0);

    QDECREF(qf);

}


static int local_lstat(FsContext *fs_ctx, V9fsPath *fs_path, struct stat *stbuf)

{

    int err;

    char buffer[PATH_MAX];

    char *path = fs_path->data;

    err =  lstat(rpath(fs_ctx, path, buffer), stbuf);

    if (err) {

        return err;

    }

    if (fs_ctx->fs_sm == SM_MAPPED) {

        /* Actual credentials are part of extended attrs */

        uid_t tmp_uid;

        gid_t tmp_gid;

        mode_t tmp_mode;

        dev_t tmp_dev;

        if (getxattr(rpath(fs_ctx, path, buffer), "user.virtfs.uid", &tmp_uid,

                    sizeof(uid_t)) > 0) {

            stbuf->st_uid = tmp_uid;

        }

        if (getxattr(rpath(fs_ctx, path, buffer), "user.virtfs.gid", &tmp_gid,

                    sizeof(gid_t)) > 0) {

            stbuf->st_gid = tmp_gid;

        }

        if (getxattr(rpath(fs_ctx, path, buffer), "user.virtfs.mode",

                    &tmp_mode, sizeof(mode_t)) > 0) {

            stbuf->st_mode = tmp_mode;

        }

        if (getxattr(rpath(fs_ctx, path, buffer), "user.virtfs.rdev", &tmp_dev,

                        sizeof(dev_t)) > 0) {

                stbuf->st_rdev = tmp_dev;

        }

    }

    return err;

}


void QEMU_NORETURN runtime_exception(CPUS390XState *env, int excp,

                                     uintptr_t retaddr)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    int t;

    cs->exception_index = EXCP_PGM;

    env->int_pgm_code = excp;

    /* Use the (ultimate) callers address to find the insn that trapped.  */

    cpu_restore_state(cs, retaddr);

    /* Advance past the insn.  */

    t = cpu_ldub_code(env, env->psw.addr);

    env->int_pgm_ilen = t = get_ilen(t);

    env->psw.addr += t;

    cpu_loop_exit(cs);

}


static int usb_host_init(void)

{

    const struct libusb_pollfd **poll;

    int i, rc;

    if (ctx) {

        return 0;

    }

    rc = libusb_init(&ctx);

    if (rc != 0) {

        return -1;

    }

    libusb_set_debug(ctx, loglevel);

    libusb_set_pollfd_notifiers(ctx, usb_host_add_fd,

                                usb_host_del_fd,

                                ctx);

    poll = libusb_get_pollfds(ctx);

    if (poll) {

        for (i = 0; poll[i] != NULL; i++) {

            usb_host_add_fd(poll[i]->fd, poll[i]->events, ctx);

        }

    }

    free(poll);

    return 0;

}


SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,

                                                         bool has_id,

                                                         const char *id,

                                                         bool has_name,

                                                         const char *name,

                                                         Error **errp)

{

    BlockDriverState *bs;

    BlockBackend *blk;

    AioContext *aio_context;

    QEMUSnapshotInfo sn;

    Error *local_err = NULL;

    SnapshotInfo *info = NULL;

    int ret;

    blk = blk_by_name(device);

    if (!blk) {

        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,

                  "Device '%s' not found", device);

        return NULL;

    }

    aio_context = blk_get_aio_context(blk);

    aio_context_acquire(aio_context);

    if (!has_id) {

        id = NULL;

    }

    if (!has_name) {

        name = NULL;

    }

    if (!id && !name) {

        error_setg(errp, "Name or id must be provided");

        goto out_aio_context;

    }

    if (!blk_is_available(blk)) {

        error_setg(errp, "Device '%s' has no medium", device);

        goto out_aio_context;

    }

    bs = blk_bs(blk);

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

        goto out_aio_context;

    }

    ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto out_aio_context;

    }

    if (!ret) {

        error_setg(errp,

                   "Snapshot with id '%s' and name '%s' does not exist on "

                   "device '%s'",

                   STR_OR_NULL(id), STR_OR_NULL(name), device);

        goto out_aio_context;

    }

    bdrv_snapshot_delete(bs, id, name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto out_aio_context;

    }

    aio_context_release(aio_context);

    info = g_new0(SnapshotInfo, 1);

    info->id = g_strdup(sn.id_str);

    info->name = g_strdup(sn.name);

    info->date_nsec = sn.date_nsec;

    info->date_sec = sn.date_sec;

    info->vm_state_size = sn.vm_state_size;

    info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;

    info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;

    return info;

out_aio_context:

    aio_context_release(aio_context);

    return NULL;

}


static void virtio_scsi_complete_req(VirtIOSCSIReq *req)

{

    VirtIOSCSI *s = req->dev;

    VirtQueue *vq = req->vq;

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    virtqueue_push(vq, &req->elem, req->qsgl.size + req->elem.in_sg[0].iov_len);

    if (req->sreq) {

        req->sreq->hba_private = NULL;

        scsi_req_unref(req->sreq);

    }

    virtio_scsi_free_req(req);

    virtio_notify(vdev, vq);

}


bool timer_pending(QEMUTimer *ts)

{

    QEMUTimer *t;

    for (t = ts->timer_list->active_timers; t != NULL; t = t->next) {

        if (t == ts) {

            return true;

        }

    }

    return false;

}


static int av_cold libopus_encode_init(AVCodecContext *avctx)

{

    LibopusEncContext *opus = avctx->priv_data;

    const uint8_t *channel_mapping;

    OpusMSEncoder *enc;

    int ret = OPUS_OK;

    int coupled_stream_count, header_size, frame_size;

    coupled_stream_count = opus_coupled_streams[avctx->channels - 1];

    opus->stream_count   = avctx->channels - coupled_stream_count;

    channel_mapping      = libav_libopus_channel_map[avctx->channels - 1];

    /* FIXME: Opus can handle up to 255 channels. However, the mapping for

     * anything greater than 8 is undefined. */

    if (avctx->channels > 8)

        av_log(avctx, AV_LOG_WARNING,

               "Channel layout undefined for %d channels.\n", avctx->channels);

    if (!avctx->bit_rate) {

        /* Sane default copied from opusenc */

        avctx->bit_rate = 64000 * opus->stream_count +

                          32000 * coupled_stream_count;

        av_log(avctx, AV_LOG_WARNING,

               "No bit rate set. Defaulting to %d bps.\n", avctx->bit_rate);

    }

    if (avctx->bit_rate < 500 || avctx->bit_rate > 256000 * avctx->channels) {

        av_log(avctx, AV_LOG_ERROR, "The bit rate %d bps is unsupported. "

               "Please choose a value between 500 and %d.\n", avctx->bit_rate,

               256000 * avctx->channels);

        return AVERROR(EINVAL);

    }

    frame_size = opus->opts.frame_duration * 48000 / 1000;

    switch (frame_size) {

    case 120:

    case 240:

        if (opus->opts.application != OPUS_APPLICATION_RESTRICTED_LOWDELAY)

            av_log(avctx, AV_LOG_WARNING,

                   "LPC mode cannot be used with a frame duration of less "

                   "than 10ms. Enabling restricted low-delay mode.\n"

                   "Use a longer frame duration if this is not what you want.\n");

        /* Frame sizes less than 10 ms can only use MDCT mode, so switching to

         * RESTRICTED_LOWDELAY avoids an unnecessary extra 2.5ms lookahead. */

        opus->opts.application = OPUS_APPLICATION_RESTRICTED_LOWDELAY;

    case 480:

    case 960:

    case 1920:

    case 2880:

        opus->opts.packet_size =

        avctx->frame_size      = frame_size * avctx->sample_rate / 48000;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Invalid frame duration: %g.\n"

               "Frame duration must be exactly one of: 2.5, 5, 10, 20, 40 or 60.\n",

               opus->opts.frame_duration);

        return AVERROR(EINVAL);

    }

    if (avctx->compression_level < 0 || avctx->compression_level > 10) {

        av_log(avctx, AV_LOG_WARNING,

               "Compression level must be in the range 0 to 10. "

               "Defaulting to 10.\n");

        opus->opts.complexity = 10;

    } else {

        opus->opts.complexity = avctx->compression_level;

    }

    if (avctx->cutoff) {

        switch (avctx->cutoff) {

        case  4000:

            opus->opts.max_bandwidth = OPUS_BANDWIDTH_NARROWBAND;

            break;

        case  6000:

            opus->opts.max_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND;

            break;

        case  8000:

            opus->opts.max_bandwidth = OPUS_BANDWIDTH_WIDEBAND;

            break;

        case 12000:

            opus->opts.max_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND;

            break;

        case 20000:

            opus->opts.max_bandwidth = OPUS_BANDWIDTH_FULLBAND;

            break;

        default:

            av_log(avctx, AV_LOG_WARNING,

                   "Invalid frequency cutoff: %d. Using default maximum bandwidth.\n"

                   "Cutoff frequency must be exactly one of: 4000, 6000, 8000, 12000 or 20000.\n",

                   avctx->cutoff);

            avctx->cutoff = 0;

        }

    }

    enc = opus_multistream_encoder_create(avctx->sample_rate, avctx->channels,

                                          opus->stream_count,

                                          coupled_stream_count,

                                          channel_mapping,

                                          opus->opts.application, &ret);

    if (ret != OPUS_OK) {

        av_log(avctx, AV_LOG_ERROR,

               "Failed to create encoder: %s\n", opus_strerror(ret));

        return ff_opus_error_to_averror(ret);

    }

    ret = libopus_configure_encoder(avctx, enc, &opus->opts);

    if (ret != OPUS_OK) {

        ret = ff_opus_error_to_averror(ret);

        goto fail;

    }

    header_size = 19 + (avctx->channels > 2 ? 2 + avctx->channels : 0);

    avctx->extradata = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!avctx->extradata) {

        av_log(avctx, AV_LOG_ERROR, "Failed to allocate extradata.\n");

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    avctx->extradata_size = header_size;

    opus->samples = av_mallocz(frame_size * avctx->channels *

                               av_get_bytes_per_sample(avctx->sample_fmt));

    if (!opus->samples) {

        av_log(avctx, AV_LOG_ERROR, "Failed to allocate samples buffer.\n");

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    ret = opus_multistream_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&avctx->delay));

    if (ret != OPUS_OK)

        av_log(avctx, AV_LOG_WARNING,

               "Unable to get number of lookahead samples: %s\n",

               opus_strerror(ret));

    libopus_write_header(avctx, opus->stream_count, coupled_stream_count,

                         opus_vorbis_channel_map[avctx->channels - 1]);

    ff_af_queue_init(avctx, &opus->afq);

    opus->enc = enc;

    return 0;

fail:

    opus_multistream_encoder_destroy(enc);

    av_freep(&avctx->extradata);

    return ret;

}


static void setup_rt_frame(int sig, struct emulated_sigaction *ka,

                           target_siginfo_t *info,

			   target_sigset_t *set, CPUX86State *env)

{

	struct rt_sigframe *frame;

	int err = 0;

	frame = get_sigframe(ka, env, sizeof(*frame));

#if 0

	if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))

		goto give_sigsegv;

#endif

	err |= __put_user((/*current->exec_domain

		    	   && current->exec_domain->signal_invmap

		    	   && sig < 32

		    	   ? current->exec_domain->signal_invmap[sig]

			   : */sig),

			  &frame->sig);

	err |= __put_user((target_ulong)&frame->info, &frame->pinfo);

	err |= __put_user((target_ulong)&frame->uc, &frame->puc);

	err |= copy_siginfo_to_user(&frame->info, info);

	if (err)

		goto give_sigsegv;

	/* Create the ucontext.  */

	err |= __put_user(0, &frame->uc.uc_flags);

	err |= __put_user(0, &frame->uc.uc_link);

	err |= __put_user(/*current->sas_ss_sp*/ 0, &frame->uc.uc_stack.ss_sp);

	err |= __put_user(/* sas_ss_flags(regs->esp) */ 0,

			  &frame->uc.uc_stack.ss_flags);

	err |= __put_user(/* current->sas_ss_size */ 0, &frame->uc.uc_stack.ss_size);

	err |= setup_sigcontext(&frame->uc.uc_mcontext, &frame->fpstate,

			        env, set->sig[0]);

	err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));

	if (err)

		goto give_sigsegv;

	/* Set up to return from userspace.  If provided, use a stub

	   already in userspace.  */

	if (ka->sa.sa_flags & TARGET_SA_RESTORER) {

		err |= __put_user(ka->sa.sa_restorer, &frame->pretcode);

	} else {

		err |= __put_user(frame->retcode, &frame->pretcode);

		/* This is movl $,%eax ; int $0x80 */

		err |= __put_user(0xb8, (char *)(frame->retcode+0));

		err |= __put_user(TARGET_NR_rt_sigreturn, (int *)(frame->retcode+1));

		err |= __put_user(0x80cd, (short *)(frame->retcode+5));

	}

	if (err)

		goto give_sigsegv;

	/* Set up registers for signal handler */

	env->regs[R_ESP] = (unsigned long) frame;

	env->eip = (unsigned long) ka->sa._sa_handler;

        cpu_x86_load_seg(env, R_DS, __USER_DS);

        cpu_x86_load_seg(env, R_ES, __USER_DS);

        cpu_x86_load_seg(env, R_SS, __USER_DS);

        cpu_x86_load_seg(env, R_CS, __USER_CS);

	env->eflags &= ~TF_MASK;

	return;

give_sigsegv:

	if (sig == TARGET_SIGSEGV)

		ka->sa._sa_handler = TARGET_SIG_DFL;

	force_sig(TARGET_SIGSEGV /* , current */);

}


static void tcp_chr_telnet_init(QIOChannel *ioc)

{

    char buf[3];

    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */

    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */

    qio_channel_write(ioc, buf, 3, NULL);

    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */

    qio_channel_write(ioc, buf, 3, NULL);

    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */

    qio_channel_write(ioc, buf, 3, NULL);

    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */

    qio_channel_write(ioc, buf, 3, NULL);

}


static void blk_delete(BlockBackend *blk)

{

    assert(!blk->refcnt);

    assert(!blk->name);

    assert(!blk->dev);

    if (blk->root) {

        blk_remove_bs(blk);

    assert(QLIST_EMPTY(&blk->remove_bs_notifiers.notifiers));

    assert(QLIST_EMPTY(&blk->insert_bs_notifiers.notifiers));

    QTAILQ_REMOVE(&block_backends, blk, link);

    drive_info_del(blk->legacy_dinfo);

    block_acct_cleanup(&blk->stats);

    g_free(blk);


static int gdbserver_open(int port)

{

    struct sockaddr_in sockaddr;

    int fd, val, ret;

    fd = socket(PF_INET, SOCK_STREAM, 0);

    if (fd < 0) {

        perror("socket");

        return -1;

    }

#ifndef _WIN32

    fcntl(fd, F_SETFD, FD_CLOEXEC);

#endif

    /* allow fast reuse */

    val = 1;

    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));

    sockaddr.sin_family = AF_INET;

    sockaddr.sin_port = htons(port);

    sockaddr.sin_addr.s_addr = 0;

    ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));

    if (ret < 0) {

        perror("bind");

        return -1;

    }

    ret = listen(fd, 0);

    if (ret < 0) {

        perror("listen");

        return -1;

    }

    return fd;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    VIOsPAPRDeviceClass *k = VIO_SPAPR_DEVICE_CLASS(klass);

    k->realize = spapr_nvram_realize;

    k->devnode = spapr_nvram_devnode;

    k->dt_name = "nvram";

    k->dt_type = "nvram";

    k->dt_compatible = "qemu,spapr-nvram";

    set_bit(DEVICE_CATEGORY_MISC, dc->categories);

    dc->props = spapr_nvram_properties;

    dc->vmsd = &vmstate_spapr_nvram;

}


static void cpu_handle_ioreq(void *opaque)

{

    XenIOState *state = opaque;

    ioreq_t *req = cpu_get_ioreq(state);

    handle_buffered_iopage(state);

    if (req) {

        ioreq_t copy = *req;

        xen_rmb();

        handle_ioreq(state, &copy);

        req->data = copy.data;

        if (req->state != STATE_IOREQ_INPROCESS) {

            fprintf(stderr, "Badness in I/O request ... not in service?!: "

                    "%x, ptr: %x, port: %"PRIx64", "

                    "data: %"PRIx64", count: %u, size: %u, type: %u\n",

                    req->state, req->data_is_ptr, req->addr,

                    req->data, req->count, req->size, req->type);

            destroy_hvm_domain(false);

            return;

        }

        xen_wmb(); /* Update ioreq contents /then/ update state. */

        /*

         * We do this before we send the response so that the tools

         * have the opportunity to pick up on the reset before the

         * guest resumes and does a hlt with interrupts disabled which

         * causes Xen to powerdown the domain.

         */

        if (runstate_is_running()) {

            if (qemu_shutdown_requested_get()) {

                destroy_hvm_domain(false);

            }

            if (qemu_reset_requested_get()) {

                qemu_system_reset(VMRESET_REPORT);

                destroy_hvm_domain(true);

            }

        }

        req->state = STATE_IORESP_READY;

        xenevtchn_notify(state->xce_handle,

                         state->ioreq_local_port[state->send_vcpu]);

    }

}


static bool scsi_target_emulate_inquiry(SCSITargetReq *r)

{

    assert(r->req.dev->lun != r->req.lun);

    if (r->req.cmd.buf[1] & 0x2) {

        /* Command support data - optional, not implemented */

        return false;

    }

    if (r->req.cmd.buf[1] & 0x1) {

        /* Vital product data */

        uint8_t page_code = r->req.cmd.buf[2];

        r->buf[r->len++] = page_code ; /* this page */

        r->buf[r->len++] = 0x00;

        switch (page_code) {

        case 0x00: /* Supported page codes, mandatory */

        {

            int pages;

            pages = r->len++;

            r->buf[r->len++] = 0x00; /* list of supported pages (this page) */

            r->buf[pages] = r->len - pages - 1; /* number of pages */

            break;

        }

        default:

            return false;

        }

        /* done with EVPD */

        assert(r->len < sizeof(r->buf));

        r->len = MIN(r->req.cmd.xfer, r->len);

        return true;

    }

    /* Standard INQUIRY data */

    if (r->req.cmd.buf[2] != 0) {

        return false;

    }

    /* PAGE CODE == 0 */

    r->len = MIN(r->req.cmd.xfer, 36);

    memset(r->buf, 0, r->len);

    if (r->req.lun != 0) {

        r->buf[0] = TYPE_NO_LUN;

    } else {

        r->buf[0] = TYPE_NOT_PRESENT | TYPE_INACTIVE;

        r->buf[2] = 5; /* Version */

        r->buf[3] = 2 | 0x10; /* HiSup, response data format */

        r->buf[4] = r->len - 5; /* Additional Length = (Len - 1) - 4 */

        r->buf[7] = 0x10 | (r->req.bus->info->tcq ? 0x02 : 0); /* Sync, TCQ.  */

        memcpy(&r->buf[8], "QEMU    ", 8);

        memcpy(&r->buf[16], "QEMU TARGET     ", 16);

        pstrcpy((char *) &r->buf[32], 4, qemu_get_version());

    }

    return true;

}


int qcow2_expand_zero_clusters(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l1_table = NULL;

    uint64_t nb_clusters;

    uint8_t *expanded_clusters;

    int ret;

    int i, j;

    nb_clusters = size_to_clusters(s, bs->file->total_sectors *

                                   BDRV_SECTOR_SIZE);

    expanded_clusters = g_malloc0((nb_clusters + 7) / 8);

    ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,

                                     &expanded_clusters, &nb_clusters);

    if (ret < 0) {

        goto fail;

    }

    /* Inactive L1 tables may point to active L2 tables - therefore it is

     * necessary to flush the L2 table cache before trying to access the L2

     * tables pointed to by inactive L1 entries (else we might try to expand

     * zero clusters that have already been expanded); furthermore, it is also

     * necessary to empty the L2 table cache, since it may contain tables which

     * are now going to be modified directly on disk, bypassing the cache.

     * qcow2_cache_empty() does both for us. */

    ret = qcow2_cache_empty(bs, s->l2_table_cache);

    if (ret < 0) {

        goto fail;

    }

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

        int l1_sectors = (s->snapshots[i].l1_size * sizeof(uint64_t) +

                BDRV_SECTOR_SIZE - 1) / BDRV_SECTOR_SIZE;

        l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);

        ret = bdrv_read(bs->file, s->snapshots[i].l1_table_offset /

                BDRV_SECTOR_SIZE, (void *)l1_table, l1_sectors);

        if (ret < 0) {

            goto fail;

        }

        for (j = 0; j < s->snapshots[i].l1_size; j++) {

            be64_to_cpus(&l1_table[j]);

        }

        ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,

                                         &expanded_clusters, &nb_clusters);

        if (ret < 0) {

            goto fail;

        }

    }

    ret = 0;

fail:

    g_free(expanded_clusters);

    g_free(l1_table);

    return ret;

}


static int local_open2(FsContext *fs_ctx, const char *path, int flags,

        FsCred *credp)

{

    int fd = -1;

    int err = -1;

    int serrno = 0;

    /* Determine the security model */

    if (fs_ctx->fs_sm == SM_MAPPED) {

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

        if (fd == -1) {

            return fd;

        }

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

        /* Set cleint credentials in xattr */

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

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

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

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

        if (fd == -1) {

            return fd;

        }

        err = local_post_create_passthrough(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    }

    return fd;

err_end:

    close(fd);

    remove(rpath(fs_ctx, path));

    errno = serrno;

    return err;

}


static inline void yuv2packedXinC(SwsContext *c, int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

				    int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

				    uint8_t *dest, int dstW, int y)

{

	int i;

	switch(c->dstFormat)

	{

	case PIX_FMT_BGR32:

	case PIX_FMT_RGB32:

		YSCALE_YUV_2_RGBX_C(uint32_t)

			((uint32_t*)dest)[i2+0]= r[Y1] + g[Y1] + b[Y1];

			((uint32_t*)dest)[i2+1]= r[Y2] + g[Y2] + b[Y2];

		}

		break;

	case PIX_FMT_RGB24:

		YSCALE_YUV_2_RGBX_C(uint8_t)

			((uint8_t*)dest)[0]= r[Y1];

			((uint8_t*)dest)[1]= g[Y1];

			((uint8_t*)dest)[2]= b[Y1];

			((uint8_t*)dest)[3]= r[Y2];

			((uint8_t*)dest)[4]= g[Y2];

			((uint8_t*)dest)[5]= b[Y2];

			dest+=6;

		}


static int write_packet(AVFormatContext *s, AVPacket *pkt)
{
    int ret, did_split;
    if (s->output_ts_offset) {
        AVStream *st = s->streams[pkt->stream_index];
        int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
        if (pkt->dts != AV_NOPTS_VALUE)
            pkt->dts += offset;
        if (pkt->pts != AV_NOPTS_VALUE)
            pkt->pts += offset;
    }
    if (s->avoid_negative_ts > 0) {
        AVStream *st = s->streams[pkt->stream_index];
        int64_t offset = st->mux_ts_offset;
        int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
        if (s->internal->offset == AV_NOPTS_VALUE && ts != AV_NOPTS_VALUE &&
            (ts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
            s->internal->offset = -ts;
            s->internal->offset_timebase = st->time_base;
        }
        if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
            offset = st->mux_ts_offset =
                av_rescale_q_rnd(s->internal->offset,
                                 s->internal->offset_timebase,
                                 st->time_base,
                                 AV_ROUND_UP);
        }
        if (pkt->dts != AV_NOPTS_VALUE)
            pkt->dts += offset;
        if (pkt->pts != AV_NOPTS_VALUE)
            pkt->pts += offset;
        if (s->internal->avoid_negative_ts_use_pts) {
            if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
                av_log(s, AV_LOG_WARNING, "failed to avoid negative "
                    "pts %s in stream %d.\n"
                    "Try -avoid_negative_ts 1 as a possible workaround.\n",
                    av_ts2str(pkt->dts),
                    pkt->stream_index
                );
            }
        } else {
            av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
            if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
                av_log(s, AV_LOG_WARNING,
                    "Packets poorly interleaved, failed to avoid negative "
                    "timestamp %s in stream %d.\n"
                    "Try -max_interleave_delta 0 as a possible workaround.\n",
                    av_ts2str(pkt->dts),
                    pkt->stream_index
                );
            }
        }
    }
    did_split = av_packet_split_side_data(pkt);
    if (!s->internal->header_written) {
        ret = s->internal->write_header_ret ? s->internal->write_header_ret : write_header_internal(s);
        if (ret < 0)
            goto fail;
    }
    if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
        AVFrame *frame = (AVFrame *)pkt->data;
        av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
        ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
        av_frame_free(&frame);
    } else {
        ret = s->oformat->write_packet(s, pkt);
    }
    if (s->pb && ret >= 0) {
        if (s->flush_packets && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
            avio_flush(s->pb);
        if (s->pb->error < 0)
            ret = s->pb->error;
    }
fail:
    if (did_split)
        av_packet_merge_side_data(pkt);
    if (ret < 0) {
        pkt->pts = pts_backup;
        pkt->dts = dts_backup;
    }
    return ret;
}


static void read_sgi_header(ByteIOContext *f, SGIInfo *info)
{
    info->magic = (unsigned short) get_be16(f);
    info->rle = get_byte(f);
    info->bytes_per_channel = get_byte(f);
    info->dimension = (unsigned short)get_be16(f);
    info->xsize = (unsigned short) get_be16(f);
    info->ysize = (unsigned short) get_be16(f);
    info->zsize = (unsigned short) get_be16(f);
#ifdef DEBUG
    printf("sgi header fields:\n");
    printf("  magic: %d\n", info->magic);
    printf("    rle: %d\n", info->rle);
    printf("    bpc: %d\n", info->bytes_per_channel);
    printf("    dim: %d\n", info->dimension);
    printf("  xsize: %d\n", info->xsize);
    printf("  ysize: %d\n", info->ysize);
    printf("  zsize: %d\n", info->zsize);
#endif
    return;
}


static void pc_init1(ram_addr_t ram_size, int vga_ram_size,

                     const char *boot_device, DisplayState *ds,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename,

                     int pci_enabled, const char *cpu_model)

{

    char buf[1024];

    int ret, linux_boot, i;

    ram_addr_t ram_addr, vga_ram_addr, bios_offset, vga_bios_offset;

    ram_addr_t below_4g_mem_size, above_4g_mem_size = 0;

    int bios_size, isa_bios_size, vga_bios_size;

    PCIBus *pci_bus;

    int piix3_devfn = -1;

    CPUState *env;

    qemu_irq *cpu_irq;

    qemu_irq *i8259;

    int index;

    BlockDriverState *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BlockDriverState *fd[MAX_FD];

    if (ram_size >= 0xe0000000 ) {

        above_4g_mem_size = ram_size - 0xe0000000;

        below_4g_mem_size = 0xe0000000;

    } else {

        below_4g_mem_size = ram_size;

    }

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_X86_64

        cpu_model = "qemu64";

#else

        cpu_model = "qemu32";

#endif

    }

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

        env = cpu_init(cpu_model);

        if (!env) {

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

            exit(1);

        }

        if (i != 0)

            env->halted = 1;

        if (smp_cpus > 1) {

            /* XXX: enable it in all cases */

            env->cpuid_features |= CPUID_APIC;

        }

        qemu_register_reset(main_cpu_reset, env);

        if (pci_enabled) {

            apic_init(env);

        }

    }

    vmport_init();

    /* allocate RAM */

    ram_addr = qemu_ram_alloc(0xa0000);

    cpu_register_physical_memory(0, 0xa0000, ram_addr);

    /* Allocate, even though we won't register, so we don't break the

     * phys_ram_base + PA assumption. This range includes vga (0xa0000 - 0xc0000),

     * and some bios areas, which will be registered later

     */

    ram_addr = qemu_ram_alloc(0x100000 - 0xa0000);

    ram_addr = qemu_ram_alloc(below_4g_mem_size - 0x100000);

    cpu_register_physical_memory(0x100000,

                 below_4g_mem_size - 0x100000,

                 ram_addr);

    /* above 4giga memory allocation */

    if (above_4g_mem_size > 0) {

        ram_addr = qemu_ram_alloc(above_4g_mem_size);

        cpu_register_physical_memory(0x100000000ULL,

                                     above_4g_mem_size,

                                     ram_addr);

    }

    /* allocate VGA RAM */

    vga_ram_addr = qemu_ram_alloc(vga_ram_size);

    /* BIOS load */

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    snprintf(buf, sizeof(buf), "%s/%s", bios_dir, bios_name);

    bios_size = get_image_size(buf);

    if (bios_size <= 0 ||

        (bios_size % 65536) != 0) {

        goto bios_error;

    }

    bios_offset = qemu_ram_alloc(bios_size);

    ret = load_image(buf, phys_ram_base + bios_offset);

    if (ret != bios_size) {

    bios_error:

        fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", buf);

        exit(1);

    }

    if (cirrus_vga_enabled || std_vga_enabled || vmsvga_enabled) {

        /* VGA BIOS load */

        if (cirrus_vga_enabled) {

            snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_CIRRUS_FILENAME);

        } else {

            snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);

        }

        vga_bios_size = get_image_size(buf);

        if (vga_bios_size <= 0 || vga_bios_size > 65536)

            goto vga_bios_error;

        vga_bios_offset = qemu_ram_alloc(65536);

        ret = load_image(buf, phys_ram_base + vga_bios_offset);

        if (ret != vga_bios_size) {

vga_bios_error:

            fprintf(stderr, "qemu: could not load VGA BIOS '%s'\n", buf);

            exit(1);

        }

    }

    /* setup basic memory access */

    cpu_register_physical_memory(0xc0000, 0x10000,

                                 vga_bios_offset | IO_MEM_ROM);

    /* map the last 128KB of the BIOS in ISA space */

    isa_bios_size = bios_size;

    if (isa_bios_size > (128 * 1024))

        isa_bios_size = 128 * 1024;

    cpu_register_physical_memory(0x100000 - isa_bios_size,

                                 isa_bios_size,

                                 (bios_offset + bios_size - isa_bios_size) | IO_MEM_ROM);

    {

        ram_addr_t option_rom_offset;

        int size, offset;

        offset = 0;

        if (linux_boot) {

            option_rom_offset = qemu_ram_alloc(TARGET_PAGE_SIZE);

            load_linux(phys_ram_base + option_rom_offset,

                       kernel_filename, initrd_filename, kernel_cmdline);

            cpu_register_physical_memory(0xd0000, TARGET_PAGE_SIZE,

                                         option_rom_offset | IO_MEM_ROM);

            offset = TARGET_PAGE_SIZE;

        }

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

            size = get_image_size(option_rom[i]);

            if (size < 0) {

                fprintf(stderr, "Could not load option rom '%s'\n",

                        option_rom[i]);

                exit(1);

            }

            if (size > (0x10000 - offset))

                goto option_rom_error;

            option_rom_offset = qemu_ram_alloc(size);

            ret = load_image(option_rom[i], phys_ram_base + option_rom_offset);

            if (ret != size) {

            option_rom_error:

                fprintf(stderr, "Too many option ROMS\n");

                exit(1);

            }

            size = (size + 4095) & ~4095;

            cpu_register_physical_memory(0xd0000 + offset,

                                         size, option_rom_offset | IO_MEM_ROM);

            offset += size;

        }

    }

    /* map all the bios at the top of memory */

    cpu_register_physical_memory((uint32_t)(-bios_size),

                                 bios_size, bios_offset | IO_MEM_ROM);

    bochs_bios_init();

    cpu_irq = qemu_allocate_irqs(pic_irq_request, NULL, 1);

    i8259 = i8259_init(cpu_irq[0]);

    ferr_irq = i8259[13];

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, i8259);

        piix3_devfn = piix3_init(pci_bus, -1);

    } else {

        pci_bus = NULL;

    }

    /* init basic PC hardware */

    register_ioport_write(0x80, 1, 1, ioport80_write, NULL);

    register_ioport_write(0xf0, 1, 1, ioportF0_write, NULL);

    if (cirrus_vga_enabled) {

        if (pci_enabled) {

            pci_cirrus_vga_init(pci_bus,

                                ds, phys_ram_base + vga_ram_addr,

                                vga_ram_addr, vga_ram_size);

        } else {

            isa_cirrus_vga_init(ds, phys_ram_base + vga_ram_addr,

                                vga_ram_addr, vga_ram_size);

        }

    } else if (vmsvga_enabled) {

        if (pci_enabled)

            pci_vmsvga_init(pci_bus, ds, phys_ram_base + vga_ram_addr,

                            vga_ram_addr, vga_ram_size);

        else

            fprintf(stderr, "%s: vmware_vga: no PCI bus\n", __FUNCTION__);

    } else if (std_vga_enabled) {

        if (pci_enabled) {

            pci_vga_init(pci_bus, ds, phys_ram_base + vga_ram_addr,

                         vga_ram_addr, vga_ram_size, 0, 0);

        } else {

            isa_vga_init(ds, phys_ram_base + vga_ram_addr,

                         vga_ram_addr, vga_ram_size);

        }

    }

    rtc_state = rtc_init(0x70, i8259[8]);

    qemu_register_boot_set(pc_boot_set, rtc_state);

    register_ioport_read(0x92, 1, 1, ioport92_read, NULL);

    register_ioport_write(0x92, 1, 1, ioport92_write, NULL);

    if (pci_enabled) {

        ioapic = ioapic_init();

    }

    pit = pit_init(0x40, i8259[0]);

    pcspk_init(pit);

    if (!no_hpet) {

        hpet_init(i8259);

    }

    if (pci_enabled) {

        pic_set_alt_irq_func(isa_pic, ioapic_set_irq, ioapic);

    }

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

        if (serial_hds[i]) {

            serial_init(serial_io[i], i8259[serial_irq[i]], 115200,

                        serial_hds[i]);

        }

    }

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

        if (parallel_hds[i]) {

            parallel_init(parallel_io[i], i8259[parallel_irq[i]],

                          parallel_hds[i]);

        }

    }

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

        NICInfo *nd = &nd_table[i];

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

            pc_init_ne2k_isa(nd, i8259);

        else

            pci_nic_init(pci_bus, nd, -1, "ne2k_pci");

    }

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

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

        exit(1);

    }

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

        index = drive_get_index(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

	if (index != -1)

	    hd[i] = drives_table[index].bdrv;

	else

	    hd[i] = NULL;

    }

    if (pci_enabled) {

        pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1, i8259);

    } else {

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

            isa_ide_init(ide_iobase[i], ide_iobase2[i], i8259[ide_irq[i]],

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

        }

    }

    i8042_init(i8259[1], i8259[12], 0x60);

    DMA_init(0);

#ifdef HAS_AUDIO

    audio_init(pci_enabled ? pci_bus : NULL, i8259);

#endif

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

        index = drive_get_index(IF_FLOPPY, 0, i);

	if (index != -1)

	    fd[i] = drives_table[index].bdrv;

	else

	    fd[i] = NULL;

    }

    floppy_controller = fdctrl_init(i8259[6], 2, 0, 0x3f0, fd);

    cmos_init(below_4g_mem_size, above_4g_mem_size, boot_device, hd);

    if (pci_enabled && usb_enabled) {

        usb_uhci_piix3_init(pci_bus, piix3_devfn + 2);

    }

    if (pci_enabled && acpi_enabled) {

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

        i2c_bus *smbus;

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100, i8259[9]);

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

            smbus_eeprom_device_init(smbus, 0x50 + i, eeprom_buf + (i * 256));

        }

    }

    if (i440fx_state) {

        i440fx_init_memory_mappings(i440fx_state);

    }

    if (pci_enabled) {

	int max_bus;

        int bus, unit;

        void *scsi;

        max_bus = drive_get_max_bus(IF_SCSI);

	for (bus = 0; bus <= max_bus; bus++) {

            scsi = lsi_scsi_init(pci_bus, -1);

            for (unit = 0; unit < LSI_MAX_DEVS; unit++) {

	        index = drive_get_index(IF_SCSI, bus, unit);

		if (index == -1)

		    continue;

		lsi_scsi_attach(scsi, drives_table[index].bdrv, unit);

	    }

        }

    }

    /* Add virtio block devices */

    if (pci_enabled) {

        int index;

        int unit_id = 0;

        while ((index = drive_get_index(IF_VIRTIO, 0, unit_id)) != -1) {

            virtio_blk_init(pci_bus, drives_table[index].bdrv);

            unit_id++;

        }

    }

    /* Add virtio balloon device */

    if (pci_enabled)

        virtio_balloon_init(pci_bus);

    /* Add virtio console devices */

    if (pci_enabled) {

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

            if (virtcon_hds[i])

                virtio_console_init(pci_bus, virtcon_hds[i]);

        }

    }

}


static int slirp_hostfwd(SlirpState *s, const char *redir_str,

                         int legacy_format)

{

    struct in_addr host_addr = { .s_addr = INADDR_ANY };

    struct in_addr guest_addr = { .s_addr = 0 };

    int host_port, guest_port;

    const char *p;

    char buf[256];

    int is_udp;

    char *end;

    p = redir_str;

    if (!p || get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

        goto fail_syntax;

    }

    if (!strcmp(buf, "tcp") || buf[0] == '\0') {

        is_udp = 0;

    } else if (!strcmp(buf, "udp")) {

        is_udp = 1;

    } else {

        goto fail_syntax;

    }

    if (!legacy_format) {

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

        if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {

            goto fail_syntax;

        }

    }

    if (get_str_sep(buf, sizeof(buf), &p, legacy_format ? ':' : '-') < 0) {

        goto fail_syntax;

    }

    host_port = strtol(buf, &end, 0);

    if (*end != '\0' || host_port < 1 || host_port > 65535) {

        goto fail_syntax;

    }

    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

        goto fail_syntax;

    }

    if (buf[0] != '\0' && !inet_aton(buf, &guest_addr)) {

        goto fail_syntax;

    }

    guest_port = strtol(p, &end, 0);

    if (*end != '\0' || guest_port < 1 || guest_port > 65535) {

        goto fail_syntax;

    }

    if (slirp_add_hostfwd(s->slirp, is_udp, host_addr, host_port, guest_addr,

                          guest_port) < 0) {

        error_report("could not set up host forwarding rule '%s'",

                     redir_str);

        return -1;

    }

    return 0;

 fail_syntax:

    error_report("invalid host forwarding rule '%s'", redir_str);

    return -1;

}


int kvm_arch_put_registers(CPUState *cs, int level)

{

    S390CPU *cpu = S390_CPU(cs);

    CPUS390XState *env = &cpu->env;

    struct kvm_sregs sregs;

    struct kvm_regs regs;

    struct kvm_fpu fpu;

    int r;

    int i;

    /* always save the PSW  and the GPRS*/

    cs->kvm_run->psw_addr = env->psw.addr;

    cs->kvm_run->psw_mask = env->psw.mask;

    if (cap_sync_regs && cs->kvm_run->kvm_valid_regs & KVM_SYNC_GPRS) {

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

            cs->kvm_run->s.regs.gprs[i] = env->regs[i];

            cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_GPRS;

        }

    } else {

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

            regs.gprs[i] = env->regs[i];

        }

        r = kvm_vcpu_ioctl(cs, KVM_SET_REGS, &regs);

        if (r < 0) {

            return r;

        }

    }

    /* Floating point */

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

        fpu.fprs[i] = env->fregs[i].ll;

    }

    fpu.fpc = env->fpc;

    r = kvm_vcpu_ioctl(cs, KVM_SET_FPU, &fpu);

    if (r < 0) {

        return r;

    }

    /* Do we need to save more than that? */

    if (level == KVM_PUT_RUNTIME_STATE) {

        return 0;

    }

    /*

     * These ONE_REGS are not protected by a capability. As they are only

     * necessary for migration we just trace a possible error, but don't

     * return with an error return code.

     */

    kvm_set_one_reg(cs, KVM_REG_S390_CPU_TIMER, &env->cputm);

    kvm_set_one_reg(cs, KVM_REG_S390_CLOCK_COMP, &env->ckc);

    kvm_set_one_reg(cs, KVM_REG_S390_TODPR, &env->todpr);

    kvm_set_one_reg(cs, KVM_REG_S390_GBEA, &env->gbea);

    kvm_set_one_reg(cs, KVM_REG_S390_PP, &env->pp);

    if (cap_async_pf) {

        r = kvm_set_one_reg(cs, KVM_REG_S390_PFTOKEN, &env->pfault_token);

        if (r < 0) {

            return r;

        }

        r = kvm_set_one_reg(cs, KVM_REG_S390_PFCOMPARE, &env->pfault_compare);

        if (r < 0) {

            return r;

        }

        r = kvm_set_one_reg(cs, KVM_REG_S390_PFSELECT, &env->pfault_select);

        if (r < 0) {

            return r;

        }

    }

    if (cap_sync_regs &&

        cs->kvm_run->kvm_valid_regs & KVM_SYNC_ACRS &&

        cs->kvm_run->kvm_valid_regs & KVM_SYNC_CRS) {

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

            cs->kvm_run->s.regs.acrs[i] = env->aregs[i];

            cs->kvm_run->s.regs.crs[i] = env->cregs[i];

        }

        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_ACRS;

        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_CRS;

    } else {

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

            sregs.acrs[i] = env->aregs[i];

            sregs.crs[i] = env->cregs[i];

        }

        r = kvm_vcpu_ioctl(cs, KVM_SET_SREGS, &sregs);

        if (r < 0) {

            return r;

        }

    }

    /* Finally the prefix */

    if (cap_sync_regs && cs->kvm_run->kvm_valid_regs & KVM_SYNC_PREFIX) {

        cs->kvm_run->s.regs.prefix = env->psa;

        cs->kvm_run->kvm_dirty_regs |= KVM_SYNC_PREFIX;

    } else {

        /* prefix is only supported via sync regs */

    }

    return 0;

}


static void spapr_hotplug_req_event(uint8_t hp_id, uint8_t hp_action,

                                    sPAPRDRConnectorType drc_type,

                                    uint32_t drc)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    struct hp_log_full *new_hp;

    struct rtas_error_log *hdr;

    struct rtas_event_log_v6 *v6hdr;

    struct rtas_event_log_v6_maina *maina;

    struct rtas_event_log_v6_mainb *mainb;

    struct rtas_event_log_v6_hp *hp;

    new_hp = g_malloc0(sizeof(struct hp_log_full));

    hdr = &new_hp->hdr;

    v6hdr = &new_hp->v6hdr;

    maina = &new_hp->maina;

    mainb = &new_hp->mainb;

    hp = &new_hp->hp;

    hdr->summary = cpu_to_be32(RTAS_LOG_VERSION_6

                               | RTAS_LOG_SEVERITY_EVENT

                               | RTAS_LOG_DISPOSITION_NOT_RECOVERED

                               | RTAS_LOG_OPTIONAL_PART_PRESENT

                               | RTAS_LOG_INITIATOR_HOTPLUG

                               | RTAS_LOG_TYPE_HOTPLUG);

    hdr->extended_length = cpu_to_be32(sizeof(*new_hp)

                                       - sizeof(new_hp->hdr));

    spapr_init_v6hdr(v6hdr);

    spapr_init_maina(maina, 3 /* Main-A, Main-B, HP */);

    mainb->hdr.section_id = cpu_to_be16(RTAS_LOG_V6_SECTION_ID_MAINB);

    mainb->hdr.section_length = cpu_to_be16(sizeof(*mainb));

    mainb->subsystem_id = 0x80; /* External environment */

    mainb->event_severity = 0x00; /* Informational / non-error */

    mainb->event_subtype = 0x00; /* Normal shutdown */

    hp->hdr.section_id = cpu_to_be16(RTAS_LOG_V6_SECTION_ID_HOTPLUG);

    hp->hdr.section_length = cpu_to_be16(sizeof(*hp));

    hp->hdr.section_version = 1; /* includes extended modifier */

    hp->hotplug_action = hp_action;

    hp->hotplug_identifier = hp_id;

    switch (drc_type) {

    case SPAPR_DR_CONNECTOR_TYPE_PCI:

        hp->hotplug_type = RTAS_LOG_V6_HP_TYPE_PCI;

        if (hp->hotplug_action == RTAS_LOG_V6_HP_ACTION_ADD) {

            spapr_hotplug_set_signalled(drc);

        }

        break;

    case SPAPR_DR_CONNECTOR_TYPE_LMB:

        hp->hotplug_type = RTAS_LOG_V6_HP_TYPE_MEMORY;

        break;

    case SPAPR_DR_CONNECTOR_TYPE_CPU:

        hp->hotplug_type = RTAS_LOG_V6_HP_TYPE_CPU;

        break;

    default:

        /* we shouldn't be signaling hotplug events for resources

         * that don't support them

         */

        g_assert(false);

        return;

    }

    if (hp_id == RTAS_LOG_V6_HP_ID_DRC_COUNT) {

        hp->drc.count = cpu_to_be32(drc);

    } else if (hp_id == RTAS_LOG_V6_HP_ID_DRC_INDEX) {

        hp->drc.index = cpu_to_be32(drc);

    }

    rtas_event_log_queue(RTAS_LOG_TYPE_HOTPLUG, new_hp, true);

    qemu_irq_pulse(xics_get_qirq(spapr->xics, spapr->check_exception_irq));

}


static int usb_hub_broadcast_packet(USBHubState *s, USBPacket *p)

{

    USBHubPort *port;

    USBDevice *dev;

    int i, ret;

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

        port = &s->ports[i];

        dev = port->port.dev;

        if (dev && (port->wPortStatus & PORT_STAT_ENABLE)) {

            ret = usb_handle_packet(dev, p);

            if (ret != USB_RET_NODEV) {

                return ret;

            }

        }

    }

    return USB_RET_NODEV;

}


BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,

                                  QEMUIOVector *qiov, int nb_sectors,

                                  BlockDriverCompletionFunc *cb, void *opaque)

{

    BlockDriver *drv = bs->drv;

    BlockDriverAIOCB *ret;

    if (!drv)

        return NULL;

    if (bs->read_only)

        return NULL;

    if (bdrv_check_request(bs, sector_num, nb_sectors))

        return NULL;

    if (bs->dirty_tracking) {

        set_dirty_bitmap(bs, sector_num, nb_sectors, 1);

    }

    ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,

                               cb, opaque);

    if (ret) {

	/* Update stats even though technically transfer has not happened. */

	bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;

	bs->wr_ops ++;

    }

    return ret;

}


av_cold void ff_dct_init_x86(DCTContext *s)

{

    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_SSE(cpu_flags))

        s->dct32 = ff_dct32_float_sse;

    if (EXTERNAL_SSE2(cpu_flags))

        s->dct32 = ff_dct32_float_sse2;

    if (EXTERNAL_AVX(cpu_flags))

        s->dct32 = ff_dct32_float_avx;

}


static int msrle_decode_pal4(AVCodecContext *avctx, AVPicture *pic,

                             GetByteContext *gb)

{

    unsigned char rle_code;

    unsigned char extra_byte, odd_pixel;

    unsigned char stream_byte;

    unsigned int pixel_ptr = 0;

    int row_dec = pic->linesize[0];

    int row_ptr = (avctx->height - 1) * row_dec;

    int frame_size = row_dec * avctx->height;

    int i;

    while (row_ptr >= 0) {

        if (bytestream2_get_bytes_left(gb) <= 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "MS RLE: bytestream overrun, %d rows left\n",

                   row_ptr);

            return AVERROR_INVALIDDATA;

        }

        rle_code = stream_byte = bytestream2_get_byteu(gb);

        if (rle_code == 0) {

            /* fetch the next byte to see how to handle escape code */

            stream_byte = bytestream2_get_byte(gb);

            if (stream_byte == 0) {

                /* line is done, goto the next one */

                row_ptr -= row_dec;

                pixel_ptr = 0;

            } else if (stream_byte == 1) {

                /* decode is done */

                return 0;

            } else if (stream_byte == 2) {

                /* reposition frame decode coordinates */

                stream_byte = bytestream2_get_byte(gb);

                pixel_ptr += stream_byte;

                stream_byte = bytestream2_get_byte(gb);

                row_ptr -= stream_byte * row_dec;

            } else {

                // copy pixels from encoded stream

                odd_pixel =  stream_byte & 1;

                rle_code = (stream_byte + 1) / 2;

                extra_byte = rle_code & 0x01;

                if (row_ptr + pixel_ptr + stream_byte > frame_size ||

                    bytestream2_get_bytes_left(gb) < rle_code) {

                    av_log(avctx, AV_LOG_ERROR,

                           "MS RLE: frame/stream ptr just went out of bounds (copy)\n");

                    return AVERROR_INVALIDDATA;

                }

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

                    if (pixel_ptr >= avctx->width)

                        break;

                    stream_byte = bytestream2_get_byteu(gb);

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;

                    pixel_ptr++;

                    if (i + 1 == rle_code && odd_pixel)

                        break;

                    if (pixel_ptr >= avctx->width)

                        break;

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;

                    pixel_ptr++;

                }

                // if the RLE code is odd, skip a byte in the stream

                if (extra_byte)

                    bytestream2_skip(gb, 1);

            }

        } else {

            // decode a run of data

            if (row_ptr + pixel_ptr + stream_byte > frame_size) {

                av_log(avctx, AV_LOG_ERROR,

                       "MS RLE: frame ptr just went out of bounds (run)\n");

                return AVERROR_INVALIDDATA;

            }

            stream_byte = bytestream2_get_byte(gb);

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

                if (pixel_ptr >= avctx->width)

                    break;

                if ((i & 1) == 0)

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte >> 4;

                else

                    pic->data[0][row_ptr + pixel_ptr] = stream_byte & 0x0F;

                pixel_ptr++;

            }

        }

    }

    /* one last sanity check on the way out */

    if (bytestream2_get_bytes_left(gb)) {

        av_log(avctx, AV_LOG_ERROR,

               "MS RLE: ended frame decode with %d bytes left over\n",

               bytestream2_get_bytes_left(gb));

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


void HELPER(mvc)(CPUS390XState *env, uint32_t l, uint64_t dest, uint64_t src)

{

    int i = 0;

    int x = 0;

    uint32_t l_64 = (l + 1) / 8;

    HELPER_LOG("%s l %d dest %" PRIx64 " src %" PRIx64 "\n",

               __func__, l, dest, src);

#ifndef CONFIG_USER_ONLY

    if ((l > 32) &&

        (src & TARGET_PAGE_MASK) == ((src + l) & TARGET_PAGE_MASK) &&

        (dest & TARGET_PAGE_MASK) == ((dest + l) & TARGET_PAGE_MASK)) {

        if (dest == (src + 1)) {

            mvc_fast_memset(env, l + 1, dest, cpu_ldub_data(env, src));

            return;

        } else if ((src & TARGET_PAGE_MASK) != (dest & TARGET_PAGE_MASK)) {

            mvc_fast_memmove(env, l + 1, dest, src);

            return;

        }

    }

#else

    if (dest == (src + 1)) {

        memset(g2h(dest), cpu_ldub_data(env, src), l + 1);

        return;

    } else {

        memmove(g2h(dest), g2h(src), l + 1);

        return;

    }

#endif

    /* handle the parts that fit into 8-byte loads/stores */

    if (dest != (src + 1)) {

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

            cpu_stq_data(env, dest + x, cpu_ldq_data(env, src + x));

            x += 8;

        }

    }

    /* slow version crossing pages with byte accesses */

    for (i = x; i <= l; i++) {

        cpu_stb_data(env, dest + i, cpu_ldub_data(env, src + i));

    }

}


static void test_properties(const char *path, bool recurse)

{

    char *child_path;

    QDict *response, *tuple;

    QList *list;

    QListEntry *entry;

    g_test_message("Obtaining properties of %s", path);

    response = qmp("{ 'execute': 'qom-list',"

                   "  'arguments': { 'path': %s } }", path);

    g_assert(response);

    if (!recurse) {

        return;

    }

    g_assert(qdict_haskey(response, "return"));

    list = qobject_to_qlist(qdict_get(response, "return"));

    QLIST_FOREACH_ENTRY(list, entry) {

        tuple = qobject_to_qdict(qlist_entry_obj(entry));

        bool is_child = strstart(qdict_get_str(tuple, "type"), "child<", NULL);

        bool is_link = strstart(qdict_get_str(tuple, "type"), "link<", NULL);

        if (is_child || is_link) {

            child_path = g_strdup_printf("%s/%s",

                                         path, qdict_get_str(tuple, "name"));

            test_properties(child_path, is_child);

            g_free(child_path);

        } else {

            const char *prop = qdict_get_str(tuple, "name");

            g_test_message("Testing property %s.%s", path, prop);

            response = qmp("{ 'execute': 'qom-get',"

                           "  'arguments': { 'path': %s,"

                           "                 'property': %s } }",

                           path, prop);

            /* qom-get may fail but should not, e.g., segfault. */

            g_assert(response);

        }

    }

}


static int thp_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    ThpDemuxContext *thp = s->priv_data;

    AVStream *st;

    AVIOContext *pb = s->pb;

    int i;

    /* Read the file header.  */

                           avio_rb32(pb); /* Skip Magic.  */

    thp->version         = avio_rb32(pb);

                           avio_rb32(pb); /* Max buf size.  */

                           avio_rb32(pb); /* Max samples.  */

    thp->fps             = av_d2q(av_int2float(avio_rb32(pb)), INT_MAX);

    thp->framecnt        = avio_rb32(pb);

    thp->first_framesz   = avio_rb32(pb);

                           avio_rb32(pb); /* Data size.  */

    thp->compoff         = avio_rb32(pb);

                           avio_rb32(pb); /* offsetDataOffset.  */

    thp->first_frame     = avio_rb32(pb);

    thp->last_frame      = avio_rb32(pb);

    thp->next_framesz    = thp->first_framesz;

    thp->next_frame      = thp->first_frame;

    /* Read the component structure.  */

    avio_seek (pb, thp->compoff, SEEK_SET);

    thp->compcount       = avio_rb32(pb);

    /* Read the list of component types.  */

    avio_read(pb, thp->components, 16);

    for (i = 0; i < thp->compcount; i++) {

        if (thp->components[i] == 0) {

            if (thp->vst != 0)

                break;

            /* Video component.  */

            st = avformat_new_stream(s, NULL);

            if (!st)

                return AVERROR(ENOMEM);

            /* The denominator and numerator are switched because 1/fps

               is required.  */

            avpriv_set_pts_info(st, 64, thp->fps.den, thp->fps.num);

            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            st->codec->codec_id = CODEC_ID_THP;

            st->codec->codec_tag = 0;  /* no fourcc */

            st->codec->width = avio_rb32(pb);

            st->codec->height = avio_rb32(pb);

            st->codec->sample_rate = av_q2d(thp->fps);

            thp->vst = st;

            thp->video_stream_index = st->index;

            if (thp->version == 0x11000)

                avio_rb32(pb); /* Unknown.  */

        } else if (thp->components[i] == 1) {

            if (thp->has_audio != 0)

                break;

            /* Audio component.  */

            st = avformat_new_stream(s, NULL);

            if (!st)

                return AVERROR(ENOMEM);

            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            st->codec->codec_id = CODEC_ID_ADPCM_THP;

            st->codec->codec_tag = 0;  /* no fourcc */

            st->codec->channels    = avio_rb32(pb); /* numChannels.  */

            st->codec->sample_rate = avio_rb32(pb); /* Frequency.  */

            avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

            thp->audio_stream_index = st->index;

            thp->has_audio = 1;

        }

    }

    return 0;

}


static int rdma_add_block(RDMAContext *rdma, const char *block_name,

                         void *host_addr,

                         ram_addr_t block_offset, uint64_t length)

{

    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    RDMALocalBlock *block;

    RDMALocalBlock *old = local->block;

    local->block = g_malloc0(sizeof(RDMALocalBlock) * (local->nb_blocks + 1));

    if (local->nb_blocks) {

        int x;

        if (rdma->blockmap) {

            for (x = 0; x < local->nb_blocks; x++) {

                g_hash_table_remove(rdma->blockmap,

                                    (void *)(uintptr_t)old[x].offset);

                g_hash_table_insert(rdma->blockmap,

                                    (void *)(uintptr_t)old[x].offset,

                                    &local->block[x]);

            }

        }

        memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks);

        g_free(old);

    }

    block = &local->block[local->nb_blocks];

    block->block_name = g_strdup(block_name);

    block->local_host_addr = host_addr;

    block->offset = block_offset;

    block->length = length;

    block->index = local->nb_blocks;

    block->src_index = ~0U; /* Filled in by the receipt of the block list */

    block->nb_chunks = ram_chunk_index(host_addr, host_addr + length) + 1UL;

    block->transit_bitmap = bitmap_new(block->nb_chunks);

    bitmap_clear(block->transit_bitmap, 0, block->nb_chunks);

    block->unregister_bitmap = bitmap_new(block->nb_chunks);

    bitmap_clear(block->unregister_bitmap, 0, block->nb_chunks);

    block->remote_keys = g_malloc0(block->nb_chunks * sizeof(uint32_t));

    block->is_ram_block = local->init ? false : true;

    if (rdma->blockmap) {

        g_hash_table_insert(rdma->blockmap, (void *) block_offset, block);

    }

    trace_rdma_add_block(block_name, local->nb_blocks,

                         (uintptr_t) block->local_host_addr,

                         block->offset, block->length,

                         (uintptr_t) (block->local_host_addr + block->length),

                         BITS_TO_LONGS(block->nb_chunks) *

                             sizeof(unsigned long) * 8,

                         block->nb_chunks);

    local->nb_blocks++;

    return 0;

}


process_tx_desc(E1000State *s, struct e1000_tx_desc *dp)

{

    uint32_t txd_lower = le32_to_cpu(dp->lower.data);

    uint32_t dtype = txd_lower & (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D);

    unsigned int split_size = txd_lower & 0xffff, bytes, sz, op;

    unsigned int msh = 0xfffff, hdr = 0;

    uint64_t addr;

    struct e1000_context_desc *xp = (struct e1000_context_desc *)dp;

    struct e1000_tx *tp = &s->tx;

    if (dtype == E1000_TXD_CMD_DEXT) {	// context descriptor

        op = le32_to_cpu(xp->cmd_and_length);

        tp->ipcss = xp->lower_setup.ip_fields.ipcss;

        tp->ipcso = xp->lower_setup.ip_fields.ipcso;

        tp->ipcse = le16_to_cpu(xp->lower_setup.ip_fields.ipcse);

        tp->tucss = xp->upper_setup.tcp_fields.tucss;

        tp->tucso = xp->upper_setup.tcp_fields.tucso;

        tp->tucse = le16_to_cpu(xp->upper_setup.tcp_fields.tucse);

        tp->paylen = op & 0xfffff;

        tp->hdr_len = xp->tcp_seg_setup.fields.hdr_len;

        tp->mss = le16_to_cpu(xp->tcp_seg_setup.fields.mss);

        tp->ip = (op & E1000_TXD_CMD_IP) ? 1 : 0;

        tp->tcp = (op & E1000_TXD_CMD_TCP) ? 1 : 0;

        tp->tse = (op & E1000_TXD_CMD_TSE) ? 1 : 0;

        tp->tso_frames = 0;

        if (tp->tucso == 0) {	// this is probably wrong

            DBGOUT(TXSUM, "TCP/UDP: cso 0!\n");

            tp->tucso = tp->tucss + (tp->tcp ? 16 : 6);

        }

        return;

    } else if (dtype == (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)) {

        // data descriptor

        if (tp->size == 0) {

            tp->sum_needed = le32_to_cpu(dp->upper.data) >> 8;

        }

        tp->cptse = ( txd_lower & E1000_TXD_CMD_TSE ) ? 1 : 0;

    } else {

        // legacy descriptor

        tp->cptse = 0;

    }

    if (vlan_enabled(s) && is_vlan_txd(txd_lower) &&

        (tp->cptse || txd_lower & E1000_TXD_CMD_EOP)) {

        tp->vlan_needed = 1;

        cpu_to_be16wu((uint16_t *)(tp->vlan_header),

                      le16_to_cpup((uint16_t *)(s->mac_reg + VET)));

        cpu_to_be16wu((uint16_t *)(tp->vlan_header + 2),

                      le16_to_cpu(dp->upper.fields.special));

    }

    addr = le64_to_cpu(dp->buffer_addr);

    if (tp->tse && tp->cptse) {

        hdr = tp->hdr_len;

        msh = hdr + tp->mss;

        do {

            bytes = split_size;

            if (tp->size + bytes > msh)

                bytes = msh - tp->size;

            bytes = MIN(sizeof(tp->data) - tp->size, bytes);

            pci_dma_read(&s->dev, addr, tp->data + tp->size, bytes);

            if ((sz = tp->size + bytes) >= hdr && tp->size < hdr)

                memmove(tp->header, tp->data, hdr);

            tp->size = sz;

            addr += bytes;

            if (sz == msh) {

                xmit_seg(s);

                memmove(tp->data, tp->header, hdr);

                tp->size = hdr;

            }

        } while (split_size -= bytes);

    } else if (!tp->tse && tp->cptse) {

        // context descriptor TSE is not set, while data descriptor TSE is set

        DBGOUT(TXERR, "TCP segmentaion Error\n");

    } else {

        pci_dma_read(&s->dev, addr, tp->data + tp->size, split_size);

        tp->size += split_size;

    }

    if (!(txd_lower & E1000_TXD_CMD_EOP))

        return;

    if (!(tp->tse && tp->cptse && tp->size < hdr))

        xmit_seg(s);

    tp->tso_frames = 0;

    tp->sum_needed = 0;

    tp->vlan_needed = 0;

    tp->size = 0;

    tp->cptse = 0;

}


static void virtio_input_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)

{

    VirtIOInputPCI *vinput = VIRTIO_INPUT_PCI(vpci_dev);

    DeviceState *vdev = DEVICE(&vinput->vdev);

    qdev_set_parent_bus(vdev, BUS(&vpci_dev->bus));

    /* force virtio-1.0 */

    vpci_dev->flags &= ~VIRTIO_PCI_FLAG_DISABLE_MODERN;

    vpci_dev->flags |= VIRTIO_PCI_FLAG_DISABLE_LEGACY;

    object_property_set_bool(OBJECT(vdev), true, "realized", errp);

}


static void test_visitor_out_string(TestOutputVisitorData *data,

                                    const void *unused)

{

    char *string = (char *) "Q E M U";

    Error *err = NULL;

    QObject *obj;

    visit_type_str(data->ov, &string, NULL, &err);

    g_assert(!err);

    obj = qmp_output_get_qobject(data->qov);

    g_assert(obj != NULL);

    g_assert(qobject_type(obj) == QTYPE_QSTRING);

    g_assert_cmpstr(qstring_get_str(qobject_to_qstring(obj)), ==, string);

    qobject_decref(obj);

}


static void pc_machine_set_vmport(Object *obj, bool value, Error **errp)

{

    PCMachineState *pcms = PC_MACHINE(obj);

    pcms->vmport = value;

}


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

{

    AVStream *st;

    MOVStreamContext *sc;

    int ret;

    st = avformat_new_stream(c->fc, NULL);

    if (!st) return AVERROR(ENOMEM);

    st->id = c->fc->nb_streams;

    sc = av_mallocz(sizeof(MOVStreamContext));

    if (!sc) return AVERROR(ENOMEM);

    st->priv_data = sc;

    st->codec->codec_type = AVMEDIA_TYPE_DATA;

    sc->ffindex = st->index;

    if ((ret = mov_read_default(c, pb, atom)) < 0)

        return ret;

    /* sanity checks */

    if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||

                            (!sc->sample_size && !sc->sample_count))) {

        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",

               st->index);

        return 0;

    }

    fix_timescale(c, sc);

    avpriv_set_pts_info(st, 64, 1, sc->time_scale);

    mov_build_index(c, st);

    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {

        MOVDref *dref = &sc->drefs[sc->dref_id - 1];

        if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,

            c->use_absolute_path, c->fc) < 0)

            av_log(c->fc, AV_LOG_ERROR,

                   "stream %d, error opening alias: path='%s', dir='%s', "

                   "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",

                   st->index, dref->path, dref->dir, dref->filename,

                   dref->volume, dref->nlvl_from, dref->nlvl_to);

    } else {

        sc->pb = c->fc->pb;

        sc->pb_is_copied = 1;

    }

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

        if (!st->sample_aspect_ratio.num &&

            (st->codec->width != sc->width || st->codec->height != sc->height)) {

            st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /

                                             ((double)st->codec->width * sc->height), INT_MAX);

        }

#if FF_API_R_FRAME_RATE

        if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))

            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,

                      sc->time_scale, sc->stts_data[0].duration, INT_MAX);

#endif

    }

    // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.

    if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&

        TAG_IS_AVCI(st->codec->codec_tag)) {

        ret = ff_generate_avci_extradata(st);

        if (ret < 0)

            return ret;

    }

    switch (st->codec->codec_id) {

#if CONFIG_H261_DECODER

    case AV_CODEC_ID_H261:

#endif

#if CONFIG_H263_DECODER

    case AV_CODEC_ID_H263:

#endif

#if CONFIG_MPEG4_DECODER

    case AV_CODEC_ID_MPEG4:

#endif

        st->codec->width = 0; /* let decoder init width/height */

        st->codec->height= 0;

        break;

    }

    /* Do not need those anymore. */

    av_freep(&sc->chunk_offsets);

    av_freep(&sc->stsc_data);

    av_freep(&sc->sample_sizes);

    av_freep(&sc->keyframes);

    av_freep(&sc->stts_data);

    av_freep(&sc->stps_data);

    av_freep(&sc->elst_data);

    av_freep(&sc->rap_group);

    return 0;

}


static int buffer_empty(Buffer *buffer)

{

    return buffer->offset == 0;

}


static gboolean pty_chr_timer(gpointer opaque)

{

    struct CharDriverState *chr = opaque;

    PtyCharDriver *s = chr->opaque;

    if (s->connected) {

        goto out;

    }

    /* Next poll ... */

    pty_chr_update_read_handler(chr);

out:

    s->timer_tag = 0;

    return FALSE;

}


void h263_encode_init(MpegEncContext *s)

{

    static int done = 0;

    if (!done) {

        done = 1;

        init_uni_dc_tab();

        init_rl(&rl_inter);

        init_rl(&rl_intra);

        init_rl(&rl_intra_aic);

        init_uni_mpeg4_rl_tab(&rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);

        init_uni_mpeg4_rl_tab(&rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);

        init_uni_h263_rl_tab(&rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);

        init_uni_h263_rl_tab(&rl_inter    , NULL, uni_h263_inter_rl_len);

        init_mv_penalty_and_fcode(s);

    }

    s->me.mv_penalty= mv_penalty; //FIXME exact table for msmpeg4 & h263p

    s->intra_ac_vlc_length     =s->inter_ac_vlc_length     = uni_h263_inter_rl_len;

    s->intra_ac_vlc_last_length=s->inter_ac_vlc_last_length= uni_h263_inter_rl_len + 128*64;

    if(s->h263_aic){

        s->intra_ac_vlc_length     = uni_h263_intra_aic_rl_len;

        s->intra_ac_vlc_last_length= uni_h263_intra_aic_rl_len + 128*64;

    }

    s->ac_esc_length= 7+1+6+8;

    // use fcodes >1 only for mpeg4 & h263 & h263p FIXME

    switch(s->codec_id){

    case CODEC_ID_MPEG4:

        s->fcode_tab= fcode_tab;

        s->min_qcoeff= -2048;

        s->max_qcoeff=  2047;

        s->intra_ac_vlc_length     = uni_mpeg4_intra_rl_len;

        s->intra_ac_vlc_last_length= uni_mpeg4_intra_rl_len + 128*64;

        s->inter_ac_vlc_length     = uni_mpeg4_inter_rl_len;

        s->inter_ac_vlc_last_length= uni_mpeg4_inter_rl_len + 128*64;

        s->luma_dc_vlc_length= uni_DCtab_lum_len;

        s->chroma_dc_vlc_length= uni_DCtab_chrom_len;

        s->ac_esc_length= 7+2+1+6+1+12+1;

        s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;

        s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;

        if(s->flags & CODEC_FLAG_GLOBAL_HEADER){

            s->avctx->extradata= av_malloc(1024);

            init_put_bits(&s->pb, s->avctx->extradata, 1024);

            mpeg4_encode_visual_object_header(s);

            mpeg4_encode_vol_header(s, 0, 0);

//            ff_mpeg4_stuffing(&s->pb); ?

            flush_put_bits(&s->pb);

            s->avctx->extradata_size= (put_bits_count(&s->pb)+7)>>3;

        }

        break;

    case CODEC_ID_H263P:

        if(s->umvplus)

            s->fcode_tab= umv_fcode_tab;

        if(s->modified_quant){

            s->min_qcoeff= -2047;

            s->max_qcoeff=  2047;

        }else{

            s->min_qcoeff= -127;

            s->max_qcoeff=  127;

        }

        break;

        //Note for mpeg4 & h263 the dc-scale table will be set per frame as needed later

    case CODEC_ID_FLV1:

        if (s->h263_flv > 1) {

            s->min_qcoeff= -1023;

            s->max_qcoeff=  1023;

        } else {

            s->min_qcoeff= -127;

            s->max_qcoeff=  127;

        }

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

        break;

    default: //nothing needed default table allready set in mpegvideo.c

        s->min_qcoeff= -127;

        s->max_qcoeff=  127;

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

    }

}


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

                              BdrvCheckMode fix)

{

    BDRVQcow2State *s = bs->opaque;

    uint64_t *l2_table = qemu_blockalign(bs, s->cluster_size);

    int ret;

    uint64_t refcount;

    int i, j;

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

        uint64_t l1_entry = s->l1_table[i];

        uint64_t l2_offset = l1_entry & L1E_OFFSET_MASK;

        bool l2_dirty = false;

        if (!l2_offset) {

            continue;

        }

        ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,

                                 &refcount);

        if (ret < 0) {

            /* don't print message nor increment check_errors */

            continue;

        }

        if ((refcount == 1) != ((l1_entry & QCOW_OFLAG_COPIED) != 0)) {

            fprintf(stderr, "%s OFLAG_COPIED L2 cluster: l1_index=%d "

                    "l1_entry=%" PRIx64 " refcount=%" PRIu64 "\n",

                    fix & BDRV_FIX_ERRORS ? "Repairing" :

                                            "ERROR",

                    i, l1_entry, refcount);

            if (fix & BDRV_FIX_ERRORS) {

                s->l1_table[i] = refcount == 1

                               ? l1_entry |  QCOW_OFLAG_COPIED

                               : l1_entry & ~QCOW_OFLAG_COPIED;

                ret = qcow2_write_l1_entry(bs, i);

                if (ret < 0) {

                    res->check_errors++;

                    goto fail;

                }

                res->corruptions_fixed++;

            } else {

                res->corruptions++;

            }

        }

        ret = bdrv_pread(bs->file, l2_offset, l2_table,

                         s->l2_size * sizeof(uint64_t));

        if (ret < 0) {

            fprintf(stderr, "ERROR: Could not read L2 table: %s\n",

                    strerror(-ret));

            res->check_errors++;

            goto fail;

        }

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

            uint64_t l2_entry = be64_to_cpu(l2_table[j]);

            uint64_t data_offset = l2_entry & L2E_OFFSET_MASK;

            QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);

            if ((cluster_type == QCOW2_CLUSTER_NORMAL) ||

                ((cluster_type == QCOW2_CLUSTER_ZERO) && (data_offset != 0))) {

                ret = qcow2_get_refcount(bs,

                                         data_offset >> s->cluster_bits,

                                         &refcount);

                if (ret < 0) {

                    /* don't print message nor increment check_errors */

                    continue;

                }

                if ((refcount == 1) != ((l2_entry & QCOW_OFLAG_COPIED) != 0)) {

                    fprintf(stderr, "%s OFLAG_COPIED data cluster: "

                            "l2_entry=%" PRIx64 " refcount=%" PRIu64 "\n",

                            fix & BDRV_FIX_ERRORS ? "Repairing" :

                                                    "ERROR",

                            l2_entry, refcount);

                    if (fix & BDRV_FIX_ERRORS) {

                        l2_table[j] = cpu_to_be64(refcount == 1

                                    ? l2_entry |  QCOW_OFLAG_COPIED

                                    : l2_entry & ~QCOW_OFLAG_COPIED);

                        l2_dirty = true;

                        res->corruptions_fixed++;

                    } else {

                        res->corruptions++;

                    }

                }

            }

        }

        if (l2_dirty) {

            ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L2,

                                                l2_offset, s->cluster_size);

            if (ret < 0) {

                fprintf(stderr, "ERROR: Could not write L2 table; metadata "

                        "overlap check failed: %s\n", strerror(-ret));

                res->check_errors++;

                goto fail;

            }

            ret = bdrv_pwrite(bs->file, l2_offset, l2_table,

                              s->cluster_size);

            if (ret < 0) {

                fprintf(stderr, "ERROR: Could not write L2 table: %s\n",

                        strerror(-ret));

                res->check_errors++;

                goto fail;

            }

        }

    }

    ret = 0;

fail:

    qemu_vfree(l2_table);

    return ret;

}


static void mainstone_common_init(MemoryRegion *address_space_mem,

                                  MachineState *machine,

                                  enum mainstone_model_e model, int arm_id)

{

    uint32_t sector_len = 256 * 1024;

    hwaddr mainstone_flash_base[] = { MST_FLASH_0, MST_FLASH_1 };

    PXA2xxState *mpu;

    DeviceState *mst_irq;

    DriveInfo *dinfo;

    int i;

    int be;

    MemoryRegion *rom = g_new(MemoryRegion, 1);

    const char *cpu_model = machine->cpu_model;

    if (!cpu_model)

        cpu_model = "pxa270-c5";

    /* Setup CPU & memory */

    mpu = pxa270_init(address_space_mem, mainstone_binfo.ram_size, cpu_model);

    memory_region_init_ram(rom, NULL, "mainstone.rom", MAINSTONE_ROM,

                           &error_abort);

    vmstate_register_ram_global(rom);

    memory_region_set_readonly(rom, true);

    memory_region_add_subregion(address_space_mem, 0, rom);

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    /* There are two 32MiB flash devices on the board */

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

        dinfo = drive_get(IF_PFLASH, 0, i);

        if (!dinfo) {

            if (qtest_enabled()) {

                break;

            }

            fprintf(stderr, "Two flash images must be given with the "

                    "'pflash' parameter\n");

            exit(1);

        }

        if (!pflash_cfi01_register(mainstone_flash_base[i], NULL,

                                   i ? "mainstone.flash1" : "mainstone.flash0",

                                   MAINSTONE_FLASH,

                                   blk_bs(blk_by_legacy_dinfo(dinfo)),

                                   sector_len, MAINSTONE_FLASH / sector_len,

                                   4, 0, 0, 0, 0, be)) {

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

            exit(1);

        }

    }

    mst_irq = sysbus_create_simple("mainstone-fpga", MST_FPGA_PHYS,

                    qdev_get_gpio_in(mpu->gpio, 0));

    /* setup keypad */

    pxa27x_register_keypad(mpu->kp, map, 0xe0);

    /* MMC/SD host */

    pxa2xx_mmci_handlers(mpu->mmc, NULL, qdev_get_gpio_in(mst_irq, MMC_IRQ));

    pxa2xx_pcmcia_set_irq_cb(mpu->pcmcia[0],

            qdev_get_gpio_in(mst_irq, S0_IRQ),

            qdev_get_gpio_in(mst_irq, S0_CD_IRQ));

    pxa2xx_pcmcia_set_irq_cb(mpu->pcmcia[1],

            qdev_get_gpio_in(mst_irq, S1_IRQ),

            qdev_get_gpio_in(mst_irq, S1_CD_IRQ));

    smc91c111_init(&nd_table[0], MST_ETH_PHYS,

                    qdev_get_gpio_in(mst_irq, ETHERNET_IRQ));

    mainstone_binfo.kernel_filename = machine->kernel_filename;

    mainstone_binfo.kernel_cmdline = machine->kernel_cmdline;

    mainstone_binfo.initrd_filename = machine->initrd_filename;

    mainstone_binfo.board_id = arm_id;

    arm_load_kernel(mpu->cpu, &mainstone_binfo);

}


static inline void RENAME(vu9_to_vu12)(const uint8_t *src1, const uint8_t *src2,

			uint8_t *dst1, uint8_t *dst2,

			long width, long height,

			long srcStride1, long srcStride2,

			long dstStride1, long dstStride2)

{

    long y,x,w,h;

    w=width/2; h=height/2;

#ifdef HAVE_MMX

    asm volatile(

	PREFETCH" %0\n\t"

	PREFETCH" %1\n\t"

	::"m"(*(src1+srcStride1)),"m"(*(src2+srcStride2)):"memory");

#endif

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

	const uint8_t* s1=src1+srcStride1*(y>>1);

	uint8_t* d=dst1+dstStride1*y;

	x=0;

#ifdef HAVE_MMX

	for(;x<w-31;x+=32)

	{

	    asm volatile(

		PREFETCH" 32%1\n\t"

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

	        "movq	8%1, %%mm2\n\t"

	        "movq	16%1, %%mm4\n\t"

	        "movq	24%1, %%mm6\n\t"

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

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

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

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

		"punpcklbw %%mm0, %%mm0\n\t"

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

		"punpcklbw %%mm2, %%mm2\n\t"

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

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

		"punpckhbw %%mm5, %%mm5\n\t"

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

		"punpckhbw %%mm7, %%mm7\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		MOVNTQ"	%%mm1, 8%0\n\t"

		MOVNTQ"	%%mm2, 16%0\n\t"

		MOVNTQ"	%%mm3, 24%0\n\t"

		MOVNTQ"	%%mm4, 32%0\n\t"

		MOVNTQ"	%%mm5, 40%0\n\t"

		MOVNTQ"	%%mm6, 48%0\n\t"

		MOVNTQ"	%%mm7, 56%0"

		:"=m"(d[2*x])

		:"m"(s1[x])

		:"memory");

	}

#endif

	for(;x<w;x++) d[2*x]=d[2*x+1]=s1[x];

    }

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

	const uint8_t* s2=src2+srcStride2*(y>>1);

	uint8_t* d=dst2+dstStride2*y;

	x=0;

#ifdef HAVE_MMX

	for(;x<w-31;x+=32)

	{

	    asm volatile(

		PREFETCH" 32%1\n\t"

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

	        "movq	8%1, %%mm2\n\t"

	        "movq	16%1, %%mm4\n\t"

	        "movq	24%1, %%mm6\n\t"

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

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

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

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

		"punpcklbw %%mm0, %%mm0\n\t"

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

		"punpcklbw %%mm2, %%mm2\n\t"

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

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

		"punpckhbw %%mm5, %%mm5\n\t"

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

		"punpckhbw %%mm7, %%mm7\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		MOVNTQ"	%%mm1, 8%0\n\t"

		MOVNTQ"	%%mm2, 16%0\n\t"

		MOVNTQ"	%%mm3, 24%0\n\t"

		MOVNTQ"	%%mm4, 32%0\n\t"

		MOVNTQ"	%%mm5, 40%0\n\t"

		MOVNTQ"	%%mm6, 48%0\n\t"

		MOVNTQ"	%%mm7, 56%0"

		:"=m"(d[2*x])

		:"m"(s2[x])

		:"memory");

	}

#endif

	for(;x<w;x++) d[2*x]=d[2*x+1]=s2[x];

    }

#ifdef HAVE_MMX

	asm(

		EMMS" \n\t"

		SFENCE" \n\t"

		::: "memory"

		);

#endif

}


static void puv3_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *initrd_filename = machine->initrd_filename;

    CPUUniCore32State *env;

    UniCore32CPU *cpu;

    if (initrd_filename) {

        error_report("Please use kernel built-in initramdisk");

        exit(1);

    }

    if (!cpu_model) {

        cpu_model = "UniCore-II";

    }

    cpu = UNICORE32_CPU(cpu_generic_init(TYPE_UNICORE32_CPU, cpu_model));

    if (!cpu) {

        error_report("Unable to find CPU definition");

        exit(1);

    }

    env = &cpu->env;

    puv3_soc_init(env);

    puv3_board_init(env, ram_size);

    puv3_load_kernel(kernel_filename);

}


static int output_data_internal(MLPDecodeContext *m, unsigned int substr,

                                uint8_t *data, unsigned int *data_size, int is32)

{

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

    unsigned int i, out_ch = 0;

    int32_t *data_32 = (int32_t*) data;

    int16_t *data_16 = (int16_t*) data;

    if (*data_size < (s->max_channel + 1) * s->blockpos * (is32 ? 4 : 2))

        return -1;

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

        for (out_ch = 0; out_ch <= s->max_matrix_channel; out_ch++) {

            int mat_ch = s->ch_assign[out_ch];

            int32_t sample = m->sample_buffer[i][mat_ch]

                          << s->output_shift[mat_ch];

            s->lossless_check_data ^= (sample & 0xffffff) << mat_ch;

            if (is32) *data_32++ = sample << 8;

            else      *data_16++ = sample >> 8;

        }

    }

    *data_size = i * out_ch * (is32 ? 4 : 2);

    return 0;

}


static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,

                                 uint64_t end_offset, void **p_feature_table,

                                 Error **errp)

{

    BDRVQcowState *s = bs->opaque;

    QCowExtension ext;

    uint64_t offset;

    int ret;

#ifdef DEBUG_EXT

    printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);

#endif

    offset = start_offset;

    while (offset < end_offset) {

#ifdef DEBUG_EXT

        /* Sanity check */

        if (offset > s->cluster_size)

            printf("qcow2_read_extension: suspicious offset %lu\n", offset);

        printf("attempting to read extended header in offset %lu\n", offset);

#endif

        ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));

        if (ret < 0) {

            error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "

                             "pread fail from offset %" PRIu64, offset);

            return 1;

        }

        be32_to_cpus(&ext.magic);

        be32_to_cpus(&ext.len);

        offset += sizeof(ext);

#ifdef DEBUG_EXT

        printf("ext.magic = 0x%x\n", ext.magic);

#endif

        if (ext.len > end_offset - offset) {

            error_setg(errp, "Header extension too large");

            return -EINVAL;

        }

        switch (ext.magic) {

        case QCOW2_EXT_MAGIC_END:

            return 0;

        case QCOW2_EXT_MAGIC_BACKING_FORMAT:

            if (ext.len >= sizeof(bs->backing_format)) {

                error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32

                           " too large (>=%zu)", ext.len,

                           sizeof(bs->backing_format));

                return 2;

            }

            ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);

            if (ret < 0) {

                error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "

                                 "Could not read format name");

                return 3;

            }

            bs->backing_format[ext.len] = '\0';

#ifdef DEBUG_EXT

            printf("Qcow2: Got format extension %s\n", bs->backing_format);

#endif

            break;

        case QCOW2_EXT_MAGIC_FEATURE_TABLE:

            if (p_feature_table != NULL) {

                void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));

                ret = bdrv_pread(bs->file, offset , feature_table, ext.len);

                if (ret < 0) {

                    error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "

                                     "Could not read table");

                    return ret;

                }

                *p_feature_table = feature_table;

            }

            break;

        default:

            /* unknown magic - save it in case we need to rewrite the header */

            {

                Qcow2UnknownHeaderExtension *uext;

                uext = g_malloc0(sizeof(*uext)  + ext.len);

                uext->magic = ext.magic;

                uext->len = ext.len;

                QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);

                ret = bdrv_pread(bs->file, offset , uext->data, uext->len);

                if (ret < 0) {

                    error_setg_errno(errp, -ret, "ERROR: unknown extension: "

                                     "Could not read data");

                    return ret;

                }

            }

            break;

        }

        offset += ((ext.len + 7) & ~7);

    }

    return 0;

}


inline static void RENAME(hcscale)(SwsContext *c, uint16_t *dst, int dstWidth, const uint8_t *src1, const uint8_t *src2,

                                   int srcW, int xInc, const int16_t *hChrFilter,

                                   const int16_t *hChrFilterPos, int hChrFilterSize,

                                   uint8_t *formatConvBuffer,

                                   uint32_t *pal)

{

    src1 += c->chrSrcOffset;

    src2 += c->chrSrcOffset;

    if (c->chrToYV12) {

        c->chrToYV12(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW, pal);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    if (!c->hcscale_fast) {

        c->hScale(dst     , dstWidth, src1, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

        c->hScale(dst+VOFW, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    } else { // fast bilinear upscale / crap downscale

        c->hcscale_fast(c, dst, dstWidth, src1, src2, srcW, xInc);

    }

    if (c->chrConvertRange)

        c->chrConvertRange(dst, dstWidth);

}


void pl011_init(uint32_t base, qemu_irq irq,

                CharDriverState *chr)

{

    int iomemtype;

    pl011_state *s;

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

    iomemtype = cpu_register_io_memory(0, pl011_readfn,

                                       pl011_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    s->base = base;

    s->irq = irq;

    s->chr = chr;

    s->read_trigger = 1;

    s->ifl = 0x12;

    s->cr = 0x300;

    s->flags = 0x90;

    if (chr){

        qemu_chr_add_handlers(chr, pl011_can_recieve, pl011_recieve,

                              pl011_event, s);

    }

    /* ??? Save/restore.  */

}


static void spr_read_xer (DisasContext *ctx, int gprn, int sprn)

{

    gen_read_xer(cpu_gpr[gprn]);

}


static int cpu_load_old(QEMUFile *f, void *opaque, int version_id)

{

    PowerPCCPU *cpu = opaque;

    CPUPPCState *env = &cpu->env;

    unsigned int i, j;

    target_ulong sdr1;

    uint32_t fpscr;

    target_ulong xer;

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

        qemu_get_betls(f, &env->gpr[i]);

#if !defined(TARGET_PPC64)

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

        qemu_get_betls(f, &env->gprh[i]);

#endif

    qemu_get_betls(f, &env->lr);

    qemu_get_betls(f, &env->ctr);

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

        qemu_get_be32s(f, &env->crf[i]);

    qemu_get_betls(f, &xer);

    cpu_write_xer(env, xer);

    qemu_get_betls(f, &env->reserve_addr);

    qemu_get_betls(f, &env->msr);

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

        qemu_get_betls(f, &env->tgpr[i]);

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

        union {

            float64 d;

            uint64_t l;

        } u;

        u.l = qemu_get_be64(f);

        env->fpr[i] = u.d;

    }

    qemu_get_be32s(f, &fpscr);

    env->fpscr = fpscr;

    qemu_get_sbe32s(f, &env->access_type);

#if defined(TARGET_PPC64)

    qemu_get_betls(f, &env->spr[SPR_ASR]);

    qemu_get_sbe32s(f, &env->slb_nr);

#endif

    qemu_get_betls(f, &sdr1);

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

        qemu_get_betls(f, &env->sr[i]);

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

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

            qemu_get_betls(f, &env->DBAT[i][j]);

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

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

            qemu_get_betls(f, &env->IBAT[i][j]);

    qemu_get_sbe32s(f, &env->nb_tlb);

    qemu_get_sbe32s(f, &env->tlb_per_way);

    qemu_get_sbe32s(f, &env->nb_ways);

    qemu_get_sbe32s(f, &env->last_way);

    qemu_get_sbe32s(f, &env->id_tlbs);

    qemu_get_sbe32s(f, &env->nb_pids);

    if (env->tlb.tlb6) {

        // XXX assumes 6xx

        for (i = 0; i < env->nb_tlb; i++) {

            qemu_get_betls(f, &env->tlb.tlb6[i].pte0);

            qemu_get_betls(f, &env->tlb.tlb6[i].pte1);

            qemu_get_betls(f, &env->tlb.tlb6[i].EPN);

        }

    }

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

        qemu_get_betls(f, &env->pb[i]);

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

        qemu_get_betls(f, &env->spr[i]);

    ppc_store_sdr1(env, sdr1);

    qemu_get_be32s(f, &env->vscr);

    qemu_get_be64s(f, &env->spe_acc);

    qemu_get_be32s(f, &env->spe_fscr);

    qemu_get_betls(f, &env->msr_mask);

    qemu_get_be32s(f, &env->flags);

    qemu_get_sbe32s(f, &env->error_code);

    qemu_get_be32s(f, &env->pending_interrupts);

    qemu_get_be32s(f, &env->irq_input_state);

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

        qemu_get_betls(f, &env->excp_vectors[i]);

    qemu_get_betls(f, &env->excp_prefix);

    qemu_get_betls(f, &env->ivor_mask);

    qemu_get_betls(f, &env->ivpr_mask);

    qemu_get_betls(f, &env->hreset_vector);

    qemu_get_betls(f, &env->nip);

    qemu_get_betls(f, &env->hflags);

    qemu_get_betls(f, &env->hflags_nmsr);

    qemu_get_sbe32s(f, &env->mmu_idx);

    qemu_get_sbe32(f); /* Discard unused power_mode */

    return 0;

}


static void test_qemu_strtoul_invalid(void)

{

    const char *str = "   xxxx  \t abc";

    char f = 'X';

    const char *endptr = &f;

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert(endptr == str);

}