void tb_invalidate_phys_page_range(tb_page_addr_t start, tb_page_addr_t end,

                                   int is_cpu_write_access)

{

    TranslationBlock *tb, *tb_next;

#if defined(TARGET_HAS_PRECISE_SMC)

    CPUState *cpu = current_cpu;

    CPUArchState *env = NULL;

#endif

    tb_page_addr_t tb_start, tb_end;

    PageDesc *p;

    int n;

#ifdef TARGET_HAS_PRECISE_SMC

    int current_tb_not_found = is_cpu_write_access;

    TranslationBlock *current_tb = NULL;

    int current_tb_modified = 0;

    target_ulong current_pc = 0;

    target_ulong current_cs_base = 0;

    uint32_t current_flags = 0;

#endif /* TARGET_HAS_PRECISE_SMC */

    assert_memory_lock();

    assert_tb_locked();

    p = page_find(start >> TARGET_PAGE_BITS);

    if (!p) {

        return;

    }

#if defined(TARGET_HAS_PRECISE_SMC)

    if (cpu != NULL) {

        env = cpu->env_ptr;

    }

#endif

    /* we remove all the TBs in the range [start, end[ */

    /* XXX: see if in some cases it could be faster to invalidate all

       the code */

    tb = p->first_tb;

    while (tb != NULL) {

        n = (uintptr_t)tb & 3;

        tb = (TranslationBlock *)((uintptr_t)tb & ~3);

        tb_next = tb->page_next[n];

        /* NOTE: this is subtle as a TB may span two physical pages */

        if (n == 0) {

            /* NOTE: tb_end may be after the end of the page, but

               it is not a problem */

            tb_start = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);

            tb_end = tb_start + tb->size;

        } else {

            tb_start = tb->page_addr[1];

            tb_end = tb_start + ((tb->pc + tb->size) & ~TARGET_PAGE_MASK);

        }

        if (!(tb_end <= start || tb_start >= end)) {

#ifdef TARGET_HAS_PRECISE_SMC

            if (current_tb_not_found) {

                current_tb_not_found = 0;

                current_tb = NULL;

                if (cpu->mem_io_pc) {

                    /* now we have a real cpu fault */

                    current_tb = tb_find_pc(cpu->mem_io_pc);

                }

            }

            if (current_tb == tb &&

                (current_tb->cflags & CF_COUNT_MASK) != 1) {

                /* If we are modifying the current TB, we must stop

                its execution. We could be more precise by checking

                that the modification is after the current PC, but it

                would require a specialized function to partially

                restore the CPU state */

                current_tb_modified = 1;

                cpu_restore_state_from_tb(cpu, current_tb, cpu->mem_io_pc);

                cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,

                                     &current_flags);

            }

#endif /* TARGET_HAS_PRECISE_SMC */

            tb_phys_invalidate(tb, -1);

        }

        tb = tb_next;

    }

#if !defined(CONFIG_USER_ONLY)

    /* if no code remaining, no need to continue to use slow writes */

    if (!p->first_tb) {

        invalidate_page_bitmap(p);

        tlb_unprotect_code(start);

    }

#endif

#ifdef TARGET_HAS_PRECISE_SMC

    if (current_tb_modified) {

        /* we generate a block containing just the instruction

           modifying the memory. It will ensure that it cannot modify

           itself */

        tb_gen_code(cpu, current_pc, current_cs_base, current_flags,

                    1 | curr_cflags());

        cpu_loop_exit_noexc(cpu);

    }

#endif

}


static void test_io_channel_setup_sync(SocketAddress *listen_addr,

                                       SocketAddress *connect_addr,

                                       QIOChannel **src,

                                       QIOChannel **dst)

{

    QIOChannelSocket *lioc;

    lioc = qio_channel_socket_new();

    qio_channel_socket_listen_sync(lioc, listen_addr, &error_abort);

    if (listen_addr->type == SOCKET_ADDRESS_KIND_INET) {

        SocketAddress *laddr = qio_channel_socket_get_local_address(

            lioc, &error_abort);

        g_free(connect_addr->u.inet.data->port);

        connect_addr->u.inet.data->port = g_strdup(laddr->u.inet.data->port);

        qapi_free_SocketAddress(laddr);

    }

    *src = QIO_CHANNEL(qio_channel_socket_new());

    qio_channel_socket_connect_sync(

        QIO_CHANNEL_SOCKET(*src), connect_addr, &error_abort);

    qio_channel_set_delay(*src, false);

    qio_channel_wait(QIO_CHANNEL(lioc), G_IO_IN);

    *dst = QIO_CHANNEL(qio_channel_socket_accept(lioc, &error_abort));

    g_assert(*dst);

    test_io_channel_set_socket_bufs(*src, *dst);

    object_unref(OBJECT(lioc));

}


static int qcow2_create2(const char *filename, int64_t total_size,

                         const char *backing_file, const char *backing_format,

                         int flags, size_t cluster_size, PreallocMode prealloc,

                         QemuOpts *opts, int version, int refcount_order,

                         Error **errp)

{

    /* Calculate cluster_bits */

    int cluster_bits;

    cluster_bits = ffs(cluster_size) - 1;

    if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||

        (1 << cluster_bits) != cluster_size)

    {

        error_setg(errp, "Cluster size must be a power of two between %d and "

                   "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));

        return -EINVAL;

    }

    /*

     * Open the image file and write a minimal qcow2 header.

     *

     * We keep things simple and start with a zero-sized image. We also

     * do without refcount blocks or a L1 table for now. We'll fix the

     * inconsistency later.

     *

     * We do need a refcount table because growing the refcount table means

     * allocating two new refcount blocks - the seconds of which would be at

     * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file

     * size for any qcow2 image.

     */

    BlockDriverState* bs;

    QCowHeader *header;

    uint64_t* refcount_table;

    Error *local_err = NULL;

    int ret;

    if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {

        /* Note: The following calculation does not need to be exact; if it is a

         * bit off, either some bytes will be "leaked" (which is fine) or we

         * will need to increase the file size by some bytes (which is fine,

         * too, as long as the bulk is allocated here). Therefore, using

         * floating point arithmetic is fine. */

        int64_t meta_size = 0;

        uint64_t nreftablee, nrefblocke, nl1e, nl2e;

        int64_t aligned_total_size = align_offset(total_size, cluster_size);

        int refblock_bits, refblock_size;

        /* refcount entry size in bytes */

        double rces = (1 << refcount_order) / 8.;

        /* see qcow2_open() */

        refblock_bits = cluster_bits - (refcount_order - 3);

        refblock_size = 1 << refblock_bits;

        /* header: 1 cluster */

        meta_size += cluster_size;

        /* total size of L2 tables */

        nl2e = aligned_total_size / cluster_size;

        nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));

        meta_size += nl2e * sizeof(uint64_t);

        /* total size of L1 tables */

        nl1e = nl2e * sizeof(uint64_t) / cluster_size;

        nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));

        meta_size += nl1e * sizeof(uint64_t);

        /* total size of refcount blocks

         *

         * note: every host cluster is reference-counted, including metadata

         * (even refcount blocks are recursively included).

         * Let:

         *   a = total_size (this is the guest disk size)

         *   m = meta size not including refcount blocks and refcount tables

         *   c = cluster size

         *   y1 = number of refcount blocks entries

         *   y2 = meta size including everything

         *   rces = refcount entry size in bytes

         * then,

         *   y1 = (y2 + a)/c

         *   y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m

         * we can get y1:

         *   y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)

         */

        nrefblocke = (aligned_total_size + meta_size + cluster_size)

                   / (cluster_size - rces - rces * sizeof(uint64_t)

                                                 / cluster_size);

        meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;

        /* total size of refcount tables */

        nreftablee = nrefblocke / refblock_size;

        nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));

        meta_size += nreftablee * sizeof(uint64_t);

        qemu_opt_set_number(opts, BLOCK_OPT_SIZE,

                            aligned_total_size + meta_size, &error_abort);

        qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],

                     &error_abort);

    }

    ret = bdrv_create_file(filename, opts, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return ret;

    }

    bs = NULL;

    ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,

                    NULL, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return ret;

    }

    /* Write the header */

    QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));

    header = g_malloc0(cluster_size);

    *header = (QCowHeader) {

        .magic                      = cpu_to_be32(QCOW_MAGIC),

        .version                    = cpu_to_be32(version),

        .cluster_bits               = cpu_to_be32(cluster_bits),

        .size                       = cpu_to_be64(0),

        .l1_table_offset            = cpu_to_be64(0),

        .l1_size                    = cpu_to_be32(0),

        .refcount_table_offset      = cpu_to_be64(cluster_size),

        .refcount_table_clusters    = cpu_to_be32(1),

        .refcount_order             = cpu_to_be32(refcount_order),

        .header_length              = cpu_to_be32(sizeof(*header)),

    };

    if (flags & BLOCK_FLAG_ENCRYPT) {

        header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);

    } else {

        header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);

    }

    if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {

        header->compatible_features |=

            cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);

    }

    ret = bdrv_pwrite(bs, 0, header, cluster_size);

    g_free(header);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write qcow2 header");

        goto out;

    }

    /* Write a refcount table with one refcount block */

    refcount_table = g_malloc0(2 * cluster_size);

    refcount_table[0] = cpu_to_be64(2 * cluster_size);

    ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);

    g_free(refcount_table);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write refcount table");

        goto out;

    }

    bdrv_unref(bs);

    bs = NULL;

    /*

     * And now open the image and make it consistent first (i.e. increase the

     * refcount of the cluster that is occupied by the header and the refcount

     * table)

     */

    ret = bdrv_open(&bs, filename, NULL, NULL,

                    BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,

                    &bdrv_qcow2, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto out;

    }

    ret = qcow2_alloc_clusters(bs, 3 * cluster_size);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "

                         "header and refcount table");

        goto out;

    } else if (ret != 0) {

        error_report("Huh, first cluster in empty image is already in use?");

        abort();

    }

    /* Okay, now that we have a valid image, let's give it the right size */

    ret = bdrv_truncate(bs, total_size);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not resize image");

        goto out;

    }

    /* Want a backing file? There you go.*/

    if (backing_file) {

        ret = bdrv_change_backing_file(bs, backing_file, backing_format);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not assign backing file '%s' "

                             "with format '%s'", backing_file, backing_format);

            goto out;

        }

    }

    /* And if we're supposed to preallocate metadata, do that now */

    if (prealloc != PREALLOC_MODE_OFF) {

        BDRVQcowState *s = bs->opaque;

        qemu_co_mutex_lock(&s->lock);

        ret = preallocate(bs);

        qemu_co_mutex_unlock(&s->lock);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not preallocate metadata");

            goto out;

        }

    }

    bdrv_unref(bs);

    bs = NULL;

    /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */

    ret = bdrv_open(&bs, filename, NULL, NULL,

                    BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,

                    &bdrv_qcow2, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    ret = 0;

out:

    if (bs) {

        bdrv_unref(bs);

    }

    return ret;

}


static void ahci_start_transfer(IDEDMA *dma)

{

    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);

    IDEState *s = &ad->port.ifs[0];

    uint32_t size = (uint32_t)(s->data_end - s->data_ptr);

    /* write == ram -> device */

    uint32_t opts = le32_to_cpu(ad->cur_cmd->opts);

    int is_write = opts & AHCI_CMD_WRITE;

    int is_atapi = opts & AHCI_CMD_ATAPI;

    int has_sglist = 0;

    if (is_atapi && !ad->done_atapi_packet) {

        /* already prepopulated iobuffer */

        ad->done_atapi_packet = true;

        size = 0;

        goto out;

    }

    if (!ahci_populate_sglist(ad, &s->sg, s->io_buffer_offset)) {

        has_sglist = 1;

    }

    DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",

            is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",

            has_sglist ? "" : "o");

    if (has_sglist && size) {

        if (is_write) {

            dma_buf_write(s->data_ptr, size, &s->sg);

        } else {

            dma_buf_read(s->data_ptr, size, &s->sg);

        }

    }

out:

    /* declare that we processed everything */

    s->data_ptr = s->data_end;

    /* Update number of transferred bytes, destroy sglist */

    ahci_commit_buf(dma, size);

    s->end_transfer_func(s);

    if (!(s->status & DRQ_STAT)) {

        /* done with PIO send/receive */

        ahci_write_fis_pio(ad, le32_to_cpu(ad->cur_cmd->status));

    }

}


static int pl110_init(SysBusDevice *dev)

{

    pl110_state *s = FROM_SYSBUS(pl110_state, dev);

    memory_region_init_io(&s->iomem, &pl110_ops, s, "pl110", 0x1000);

    sysbus_init_mmio(dev, &s->iomem);

    sysbus_init_irq(dev, &s->irq);

    qdev_init_gpio_in(&s->busdev.qdev, pl110_mux_ctrl_set, 1);

    s->con = graphic_console_init(pl110_update_display,

                                  pl110_invalidate_display,

                                  NULL, NULL, s);

    return 0;

}


static int ljpeg_encode_bgr(AVCodecContext *avctx, PutBitContext *pb,

                            const AVFrame *frame)

{

    LJpegEncContext *s    = avctx->priv_data;

    const int width       = frame->width;

    const int height      = frame->height;

    const int linesize    = frame->linesize[0];

    uint16_t (*buffer)[4] = s->scratch;

    const int predictor   = avctx->prediction_method+1;

    int left[3], top[3], topleft[3];

    int x, y, i;

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

        buffer[0][i] = 1 << (9 - 1);

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

        const int modified_predictor = y ? predictor : 1;

        uint8_t *ptr = frame->data[0] + (linesize * y);

        if (pb->buf_end - pb->buf - (put_bits_count(pb) >> 3) < width * 3 * 3) {

            av_log(avctx, AV_LOG_ERROR, "encoded frame too large\n");

            return -1;

        }

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

            top[i]= left[i]= topleft[i]= buffer[0][i];

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

            buffer[x][1] =  ptr[3 * x + 0] -     ptr[3 * x + 1] + 0x100;

            buffer[x][2] =  ptr[3 * x + 2] -     ptr[3 * x + 1] + 0x100;

            buffer[x][0] = (ptr[3 * x + 0] + 2 * ptr[3 * x + 1] + ptr[3 * x + 2]) >> 2;

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

                int pred, diff;

                PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);

                topleft[i] = top[i];

                top[i]     = buffer[x+1][i];

                left[i]    = buffer[x][i];

                diff       = ((left[i] - pred + 0x100) & 0x1FF) - 0x100;

                if (i == 0)

                    ff_mjpeg_encode_dc(pb, diff, s->huff_size_dc_luminance, s->huff_code_dc_luminance); //FIXME ugly

                else

                    ff_mjpeg_encode_dc(pb, diff, s->huff_size_dc_chrominance, s->huff_code_dc_chrominance);

            }

        }

    }

    return 0;

}


static int ipmovie_probe(AVProbeData *p)

{

    if (p->buf_size < IPMOVIE_SIGNATURE_SIZE)

        return 0;

    if (strncmp(p->buf, IPMOVIE_SIGNATURE, IPMOVIE_SIGNATURE_SIZE) != 0)

        return 0;

    return AVPROBE_SCORE_MAX;

}


static void vc1_decode_p_blocks(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    int apply_loop_filter;

    /* select codingmode used for VLC tables selection */

    switch (v->c_ac_table_index) {

    case 0:

        v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;

        break;

    case 1:

        v->codingset = CS_HIGH_MOT_INTRA;

        break;

    case 2:

        v->codingset = CS_MID_RATE_INTRA;

        break;

    }

    switch (v->c_ac_table_index) {

    case 0:

        v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;

        break;

    case 1:

        v->codingset2 = CS_HIGH_MOT_INTER;

        break;

    case 2:

        v->codingset2 = CS_MID_RATE_INTER;

        break;

    }

    apply_loop_filter   = s->loop_filter && !(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY);

    s->first_slice_line = 1;

    memset(v->cbp_base, 0, sizeof(v->cbp_base[0])*2*s->mb_stride);

    for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {

        s->mb_x = 0;

        ff_init_block_index(s);

        for (; s->mb_x < s->mb_width; s->mb_x++) {

            ff_update_block_index(s);

            if (v->fcm == ILACE_FIELD)

                vc1_decode_p_mb_intfi(v);

            else if (v->fcm == ILACE_FRAME)

                vc1_decode_p_mb_intfr(v);

            else vc1_decode_p_mb(v);

            if (s->mb_y != s->start_mb_y && apply_loop_filter && v->fcm == PROGRESSIVE)

                vc1_apply_p_loop_filter(v);

            if (get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) {

                // TODO: may need modification to handle slice coding

                ff_er_add_slice(s, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR);

                av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n",

                       get_bits_count(&s->gb), v->bits, s->mb_x, s->mb_y);

                return;

            }

        }

        memmove(v->cbp_base,      v->cbp,      sizeof(v->cbp_base[0])      * s->mb_stride);

        memmove(v->ttblk_base,    v->ttblk,    sizeof(v->ttblk_base[0])    * s->mb_stride);

        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0]) * s->mb_stride);

        memmove(v->luma_mv_base,  v->luma_mv,  sizeof(v->luma_mv_base[0])  * s->mb_stride);

        if (s->mb_y != s->start_mb_y) ff_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);

        s->first_slice_line = 0;

    }

    if (apply_loop_filter && v->fcm == PROGRESSIVE) {

        s->mb_x = 0;

        ff_init_block_index(s);

        for (; s->mb_x < s->mb_width; s->mb_x++) {

            ff_update_block_index(s);

            vc1_apply_p_loop_filter(v);

        }

    }

    if (s->end_mb_y >= s->start_mb_y)

        ff_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);

    ff_er_add_slice(s, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,

                    (s->end_mb_y << v->field_mode) - 1, ER_MB_END);

}


static int vc9_decode_init(AVCodecContext *avctx)

{

    VC9Context *v = avctx->priv_data;

    GetBitContext gb;

    if (!avctx->extradata_size || !avctx->extradata) return -1;

    avctx->pix_fmt = PIX_FMT_YUV420P;

    v->avctx = avctx;

    if (init_common(v) < 0) return -1;

    if (avctx->codec_id == CODEC_ID_WMV3)

    {

        int count = 0;

	// looks like WMV3 has a sequence header stored in the extradata

	// advanced sequence header may be before the first frame

	// the last byte of the extradata is a version number, 1 for the

	// samples we can decode

	init_get_bits(&gb, avctx->extradata, avctx->extradata_size);

	decode_sequence_header(avctx, &gb);

	count = avctx->extradata_size*8 - get_bits_count(&gb);

	if (count>0)

	{

    	    av_log(avctx, AV_LOG_INFO, "Extra data: %i bits left, value: %X\n",

               count, get_bits(&gb, count));

	}

	else

	{

    	    av_log(avctx, AV_LOG_INFO, "Read %i bits in overflow\n", -count);

	}

    }

    /* Done with header parsing */

    //FIXME I feel like this is wrong

    v->width_mb = (avctx->coded_width+15)>>4;

    v->height_mb = (avctx->coded_height+15)>>4;

    /* Allocate mb bitplanes */

    v->mv_type_mb_plane = (uint8_t *)av_malloc(v->width_mb*v->height_mb);

    if (!v->mv_type_mb_plane) return -1;

    v->skip_mb_plane = (uint8_t *)av_malloc(v->width_mb*v->height_mb);

    if (!v->skip_mb_plane) return -1;

    v->direct_mb_plane = (uint8_t *)av_malloc(v->width_mb*v->height_mb);

    if (!v->direct_mb_plane) return -1;

#if HAS_ADVANCED_PROFILE

    if (v->profile > PROFILE_MAIN)

    {

        v->over_flags_plane = (uint8_t *)av_malloc(v->width_mb*v->height_mb);

        if (!v->over_flags_plane) return -1;

        v->ac_pred_plane = (uint8_t *)av_malloc(v->width_mb*v->height_mb);

        if (!v->ac_pred_plane) return -1;

    }

#endif

    return 0;

}


enum AVCodecID ff_guess_image2_codec(const char *filename)

{

    return av_str2id(img_tags, filename);

}


static int sd_open(BlockDriverState *bs, const char *filename, int flags)

{

    int ret, fd;

    uint32_t vid = 0;

    BDRVSheepdogState *s = bs->opaque;

    char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];

    uint32_t snapid;

    char *buf = NULL;

    strstart(filename, "sheepdog:", (const char **)&filename);

    QLIST_INIT(&s->inflight_aio_head);

    QLIST_INIT(&s->pending_aio_head);

    s->fd = -1;

    memset(vdi, 0, sizeof(vdi));

    memset(tag, 0, sizeof(tag));

    if (parse_vdiname(s, filename, vdi, &snapid, tag) < 0) {

        ret = -EINVAL;

        goto out;

    }

    s->fd = get_sheep_fd(s);

    if (s->fd < 0) {

        ret = s->fd;

        goto out;

    }

    ret = find_vdi_name(s, vdi, snapid, tag, &vid, 0);

    if (ret) {

        goto out;

    }

    /*

     * QEMU block layer emulates writethrough cache as 'writeback + flush', so

     * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.

     */

    s->cache_flags = SD_FLAG_CMD_CACHE;

    if (flags & BDRV_O_NOCACHE) {

        s->cache_flags = SD_FLAG_CMD_DIRECT;

    }

    if (s->cache_flags == SD_FLAG_CMD_CACHE) {

        s->flush_fd = connect_to_sdog(s->addr, s->port);

        if (s->flush_fd < 0) {

            error_report("failed to connect");

            ret = s->flush_fd;

            goto out;

        }

    }

    if (snapid || tag[0] != '\0') {

        dprintf("%" PRIx32 " snapshot inode was open.\n", vid);

        s->is_snapshot = true;

    }

    fd = connect_to_sdog(s->addr, s->port);

    if (fd < 0) {

        error_report("failed to connect");

        ret = fd;

        goto out;

    }

    buf = g_malloc(SD_INODE_SIZE);

    ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,

                      s->cache_flags);

    closesocket(fd);

    if (ret) {

        goto out;

    }

    memcpy(&s->inode, buf, sizeof(s->inode));

    s->min_dirty_data_idx = UINT32_MAX;

    s->max_dirty_data_idx = 0;

    bs->total_sectors = s->inode.vdi_size / SECTOR_SIZE;

    pstrcpy(s->name, sizeof(s->name), vdi);

    qemu_co_mutex_init(&s->lock);

    g_free(buf);

    return 0;

out:

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

    if (s->fd >= 0) {

        closesocket(s->fd);

    }

    g_free(buf);

    return ret;

}


static void virt_set_gic_version(Object *obj, const char *value, Error **errp)

{

    VirtMachineState *vms = VIRT_MACHINE(obj);

    if (!strcmp(value, "3")) {

        vms->gic_version = 3;

    } else if (!strcmp(value, "2")) {

        vms->gic_version = 2;

    } else if (!strcmp(value, "host")) {

        vms->gic_version = 0; /* Will probe later */

    } else {

        error_report("Invalid gic-version option value");

        error_printf("Allowed gic-version values are: 3, 2, host\n");

        exit(1);

    }

}


static int sys_openat(int dirfd, const char *pathname, int flags, ...)

{

  /*

   * open(2) has extra parameter 'mode' when called with

   * flag O_CREAT.

   */

  if ((flags & O_CREAT) != 0) {

      va_list ap;

      mode_t mode;

      /*

       * Get the 'mode' parameter and translate it to

       * host bits.

       */

      va_start(ap, flags);

      mode = va_arg(ap, mode_t);

      mode = target_to_host_bitmask(mode, fcntl_flags_tbl);

      va_end(ap);

      return (openat(dirfd, pathname, flags, mode));

  }

  return (openat(dirfd, pathname, flags));

}


static void coroutine_fn backup_run(void *opaque)

{

    BackupBlockJob *job = opaque;

    BackupCompleteData *data;

    BlockDriverState *bs = job->common.bs;

    BlockDriverState *target = job->target;

    BlockdevOnError on_target_error = job->on_target_error;

    NotifierWithReturn before_write = {

        .notify = backup_before_write_notify,

    };

    int64_t start, end;

    int64_t sectors_per_cluster = cluster_size_sectors(job);

    int ret = 0;

    QLIST_INIT(&job->inflight_reqs);

    qemu_co_rwlock_init(&job->flush_rwlock);

    start = 0;

    end = DIV_ROUND_UP(job->common.len, job->cluster_size);

    job->bitmap = hbitmap_alloc(end, 0);

    bdrv_set_enable_write_cache(target, true);

    if (target->blk) {

        blk_set_on_error(target->blk, on_target_error, on_target_error);

        blk_iostatus_enable(target->blk);

    }

    bdrv_add_before_write_notifier(bs, &before_write);

    if (job->sync_mode == MIRROR_SYNC_MODE_NONE) {

        while (!block_job_is_cancelled(&job->common)) {

            /* Yield until the job is cancelled.  We just let our before_write

             * notify callback service CoW requests. */

            job->common.busy = false;

            qemu_coroutine_yield();

            job->common.busy = true;

        }

    } else if (job->sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {

        ret = backup_run_incremental(job);

    } else {

        /* Both FULL and TOP SYNC_MODE's require copying.. */

        for (; start < end; start++) {

            bool error_is_read;

            if (yield_and_check(job)) {

                break;

            }

            if (job->sync_mode == MIRROR_SYNC_MODE_TOP) {

                int i, n;

                int alloced = 0;

                /* Check to see if these blocks are already in the

                 * backing file. */

                for (i = 0; i < sectors_per_cluster;) {

                    /* bdrv_is_allocated() only returns true/false based

                     * on the first set of sectors it comes across that

                     * are are all in the same state.

                     * For that reason we must verify each sector in the

                     * backup cluster length.  We end up copying more than

                     * needed but at some point that is always the case. */

                    alloced =

                        bdrv_is_allocated(bs,

                                start * sectors_per_cluster + i,

                                sectors_per_cluster - i, &n);

                    i += n;

                    if (alloced == 1 || n == 0) {

                        break;

                    }

                }

                /* If the above loop never found any sectors that are in

                 * the topmost image, skip this backup. */

                if (alloced == 0) {

                    continue;

                }

            }

            /* FULL sync mode we copy the whole drive. */

            ret = backup_do_cow(bs, start * sectors_per_cluster,

                                sectors_per_cluster, &error_is_read, false);

            if (ret < 0) {

                /* Depending on error action, fail now or retry cluster */

                BlockErrorAction action =

                    backup_error_action(job, error_is_read, -ret);

                if (action == BLOCK_ERROR_ACTION_REPORT) {

                    break;

                } else {

                    start--;

                    continue;

                }

            }

        }

    }

    notifier_with_return_remove(&before_write);

    /* wait until pending backup_do_cow() calls have completed */

    qemu_co_rwlock_wrlock(&job->flush_rwlock);

    qemu_co_rwlock_unlock(&job->flush_rwlock);

    hbitmap_free(job->bitmap);

    if (target->blk) {

        blk_iostatus_disable(target->blk);

    }

    bdrv_op_unblock_all(target, job->common.blocker);

    data = g_malloc(sizeof(*data));

    data->ret = ret;

    block_job_defer_to_main_loop(&job->common, backup_complete, data);

}


static RawAIOCB *raw_aio_setup(BlockDriverState *bs, int64_t sector_num,

        QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    BDRVRawState *s = bs->opaque;

    RawAIOCB *acb;

    if (fd_open(bs) < 0)

        return NULL;

    acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);

    if (!acb)

        return NULL;

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

    acb->aiocb.ev_signo = SIGUSR2;

    acb->aiocb.aio_iov = qiov->iov;

    acb->aiocb.aio_niov = qiov->niov;

    acb->aiocb.aio_nbytes = nb_sectors * 512;

    acb->aiocb.aio_offset = sector_num * 512;

    acb->aiocb.aio_flags = 0;

    /*

     * If O_DIRECT is used the buffer needs to be aligned on a sector

     * boundary. Tell the low level code to ensure that in case it's

     * not done yet.

     */

    if (s->aligned_buf)

        acb->aiocb.aio_flags |= QEMU_AIO_SECTOR_ALIGNED;

    acb->next = posix_aio_state->first_aio;

    posix_aio_state->first_aio = acb;

    return acb;

}


static int net_socket_listen_init(NetClientState *peer,

                                  const char *model,

                                  const char *name,

                                  const char *host_str)

{

    NetClientState *nc;

    NetSocketState *s;

    SocketAddressLegacy *saddr;

    int ret;

    Error *local_error = NULL;

    saddr = socket_parse(host_str, &local_error);

    if (saddr == NULL) {

        error_report_err(local_error);

        return -1;

    }

    ret = socket_listen(saddr, &local_error);

    if (ret < 0) {

        qapi_free_SocketAddressLegacy(saddr);

        error_report_err(local_error);

        return -1;

    }

    nc = qemu_new_net_client(&net_socket_info, peer, model, name);

    s = DO_UPCAST(NetSocketState, nc, nc);

    s->fd = -1;

    s->listen_fd = ret;

    s->nc.link_down = true;

    net_socket_rs_init(&s->rs, net_socket_rs_finalize);

    qemu_set_fd_handler(s->listen_fd, net_socket_accept, NULL, s);

    qapi_free_SocketAddressLegacy(saddr);

    return 0;

}


InputEvent *qemu_input_event_new_key(KeyValue *key, bool down)

{

    InputEvent *evt = g_new0(InputEvent, 1);

    evt->key = g_new0(InputKeyEvent, 1);

    evt->kind = INPUT_EVENT_KIND_KEY;

    evt->key->key = key;

    evt->key->down = down;

    return evt;

}


static void mirror_exit(BlockJob *job, void *opaque)

{

    MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);

    MirrorExitData *data = opaque;

    AioContext *replace_aio_context = NULL;

    BlockDriverState *src = s->common.bs;

    /* Make sure that the source BDS doesn't go away before we called

     * block_job_completed(). */

    bdrv_ref(src);

    if (s->to_replace) {

        replace_aio_context = bdrv_get_aio_context(s->to_replace);

        aio_context_acquire(replace_aio_context);

    }

    if (s->should_complete && data->ret == 0) {

        BlockDriverState *to_replace = s->common.bs;

        if (s->to_replace) {

            to_replace = s->to_replace;

        }

        /* This was checked in mirror_start_job(), but meanwhile one of the

         * nodes could have been newly attached to a BlockBackend. */

        if (to_replace->blk && s->target->blk) {

            error_report("block job: Can't create node with two BlockBackends");

            data->ret = -EINVAL;

            goto out;

        }

        if (bdrv_get_flags(s->target) != bdrv_get_flags(to_replace)) {

            bdrv_reopen(s->target, bdrv_get_flags(to_replace), NULL);

        }

        bdrv_replace_in_backing_chain(to_replace, s->target);

    }

out:

    if (s->to_replace) {

        bdrv_op_unblock_all(s->to_replace, s->replace_blocker);

        error_free(s->replace_blocker);

        bdrv_unref(s->to_replace);

    }

    if (replace_aio_context) {

        aio_context_release(replace_aio_context);

    }

    g_free(s->replaces);

    bdrv_op_unblock_all(s->target, s->common.blocker);

    bdrv_unref(s->target);

    block_job_completed(&s->common, data->ret);

    g_free(data);

    bdrv_drained_end(src);

    if (qemu_get_aio_context() == bdrv_get_aio_context(src)) {

        aio_enable_external(iohandler_get_aio_context());

    }

    bdrv_unref(src);

}


static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)

{

    AVFormatContext *s = of->ctx;

    AVStream *st = ost->st;

    int ret;

    if (!of->header_written) {

        AVPacket tmp_pkt = {0};

        /* the muxer is not initialized yet, buffer the packet */

        if (!av_fifo_space(ost->muxing_queue)) {

            int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),

                                 ost->max_muxing_queue_size);

            if (new_size <= av_fifo_size(ost->muxing_queue)) {

                av_log(NULL, AV_LOG_ERROR,

                       "Too many packets buffered for output stream %d:%d.\n",

                       ost->file_index, ost->st->index);

                exit_program(1);

            }

            ret = av_fifo_realloc2(ost->muxing_queue, new_size);

            if (ret < 0)

                exit_program(1);

        }

        ret = av_packet_ref(&tmp_pkt, pkt);

        if (ret < 0)

            exit_program(1);

        av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);

        av_packet_unref(pkt);

        return;

    }

    if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||

        (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))

        pkt->pts = pkt->dts = AV_NOPTS_VALUE;

    /*

     * Audio encoders may split the packets --  #frames in != #packets out.

     * But there is no reordering, so we can limit the number of output packets

     * by simply dropping them here.

     * Counting encoded video frames needs to be done separately because of

     * reordering, see do_video_out()

     */

    if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {

        if (ost->frame_number >= ost->max_frames) {

            av_packet_unref(pkt);

            return;

        }

        ost->frame_number++;

    }

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

        int i;

        uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,

                                              NULL);

        ost->quality = sd ? AV_RL32(sd) : -1;

        ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;

        for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {

            if (sd && i < sd[5])

                ost->error[i] = AV_RL64(sd + 8 + 8*i);

            else

                ost->error[i] = -1;

        }

        if (ost->frame_rate.num && ost->is_cfr) {

            if (pkt->duration > 0)

                av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");

            pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),

                                         ost->mux_timebase);

        }

    }

    av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);

    if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {

        if (pkt->dts != AV_NOPTS_VALUE &&

            pkt->pts != AV_NOPTS_VALUE &&

            pkt->dts > pkt->pts) {

            av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",

                   pkt->dts, pkt->pts,

                   ost->file_index, ost->st->index);

            pkt->pts =

            pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1

                     - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)

                     - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);

        }

        if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&

            pkt->dts != AV_NOPTS_VALUE &&

            !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&

            ost->last_mux_dts != AV_NOPTS_VALUE) {

            int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);

            if (pkt->dts < max) {

                int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;

                av_log(s, loglevel, "Non-monotonous DTS in output stream "

                       "%d:%d; previous: %"PRId64", current: %"PRId64"; ",

                       ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);

                if (exit_on_error) {

                    av_log(NULL, AV_LOG_FATAL, "aborting.\n");

                    exit_program(1);

                }

                av_log(s, loglevel, "changing to %"PRId64". This may result "

                       "in incorrect timestamps in the output file.\n",

                       max);

                if (pkt->pts >= pkt->dts)

                    pkt->pts = FFMAX(pkt->pts, max);

                pkt->dts = max;

            }

        }

    }

    ost->last_mux_dts = pkt->dts;

    ost->data_size += pkt->size;

    ost->packets_written++;

    pkt->stream_index = ost->index;

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "

                "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",

                av_get_media_type_string(ost->enc_ctx->codec_type),

                av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),

                av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),

                pkt->size

              );

    }

    ret = av_interleaved_write_frame(s, pkt);

    if (ret < 0) {

        print_error("av_interleaved_write_frame()", ret);

        main_return_code = 1;

        close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);

    }

    av_packet_unref(pkt);

}


static int estimate_qp(MpegEncContext *s, int dry_run){

    if (s->next_lambda){

        s->current_picture_ptr->quality=

        s->current_picture.quality = s->next_lambda;

        if(!dry_run) s->next_lambda= 0;

    } else if (!s->fixed_qscale) {

        s->current_picture_ptr->quality=

        s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);

        if (s->current_picture.quality < 0)

            return -1;

    }

    if(s->adaptive_quant){

        switch(s->codec_id){

        case CODEC_ID_MPEG4:

            if (CONFIG_MPEG4_ENCODER)

                ff_clean_mpeg4_qscales(s);

            break;

        case CODEC_ID_H263:

        case CODEC_ID_H263P:

        case CODEC_ID_FLV1:

            if (CONFIG_H263_ENCODER||CONFIG_H263P_ENCODER||CONFIG_FLV_ENCODER)

                ff_clean_h263_qscales(s);

            break;

        }

        s->lambda= s->lambda_table[0];

        //FIXME broken

    }else

        s->lambda= s->current_picture.quality;

//printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);

    update_qscale(s);

    return 0;

}


int coroutine_fn bdrv_co_pwrite_zeroes(BlockDriverState *bs,

                                       int64_t offset, int count,

                                       BdrvRequestFlags flags)

{

    trace_bdrv_co_pwrite_zeroes(bs, offset, count, flags);

    if (!(bs->open_flags & BDRV_O_UNMAP)) {

        flags &= ~BDRV_REQ_MAY_UNMAP;

    }

    return bdrv_co_pwritev(bs, offset, count, NULL,

                           BDRV_REQ_ZERO_WRITE | flags);

}


static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data,

                                                     const void *unused)

{

    UserDefFlatUnion2 *tmp = NULL;

    Error *err = NULL;

    Visitor *v;

    /* test situation where discriminator field ('enum1' here) is missing */

    v = validate_test_init(data, "{ 'integer': 42, 'string': 'c', 'string1': 'd', 'string2': 'e' }");

    visit_type_UserDefFlatUnion2(v, NULL, &tmp, &err);

    error_free_or_abort(&err);

    g_assert(!tmp);

}


static void s390_init(QEMUMachineInitArgs *args)

{

    ram_addr_t my_ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    CPUS390XState *env = NULL;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    ram_addr_t kernel_size = 0;

    ram_addr_t initrd_offset;

    ram_addr_t initrd_size = 0;

    int shift = 0;

    uint8_t *storage_keys;

    void *virtio_region;

    hwaddr virtio_region_len;

    hwaddr virtio_region_start;

    int i;

    /* s390x ram size detection needs a 16bit multiplier + an increment. So

       guests > 64GB can be specified in 2MB steps etc. */

    while ((my_ram_size >> (20 + shift)) > 65535) {

        shift++;

    }

    my_ram_size = my_ram_size >> (20 + shift) << (20 + shift);

    /* lets propagate the changed ram size into the global variable. */

    ram_size = my_ram_size;

    /* get a BUS */

    s390_bus = s390_virtio_bus_init(&my_ram_size);

    s390_sclp_init();

    /* allocate RAM */

    memory_region_init_ram(ram, "s390.ram", my_ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(sysmem, 0, ram);

    /* clear virtio region */

    virtio_region_len = my_ram_size - ram_size;

    virtio_region_start = ram_size;

    virtio_region = cpu_physical_memory_map(virtio_region_start,

                                            &virtio_region_len, true);

    memset(virtio_region, 0, virtio_region_len);

    cpu_physical_memory_unmap(virtio_region, virtio_region_len, 1,

                              virtio_region_len);

    /* allocate storage keys */

    storage_keys = g_malloc0(my_ram_size / TARGET_PAGE_SIZE);

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "host";

    }

    ipi_states = g_malloc(sizeof(S390CPU *) * smp_cpus);

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

        S390CPU *cpu;

        CPUS390XState *tmp_env;

        cpu = cpu_s390x_init(cpu_model);

        tmp_env = &cpu->env;

        if (!env) {

            env = tmp_env;

        }

        ipi_states[i] = cpu;

        tmp_env->halted = 1;

        tmp_env->exception_index = EXCP_HLT;

        tmp_env->storage_keys = storage_keys;

    }

    /* One CPU has to run */

    s390_add_running_cpu(env);

    if (kernel_filename) {

        kernel_size = load_elf(kernel_filename, NULL, NULL, NULL, NULL,

                               NULL, 1, ELF_MACHINE, 0);

        if (kernel_size == -1UL) {

            kernel_size = load_image_targphys(kernel_filename, 0, ram_size);

        }

        if (kernel_size == -1UL) {

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

                    kernel_filename);

            exit(1);

        }

        /*

         * we can not rely on the ELF entry point, since up to 3.2 this

         * value was 0x800 (the SALIPL loader) and it wont work. For

         * all (Linux) cases 0x10000 (KERN_IMAGE_START) should be fine.

         */

        env->psw.addr = KERN_IMAGE_START;

        env->psw.mask = 0x0000000180000000ULL;

    } else {

        ram_addr_t bios_size = 0;

        char *bios_filename;

        /* Load zipl bootloader */

        if (bios_name == NULL) {

            bios_name = ZIPL_FILENAME;

        }

        bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        bios_size = load_image_targphys(bios_filename, ZIPL_LOAD_ADDR, 4096);

        g_free(bios_filename);

        if ((long)bios_size < 0) {

            hw_error("could not load bootloader '%s'\n", bios_name);

        }

        if (bios_size > 4096) {

            hw_error("stage1 bootloader is > 4k\n");

        }

        env->psw.addr = ZIPL_START;

        env->psw.mask = 0x0000000180000000ULL;

    }

    if (initrd_filename) {

        initrd_offset = INITRD_START;

        while (kernel_size + 0x100000 > initrd_offset) {

            initrd_offset += 0x100000;

        }

        initrd_size = load_image_targphys(initrd_filename, initrd_offset,

                                          ram_size - initrd_offset);

        if (initrd_size == -1UL) {

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

                    initrd_filename);

            exit(1);

        }

        /* we have to overwrite values in the kernel image, which are "rom" */

        stq_p(rom_ptr(INITRD_PARM_START), initrd_offset);

        stq_p(rom_ptr(INITRD_PARM_SIZE), initrd_size);

    }

    if (rom_ptr(KERN_PARM_AREA)) {

        /* we have to overwrite values in the kernel image, which are "rom" */

        memcpy(rom_ptr(KERN_PARM_AREA), kernel_cmdline,

               strlen(kernel_cmdline) + 1);

    }

    /* Create VirtIO network adapters */

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

        NICInfo *nd = &nd_table[i];

        DeviceState *dev;

        if (!nd->model) {

            nd->model = g_strdup("virtio");

        }

        if (strcmp(nd->model, "virtio")) {

            fprintf(stderr, "S390 only supports VirtIO nics\n");

            exit(1);

        }

        dev = qdev_create((BusState *)s390_bus, "virtio-net-s390");

        qdev_set_nic_properties(dev, nd);

        qdev_init_nofail(dev);

    }

    /* Create VirtIO disk drives */

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

        DriveInfo *dinfo;

        DeviceState *dev;

        dinfo = drive_get(IF_IDE, 0, i);

        if (!dinfo) {

            continue;

        }

        dev = qdev_create((BusState *)s390_bus, "virtio-blk-s390");

        qdev_prop_set_drive_nofail(dev, "drive", dinfo->bdrv);

        qdev_init_nofail(dev);

    }

}


void sparc64_set_context(CPUSPARCState *env)

{

    abi_ulong ucp_addr;

    struct target_ucontext *ucp;

    target_mc_gregset_t *grp;

    abi_ulong pc, npc, tstate;

    abi_ulong fp, i7, w_addr;

    int err;

    unsigned int i;

    ucp_addr = env->regwptr[UREG_I0];

    if (!lock_user_struct(VERIFY_READ, ucp, ucp_addr, 1))

        goto do_sigsegv;

    grp  = &ucp->tuc_mcontext.mc_gregs;

    err  = __get_user(pc, &((*grp)[MC_PC]));

    err |= __get_user(npc, &((*grp)[MC_NPC]));

    if (err || ((pc | npc) & 3))

        goto do_sigsegv;

    if (env->regwptr[UREG_I1]) {

        target_sigset_t target_set;

        sigset_t set;

        if (TARGET_NSIG_WORDS == 1) {

            if (__get_user(target_set.sig[0], &ucp->tuc_sigmask.sig[0]))

                goto do_sigsegv;

        } else {

            abi_ulong *src, *dst;

            src = ucp->tuc_sigmask.sig;

            dst = target_set.sig;

            for (i = 0; i < TARGET_NSIG_WORDS; i++, dst++, src++) {

                err |= __get_user(*dst, src);

            }

            if (err)

                goto do_sigsegv;

        }

        target_to_host_sigset_internal(&set, &target_set);

        sigprocmask(SIG_SETMASK, &set, NULL);

    }

    env->pc = pc;

    env->npc = npc;

    err |= __get_user(env->y, &((*grp)[MC_Y]));

    err |= __get_user(tstate, &((*grp)[MC_TSTATE]));

    env->asi = (tstate >> 24) & 0xff;

    cpu_put_ccr(env, tstate >> 32);

    cpu_put_cwp64(env, tstate & 0x1f);

    err |= __get_user(env->gregs[1], (&(*grp)[MC_G1]));

    err |= __get_user(env->gregs[2], (&(*grp)[MC_G2]));

    err |= __get_user(env->gregs[3], (&(*grp)[MC_G3]));

    err |= __get_user(env->gregs[4], (&(*grp)[MC_G4]));

    err |= __get_user(env->gregs[5], (&(*grp)[MC_G5]));

    err |= __get_user(env->gregs[6], (&(*grp)[MC_G6]));

    err |= __get_user(env->gregs[7], (&(*grp)[MC_G7]));

    err |= __get_user(env->regwptr[UREG_I0], (&(*grp)[MC_O0]));

    err |= __get_user(env->regwptr[UREG_I1], (&(*grp)[MC_O1]));

    err |= __get_user(env->regwptr[UREG_I2], (&(*grp)[MC_O2]));

    err |= __get_user(env->regwptr[UREG_I3], (&(*grp)[MC_O3]));

    err |= __get_user(env->regwptr[UREG_I4], (&(*grp)[MC_O4]));

    err |= __get_user(env->regwptr[UREG_I5], (&(*grp)[MC_O5]));

    err |= __get_user(env->regwptr[UREG_I6], (&(*grp)[MC_O6]));

    err |= __get_user(env->regwptr[UREG_I7], (&(*grp)[MC_O7]));

    err |= __get_user(fp, &(ucp->tuc_mcontext.mc_fp));

    err |= __get_user(i7, &(ucp->tuc_mcontext.mc_i7));

    w_addr = TARGET_STACK_BIAS+env->regwptr[UREG_I6];

    if (put_user(fp, w_addr + offsetof(struct target_reg_window, ins[6]),

                 abi_ulong) != 0)

        goto do_sigsegv;

    if (put_user(i7, w_addr + offsetof(struct target_reg_window, ins[7]),

                 abi_ulong) != 0)

        goto do_sigsegv;

    /* FIXME this does not match how the kernel handles the FPU in

     * its sparc64_set_context implementation. In particular the FPU

     * is only restored if fenab is non-zero in:

     *   __get_user(fenab, &(ucp->tuc_mcontext.mc_fpregs.mcfpu_enab));

     */

    err |= __get_user(env->fprs, &(ucp->tuc_mcontext.mc_fpregs.mcfpu_fprs));

    {

        uint32_t *src = ucp->tuc_mcontext.mc_fpregs.mcfpu_fregs.sregs;

        for (i = 0; i < 64; i++, src++) {

            if (i & 1) {

                err |= __get_user(env->fpr[i/2].l.lower, src);

            } else {

                err |= __get_user(env->fpr[i/2].l.upper, src);

            }

        }

    }

    err |= __get_user(env->fsr,

                      &(ucp->tuc_mcontext.mc_fpregs.mcfpu_fsr));

    err |= __get_user(env->gsr,

                      &(ucp->tuc_mcontext.mc_fpregs.mcfpu_gsr));

    if (err)

        goto do_sigsegv;

    unlock_user_struct(ucp, ucp_addr, 0);

    return;

 do_sigsegv:

    unlock_user_struct(ucp, ucp_addr, 0);

    force_sig(TARGET_SIGSEGV);

}


uint32_t cpu_mips_get_count (CPUState *env)

{

    if (env->CP0_Cause & (1 << CP0Ca_DC)) {

        return env->CP0_Count;

    } else {

        return env->CP0_Count +

            (uint32_t)muldiv64(qemu_get_clock(vm_clock),

                               TIMER_FREQ, get_ticks_per_sec());

    }

}


static int cpu_has_work(CPUState *env)

{

    if (env->stop)

        return 1;

    if (env->stopped)

        return 0;

    if (!env->halted)

        return 1;

    if (qemu_cpu_has_work(env))

        return 1;

    return 0;

}


static void outport_write(KBDState *s, uint32_t val)

{

    DPRINTF("kbd: write outport=0x%02x\n", val);

    s->outport = val;

    if (s->a20_out) {

        qemu_set_irq(*s->a20_out, (val >> 1) & 1);

    }

    if (!(val & 1)) {

        qemu_system_reset_request();

    }

}


static void nvdimm_dsm_get_label_data(NVDIMMDevice *nvdimm, NvdimmDsmIn *in,

                                      hwaddr dsm_mem_addr)

{

    NVDIMMClass *nvc = NVDIMM_GET_CLASS(nvdimm);

    NvdimmFuncGetLabelDataIn *get_label_data;

    NvdimmFuncGetLabelDataOut *get_label_data_out;

    uint32_t status;

    int size;

    get_label_data = (NvdimmFuncGetLabelDataIn *)in->arg3;

    le32_to_cpus(&get_label_data->offset);

    le32_to_cpus(&get_label_data->length);

    nvdimm_debug("Read Label Data: offset %#x length %#x.\n",

                 get_label_data->offset, get_label_data->length);

    status = nvdimm_rw_label_data_check(nvdimm, get_label_data->offset,

                                        get_label_data->length);

    if (status != 0 /* Success */) {

        nvdimm_dsm_no_payload(status, dsm_mem_addr);

        return;

    }

    size = sizeof(*get_label_data_out) + get_label_data->length;

    assert(size <= 4096);

    get_label_data_out = g_malloc(size);

    get_label_data_out->len = cpu_to_le32(size);

    get_label_data_out->func_ret_status = cpu_to_le32(0 /* Success */);

    nvc->read_label_data(nvdimm, get_label_data_out->out_buf,

                         get_label_data->length, get_label_data->offset);

    cpu_physical_memory_write(dsm_mem_addr, get_label_data_out, size);

    g_free(get_label_data_out);

}


static QObject *visitor_get(TestOutputVisitorData *data)

{

    visit_complete(data->ov, &data->obj);

    g_assert(data->obj);

    return data->obj;

}


static void fill_elf_header(struct elfhdr *elf, int segs, uint16_t machine,

                            uint32_t flags)

{

    (void) memset(elf, 0, sizeof(*elf));

    (void) memcpy(elf->e_ident, ELFMAG, SELFMAG);

    elf->e_ident[EI_CLASS] = ELF_CLASS;

    elf->e_ident[EI_DATA] = ELF_DATA;

    elf->e_ident[EI_VERSION] = EV_CURRENT;

    elf->e_ident[EI_OSABI] = ELF_OSABI;

    elf->e_type = ET_CORE;

    elf->e_machine = machine;

    elf->e_version = EV_CURRENT;

    elf->e_phoff = sizeof(struct elfhdr);

    elf->e_flags = flags;

    elf->e_ehsize = sizeof(struct elfhdr);

    elf->e_phentsize = sizeof(struct elf_phdr);

    elf->e_phnum = segs;

#ifdef BSWAP_NEEDED

    bswap_ehdr(elf);

#endif

}


static int vm_can_run(void)

{

    if (powerdown_requested)

        return 0;

    if (reset_requested)

        return 0;

    if (shutdown_requested)

        return 0;

    if (debug_requested)

        return 0;

    return 1;

}


void vga_common_init(VGACommonState *s, int vga_ram_size)

{

    int i, j, v, b;

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

        v = 0;

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

            v |= ((i >> j) & 1) << (j * 4);

        }

        expand4[i] = v;

        v = 0;

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

            v |= ((i >> (2 * j)) & 3) << (j * 4);

        }

        expand2[i] = v;

    }

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

        v = 0;

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

            b = ((i >> j) & 1);

            v |= b << (2 * j);

            v |= b << (2 * j + 1);

        }

        expand4to8[i] = v;

    }

#ifdef CONFIG_BOCHS_VBE

    s->is_vbe_vmstate = 1;

#else

    s->is_vbe_vmstate = 0;

#endif

    s->vram_offset = qemu_ram_alloc(vga_ram_size);

    s->vram_ptr = qemu_get_ram_ptr(s->vram_offset);

    s->vram_size = vga_ram_size;

    s->get_bpp = vga_get_bpp;

    s->get_offsets = vga_get_offsets;

    s->get_resolution = vga_get_resolution;

    s->update = vga_update_display;

    s->invalidate = vga_invalidate_display;

    s->screen_dump = vga_screen_dump;

    s->text_update = vga_update_text;

    switch (vga_retrace_method) {

    case VGA_RETRACE_DUMB:

        s->retrace = vga_dumb_retrace;

        s->update_retrace_info = vga_dumb_update_retrace_info;

        break;

    case VGA_RETRACE_PRECISE:

        s->retrace = vga_precise_retrace;

        s->update_retrace_info = vga_precise_update_retrace_info;

        break;

    }

    vga_reset(s);

}


InputEvent *qemu_input_event_new_btn(InputButton btn, bool down)

{

    InputEvent *evt = g_new0(InputEvent, 1);

    evt->btn = g_new0(InputBtnEvent, 1);

    evt->kind = INPUT_EVENT_KIND_BTN;

    evt->btn->button = btn;

    evt->btn->down = down;

    return evt;

}


static void ecc_diag_mem_write(void *opaque, target_phys_addr_t addr,

                               uint64_t val, unsigned size)

{

    ECCState *s = opaque;

    trace_ecc_diag_mem_writeb(addr, val);

    s->diag[addr & ECC_DIAG_MASK] = val;

}


static void imx_fec_do_tx(IMXFECState *s)

{

    int frame_size = 0;

    uint8_t frame[ENET_MAX_FRAME_SIZE];

    uint8_t *ptr = frame;

    uint32_t addr = s->tx_descriptor;

    while (1) {

        IMXFECBufDesc bd;

        int len;

        imx_fec_read_bd(&bd, addr);

        FEC_PRINTF("tx_bd %x flags %04x len %d data %08x\n",

                   addr, bd.flags, bd.length, bd.data);

        if ((bd.flags & ENET_BD_R) == 0) {

            /* Run out of descriptors to transmit.  */

            FEC_PRINTF("tx_bd ran out of descriptors to transmit\n");

            break;

        }

        len = bd.length;

        if (frame_size + len > ENET_MAX_FRAME_SIZE) {

            len = ENET_MAX_FRAME_SIZE - frame_size;

            s->regs[ENET_EIR] |= ENET_INT_BABT;

        }

        dma_memory_read(&address_space_memory, bd.data, ptr, len);

        ptr += len;

        frame_size += len;

        if (bd.flags & ENET_BD_L) {

            /* Last buffer in frame.  */

            qemu_send_packet(qemu_get_queue(s->nic), frame, frame_size);

            ptr = frame;

            frame_size = 0;

            s->regs[ENET_EIR] |= ENET_INT_TXF;

        }

        s->regs[ENET_EIR] |= ENET_INT_TXB;

        bd.flags &= ~ENET_BD_R;

        /* Write back the modified descriptor.  */

        imx_fec_write_bd(&bd, addr);

        /* Advance to the next descriptor.  */

        if ((bd.flags & ENET_BD_W) != 0) {

            addr = s->regs[ENET_TDSR];

        } else {

            addr += sizeof(bd);

        }

    }

    s->tx_descriptor = addr;

    imx_eth_update(s);

}


static void omap_eac_write(void *opaque, target_phys_addr_t addr,

                           uint64_t value, unsigned size)

{

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

    if (size != 2) {

        return omap_badwidth_write16(opaque, addr, value);

    }

    switch (addr) {

    case 0x098:	/* APD1LCR */

    case 0x09c:	/* APD1RCR */

    case 0x0a0:	/* APD2LCR */

    case 0x0a4:	/* APD2RCR */

    case 0x0a8:	/* APD3LCR */

    case 0x0ac:	/* APD3RCR */

    case 0x0b0:	/* APD4R */

    case 0x0b8:	/* ADRDR */

    case 0x0d0:	/* MPDDMARR */

    case 0x0d8:	/* MPUDMARR */

    case 0x0e4:	/* BPDDMARR */

    case 0x0ec:	/* BPUDMARR */

    case 0x100:	/* VERSION_NUMBER */

    case 0x108:	/* SYSSTATUS */

        OMAP_RO_REG(addr);

        return;

    case 0x000:	/* CPCFR1 */

        s->config[0] = value & 0xff;

        omap_eac_format_update(s);

        break;

    case 0x004:	/* CPCFR2 */

        s->config[1] = value & 0xff;

        omap_eac_format_update(s);

        break;

    case 0x008:	/* CPCFR3 */

        s->config[2] = value & 0xff;

        omap_eac_format_update(s);

        break;

    case 0x00c:	/* CPCFR4 */

        s->config[3] = value & 0xff;

        omap_eac_format_update(s);

        break;

    case 0x010:	/* CPTCTL */

        /* Assuming TXF and TXE bits are read-only... */

        s->control = value & 0x5f;

        omap_eac_interrupt_update(s);

        break;

    case 0x014:	/* CPTTADR */

        s->address = value & 0xff;

        break;

    case 0x018:	/* CPTDATL */

        s->data &= 0xff00;

        s->data |= value & 0xff;

        break;

    case 0x01c:	/* CPTDATH */

        s->data &= 0x00ff;

        s->data |= value << 8;

        break;

    case 0x020:	/* CPTVSLL */

        s->vtol = value & 0xf8;

        break;

    case 0x024:	/* CPTVSLH */

        s->vtsl = value & 0x9f;

        break;

    case 0x040:	/* MPCTR */

        s->modem.control = value & 0x8f;

        break;

    case 0x044:	/* MPMCCFR */

        s->modem.config = value & 0x7fff;

        break;

    case 0x060:	/* BPCTR */

        s->bt.control = value & 0x8f;

        break;

    case 0x064:	/* BPMCCFR */

        s->bt.config = value & 0x7fff;

        break;

    case 0x080:	/* AMSCFR */

        s->mixer = value & 0x0fff;

        break;

    case 0x084:	/* AMVCTR */

        s->gain[0] = value & 0xffff;

        break;

    case 0x088:	/* AM1VCTR */

        s->gain[1] = value & 0xff7f;

        break;

    case 0x08c:	/* AM2VCTR */

        s->gain[2] = value & 0xff7f;

        break;

    case 0x090:	/* AM3VCTR */

        s->gain[3] = value & 0xff7f;

        break;

    case 0x094:	/* ASTCTR */

        s->att = value & 0xff;

        break;

    case 0x0b4:	/* ADWR */

        s->codec.txbuf[s->codec.txlen ++] = value;

        if (unlikely(s->codec.txlen == EAC_BUF_LEN ||

                                s->codec.txlen == s->codec.txavail)) {

            if (s->codec.txavail)

                omap_eac_out_empty(s);

            /* Discard what couldn't be written */

            s->codec.txlen = 0;

        }

        break;

    case 0x0bc:	/* AGCFR */

        s->codec.config[0] = value & 0x07ff;

        omap_eac_format_update(s);

        break;

    case 0x0c0:	/* AGCTR */

        s->codec.config[1] = value & 0x780f;

        omap_eac_format_update(s);

        break;

    case 0x0c4:	/* AGCFR2 */

        s->codec.config[2] = value & 0x003f;

        omap_eac_format_update(s);

        break;

    case 0x0c8:	/* AGCFR3 */

        s->codec.config[3] = value & 0xffff;

        omap_eac_format_update(s);

        break;

    case 0x0cc:	/* MBPDMACTR */

    case 0x0d4:	/* MPDDMAWR */

    case 0x0e0:	/* MPUDMAWR */

    case 0x0e8:	/* BPDDMAWR */

    case 0x0f0:	/* BPUDMAWR */

        break;

    case 0x104:	/* SYSCONFIG */

        if (value & (1 << 1))				/* SOFTRESET */

            omap_eac_reset(s);

        s->sysconfig = value & 0x31d;

        break;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


static void do_hybrid_window(int order, int n, int non_rec, const float *in,

                             float *out, float *hist, float *out2,

                             const float *window)

{

    int i;

    float buffer1[order + 1];

    float buffer2[order + 1];

    float work[order + n + non_rec];

    /* update history */

    memmove(hist, hist + n, (order + non_rec)*sizeof(*hist));

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

        hist[order + non_rec + i] = in[n-i-1];

    colmult(work, window, hist, order + n + non_rec);

    convolve(buffer1, work + order    , n      , order);

    convolve(buffer2, work + order + n, non_rec, order);

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

        out2[i] = out2[i] * 0.5625 + buffer1[i];

        out [i] = out2[i]          + buffer2[i];

    }

    /* Multiply by the white noise correcting factor (WNCF) */

    *out *= 257./256.;

}


static void pxa2xx_rtc_hzupdate(PXA2xxRTCState *s)

{

    int64_t rt = qemu_get_clock(rt_clock);

    s->last_rcnr += ((rt - s->last_hz) << 15) /

            (1000 * ((s->rttr & 0xffff) + 1));

    s->last_rdcr += ((rt - s->last_hz) << 15) /

            (1000 * ((s->rttr & 0xffff) + 1));

    s->last_hz = rt;

}


void HELPER(wer)(CPUXtensaState *env, uint32_t data, uint32_t addr)

{

    address_space_stl(env->address_space_er, addr, data,

                      (MemTxAttrs){0}, NULL);

}


static void qemu_input_event_trace(QemuConsole *src, InputEvent *evt)

{

    const char *name;

    int qcode, idx = -1;

    if (src) {

        idx = qemu_console_get_index(src);

    }

    switch (evt->kind) {

    case INPUT_EVENT_KIND_KEY:

        switch (evt->key->key->kind) {

        case KEY_VALUE_KIND_NUMBER:

            qcode = qemu_input_key_number_to_qcode(evt->key->key->number);

            name = QKeyCode_lookup[qcode];

            trace_input_event_key_number(idx, evt->key->key->number,

                                         name, evt->key->down);

            break;

        case KEY_VALUE_KIND_QCODE:

            name = QKeyCode_lookup[evt->key->key->qcode];

            trace_input_event_key_qcode(idx, name, evt->key->down);

            break;

        case KEY_VALUE_KIND_MAX:

            /* keep gcc happy */

            break;

        }

        break;

    case INPUT_EVENT_KIND_BTN:

        name = InputButton_lookup[evt->btn->button];

        trace_input_event_btn(idx, name, evt->btn->down);

        break;

    case INPUT_EVENT_KIND_REL:

        name = InputAxis_lookup[evt->rel->axis];

        trace_input_event_rel(idx, name, evt->rel->value);

        break;

    case INPUT_EVENT_KIND_ABS:

        name = InputAxis_lookup[evt->abs->axis];

        trace_input_event_abs(idx, name, evt->abs->value);

        break;

    case INPUT_EVENT_KIND_MAX:

        /* keep gcc happy */

        break;

    }

}


void ff_aac_encode_tns_info(AACEncContext *s, SingleChannelElement *sce)

{

    int i, w, filt, coef_len, coef_compress;

    const int coef_res = MAX_LPC_PRECISION == 4 ? 1 : 0;

    const int is8 = sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE;

    put_bits(&s->pb, 1, !!sce->tns.present);

    if (!sce->tns.present)

        return;

    for (i = 0; i < sce->ics.num_windows; i++) {

        put_bits(&s->pb, 2 - is8, sce->tns.n_filt[i]);

        if (sce->tns.n_filt[i]) {

            put_bits(&s->pb, 1, !!coef_res);

            for (filt = 0; filt < sce->tns.n_filt[i]; filt++) {

                put_bits(&s->pb, 6 - 2 * is8, sce->tns.length[i][filt]);

                put_bits(&s->pb, 5 - 2 * is8, sce->tns.order[i][filt]);

                if (sce->tns.order[i][filt]) {

                    coef_compress = compress_coef(sce->tns.coef_idx[i][filt],

                                                  sce->tns.order[i][filt]);

                    put_bits(&s->pb, 1, !!sce->tns.direction[i][filt]);

                    put_bits(&s->pb, 1, !!coef_compress);

                    coef_len = coef_res + 3 - coef_compress;

                    for (w = 0; w < sce->tns.order[i][filt]; w++)

                        put_bits(&s->pb, coef_len, sce->tns.coef_idx[i][filt][w]);

                }

            }

        }

    }

}


AVFilterBufferRef *avfilter_null_get_audio_buffer(AVFilterLink *link, int perms,

                                                  enum AVSampleFormat sample_fmt, int size,

                                                  int64_t channel_layout, int packed)

{

    return avfilter_get_audio_buffer(link->dst->outputs[0], perms, sample_fmt,

                                     size, channel_layout, packed);

}


static void tcp_chr_read(void *opaque)

{

    CharDriverState *chr = opaque;

    TCPCharDriver *s = chr->opaque;

    uint8_t buf[1024];

    int len, size;

    if (!s->connected || s->max_size <= 0)

        return;

    len = sizeof(buf);

    if (len > s->max_size)

        len = s->max_size;

    size = tcp_chr_recv(chr, (void *)buf, len);

    if (size == 0) {

        /* connection closed */

        s->connected = 0;

        if (s->listen_fd >= 0) {

            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);

        }

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

        closesocket(s->fd);

        s->fd = -1;

        qemu_chr_event(chr, CHR_EVENT_CLOSED);

    } else if (size > 0) {

        if (s->do_telnetopt)

            tcp_chr_process_IAC_bytes(chr, s, buf, &size);

        if (size > 0)

            qemu_chr_read(chr, buf, size);

        if (s->msgfd != -1) {

            close(s->msgfd);

            s->msgfd = -1;

        }

    }

}


uint64_t helper_fctid(CPUPPCState *env, uint64_t arg)

{

    CPU_DoubleU farg;

    farg.ll = arg;

    if (unlikely(float64_is_signaling_nan(farg.d))) {

        /* sNaN conversion */

        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |

                                        POWERPC_EXCP_FP_VXCVI);

    } else if (unlikely(float64_is_quiet_nan(farg.d) ||

                        float64_is_infinity(farg.d))) {

        /* qNan / infinity conversion */

        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXCVI);

    } else {

        farg.ll = float64_to_int64(farg.d, &env->fp_status);

    }

    return farg.ll;

}


static uint64_t cchip_read(void *opaque, target_phys_addr_t addr, unsigned size)

{

    CPUAlphaState *env = cpu_single_env;

    TyphoonState *s = opaque;

    uint64_t ret = 0;

    if (addr & 4) {

        return s->latch_tmp;

    }

    switch (addr) {

    case 0x0000:

        /* CSC: Cchip System Configuration Register.  */

        /* All sorts of data here; probably the only thing relevant is

           PIP<14> Pchip 1 Present = 0.  */

        break;

    case 0x0040:

        /* MTR: Memory Timing Register.  */

        /* All sorts of stuff related to real DRAM.  */

        break;

    case 0x0080:

        /* MISC: Miscellaneous Register.  */

        ret = s->cchip.misc | (env->cpu_index & 3);

        break;

    case 0x00c0:

        /* MPD: Memory Presence Detect Register.  */

        break;

    case 0x0100: /* AAR0 */

    case 0x0140: /* AAR1 */

    case 0x0180: /* AAR2 */

    case 0x01c0: /* AAR3 */

        /* AAR: Array Address Register.  */

        /* All sorts of information about DRAM.  */

        break;

    case 0x0200:

        /* DIM0: Device Interrupt Mask Register, CPU0.  */

        ret = s->cchip.dim[0];

        break;

    case 0x0240:

        /* DIM1: Device Interrupt Mask Register, CPU1.  */

        ret = s->cchip.dim[1];

        break;

    case 0x0280:

        /* DIR0: Device Interrupt Request Register, CPU0.  */

        ret = s->cchip.dim[0] & s->cchip.drir;

        break;

    case 0x02c0:

        /* DIR1: Device Interrupt Request Register, CPU1.  */

        ret = s->cchip.dim[1] & s->cchip.drir;

        break;

    case 0x0300:

        /* DRIR: Device Raw Interrupt Request Register.  */

        ret = s->cchip.drir;

        break;

    case 0x0340:

        /* PRBEN: Probe Enable Register.  */

        break;

    case 0x0380:

        /* IIC0: Interval Ignore Count Register, CPU0.  */

        ret = s->cchip.iic[0];

        break;

    case 0x03c0:

        /* IIC1: Interval Ignore Count Register, CPU1.  */

        ret = s->cchip.iic[1];

        break;

    case 0x0400: /* MPR0 */

    case 0x0440: /* MPR1 */

    case 0x0480: /* MPR2 */

    case 0x04c0: /* MPR3 */

        /* MPR: Memory Programming Register.  */

        break;

    case 0x0580:

        /* TTR: TIGbus Timing Register.  */

        /* All sorts of stuff related to interrupt delivery timings.  */

        break;

    case 0x05c0:

        /* TDR: TIGbug Device Timing Register.  */

        break;

    case 0x0600:

        /* DIM2: Device Interrupt Mask Register, CPU2.  */

        ret = s->cchip.dim[2];

        break;

    case 0x0640:

        /* DIM3: Device Interrupt Mask Register, CPU3.  */

        ret = s->cchip.dim[3];

        break;

    case 0x0680:

        /* DIR2: Device Interrupt Request Register, CPU2.  */

        ret = s->cchip.dim[2] & s->cchip.drir;

        break;

    case 0x06c0:

        /* DIR3: Device Interrupt Request Register, CPU3.  */

        ret = s->cchip.dim[3] & s->cchip.drir;

        break;

    case 0x0700:

        /* IIC2: Interval Ignore Count Register, CPU2.  */

        ret = s->cchip.iic[2];

        break;

    case 0x0740:

        /* IIC3: Interval Ignore Count Register, CPU3.  */

        ret = s->cchip.iic[3];

        break;

    case 0x0780:

        /* PWR: Power Management Control.   */

        break;

    case 0x0c00: /* CMONCTLA */

    case 0x0c40: /* CMONCTLB */

    case 0x0c80: /* CMONCNT01 */

    case 0x0cc0: /* CMONCNT23 */

        break;

    default:

        cpu_unassigned_access(cpu_single_env, addr, 0, 0, 0, size);

        return -1;

    }

    s->latch_tmp = ret >> 32;

    return ret;

}


void qemu_system_reset(ShutdownCause reason)

{

    MachineClass *mc;

    mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;

    cpu_synchronize_all_states();

    if (mc && mc->reset) {

        mc->reset();

    } else {

        qemu_devices_reset();

    }

    if (reason) {

        /* TODO update event based on reason */

        qapi_event_send_reset(&error_abort);

    }

    cpu_synchronize_all_post_reset();

}


static int gdb_handle_packet(GDBState *s, CPUState *env, const char *line_buf)

{

    const char *p;

    int ch, reg_size, type;

    char buf[MAX_PACKET_LENGTH];

    uint8_t mem_buf[MAX_PACKET_LENGTH];

    uint8_t *registers;

    target_ulong addr, len;

#ifdef DEBUG_GDB

    printf("command='%s'\n", line_buf);

#endif

    p = line_buf;

    ch = *p++;

    switch(ch) {

    case '?':

        /* TODO: Make this return the correct value for user-mode.  */

        snprintf(buf, sizeof(buf), "S%02x", SIGTRAP);

        put_packet(s, buf);

        /* Remove all the breakpoints when this query is issued,

         * because gdb is doing and initial connect and the state

         * should be cleaned up.

         */

        cpu_breakpoint_remove_all(env);

        cpu_watchpoint_remove_all(env);

        break;

    case 'c':

        if (*p != '\0') {

            addr = strtoull(p, (char **)&p, 16);

#if defined(TARGET_I386)

            env->eip = addr;

#elif defined (TARGET_PPC)

            env->nip = addr;

#elif defined (TARGET_SPARC)

            env->pc = addr;

            env->npc = addr + 4;

#elif defined (TARGET_ARM)

            env->regs[15] = addr;

#elif defined (TARGET_SH4)

            env->pc = addr;

#elif defined (TARGET_MIPS)

            env->active_tc.PC = addr;

#elif defined (TARGET_CRIS)

            env->pc = addr;

#endif

        }

        gdb_continue(s);

	return RS_IDLE;

    case 'C':

        s->signal = strtoul(p, (char **)&p, 16);

        gdb_continue(s);

        return RS_IDLE;

    case 'k':

        /* Kill the target */

        fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");

        exit(0);

    case 'D':

        /* Detach packet */

        cpu_breakpoint_remove_all(env);

        cpu_watchpoint_remove_all(env);

        gdb_continue(s);

        put_packet(s, "OK");

        break;

    case 's':

        if (*p != '\0') {

            addr = strtoull(p, (char **)&p, 16);

#if defined(TARGET_I386)

            env->eip = addr;

#elif defined (TARGET_PPC)

            env->nip = addr;

#elif defined (TARGET_SPARC)

            env->pc = addr;

            env->npc = addr + 4;

#elif defined (TARGET_ARM)

            env->regs[15] = addr;

#elif defined (TARGET_SH4)

            env->pc = addr;

#elif defined (TARGET_MIPS)

            env->active_tc.PC = addr;

#elif defined (TARGET_CRIS)

            env->pc = addr;

#endif

        }

        cpu_single_step(env, sstep_flags);

        gdb_continue(s);

	return RS_IDLE;

    case 'F':

        {

            target_ulong ret;

            target_ulong err;

            ret = strtoull(p, (char **)&p, 16);

            if (*p == ',') {

                p++;

                err = strtoull(p, (char **)&p, 16);

            } else {

                err = 0;

            }

            if (*p == ',')

                p++;

            type = *p;

            if (gdb_current_syscall_cb)

                gdb_current_syscall_cb(s->env, ret, err);

            if (type == 'C') {

                put_packet(s, "T02");

            } else {

                gdb_continue(s);

            }

        }

        break;

    case 'g':

        len = 0;

        for (addr = 0; addr < num_g_regs; addr++) {

            reg_size = gdb_read_register(env, mem_buf + len, addr);

            len += reg_size;

        }

        memtohex(buf, mem_buf, len);

        put_packet(s, buf);

        break;

    case 'G':

        registers = mem_buf;

        len = strlen(p) / 2;

        hextomem((uint8_t *)registers, p, len);

        for (addr = 0; addr < num_g_regs && len > 0; addr++) {

            reg_size = gdb_write_register(env, registers, addr);

            len -= reg_size;

            registers += reg_size;

        }

        put_packet(s, "OK");

        break;

    case 'm':

        addr = strtoull(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        len = strtoull(p, NULL, 16);

        if (cpu_memory_rw_debug(env, addr, mem_buf, len, 0) != 0) {

            put_packet (s, "E14");

        } else {

            memtohex(buf, mem_buf, len);

            put_packet(s, buf);

        }

        break;

    case 'M':

        addr = strtoull(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        len = strtoull(p, (char **)&p, 16);

        if (*p == ':')

            p++;

        hextomem(mem_buf, p, len);

        if (cpu_memory_rw_debug(env, addr, mem_buf, len, 1) != 0)

            put_packet(s, "E14");

        else

            put_packet(s, "OK");

        break;

    case 'p':

        /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.

           This works, but can be very slow.  Anything new enough to

           understand XML also knows how to use this properly.  */

        if (!gdb_has_xml)

            goto unknown_command;

        addr = strtoull(p, (char **)&p, 16);

        reg_size = gdb_read_register(env, mem_buf, addr);

        if (reg_size) {

            memtohex(buf, mem_buf, reg_size);

            put_packet(s, buf);

        } else {

            put_packet(s, "E14");

        }

        break;

    case 'P':

        if (!gdb_has_xml)

            goto unknown_command;

        addr = strtoull(p, (char **)&p, 16);

        if (*p == '=')

            p++;

        reg_size = strlen(p) / 2;

        hextomem(mem_buf, p, reg_size);

        gdb_write_register(env, mem_buf, addr);

        put_packet(s, "OK");

        break;

    case 'Z':

        type = strtoul(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        addr = strtoull(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        len = strtoull(p, (char **)&p, 16);

        switch (type) {

        case 0:

        case 1:

            if (cpu_breakpoint_insert(env, addr) < 0)

                goto breakpoint_error;

            put_packet(s, "OK");

            break;

#ifndef CONFIG_USER_ONLY

        case 2:

            type = PAGE_WRITE;

            goto insert_watchpoint;

        case 3:

            type = PAGE_READ;

            goto insert_watchpoint;

        case 4:

            type = PAGE_READ | PAGE_WRITE;

        insert_watchpoint:

            if (cpu_watchpoint_insert(env, addr, type) < 0)

                goto breakpoint_error;

            put_packet(s, "OK");

            break;

#endif

        default:

            put_packet(s, "");

            break;

        }

        break;

    breakpoint_error:

        put_packet(s, "E22");

        break;

    case 'z':

        type = strtoul(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        addr = strtoull(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        len = strtoull(p, (char **)&p, 16);

        if (type == 0 || type == 1) {

            cpu_breakpoint_remove(env, addr);

            put_packet(s, "OK");

#ifndef CONFIG_USER_ONLY

        } else if (type >= 2 || type <= 4) {

            cpu_watchpoint_remove(env, addr);

            put_packet(s, "OK");

#endif

        } else {

            put_packet(s, "");

        }

        break;

    case 'q':

    case 'Q':

        /* parse any 'q' packets here */

        if (!strcmp(p,"qemu.sstepbits")) {

            /* Query Breakpoint bit definitions */

            snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",

                     SSTEP_ENABLE,

                     SSTEP_NOIRQ,

                     SSTEP_NOTIMER);

            put_packet(s, buf);

            break;

        } else if (strncmp(p,"qemu.sstep",10) == 0) {

            /* Display or change the sstep_flags */

            p += 10;

            if (*p != '=') {

                /* Display current setting */

                snprintf(buf, sizeof(buf), "0x%x", sstep_flags);

                put_packet(s, buf);

                break;

            }

            p++;

            type = strtoul(p, (char **)&p, 16);

            sstep_flags = type;

            put_packet(s, "OK");

            break;

        }

#ifdef CONFIG_LINUX_USER

        else if (strncmp(p, "Offsets", 7) == 0) {

            TaskState *ts = env->opaque;

            snprintf(buf, sizeof(buf),

                     "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx

                     ";Bss=" TARGET_ABI_FMT_lx,

                     ts->info->code_offset,

                     ts->info->data_offset,

                     ts->info->data_offset);

            put_packet(s, buf);

            break;

        }

#endif

        if (strncmp(p, "Supported", 9) == 0) {

            sprintf(buf, "PacketSize=%x", MAX_PACKET_LENGTH);

#ifdef GDB_CORE_XML

            strcat(buf, ";qXfer:features:read+");

#endif

            put_packet(s, buf);

            break;

        }

#ifdef GDB_CORE_XML

        if (strncmp(p, "Xfer:features:read:", 19) == 0) {

            const char *xml;

            target_ulong total_len;

            gdb_has_xml = 1;

            p += 19;

            xml = get_feature_xml(env, p, &p);

            if (!xml) {

                sprintf(buf, "E00");

                put_packet(s, buf);

                break;

            }

            if (*p == ':')

                p++;

            addr = strtoul(p, (char **)&p, 16);

            if (*p == ',')

                p++;

            len = strtoul(p, (char **)&p, 16);

            total_len = strlen(xml);

            if (addr > total_len) {

                sprintf(buf, "E00");

                put_packet(s, buf);

                break;

            }

            if (len > (MAX_PACKET_LENGTH - 5) / 2)

                len = (MAX_PACKET_LENGTH - 5) / 2;

            if (len < total_len - addr) {

                buf[0] = 'm';

                len = memtox(buf + 1, xml + addr, len);

            } else {

                buf[0] = 'l';

                len = memtox(buf + 1, xml + addr, total_len - addr);

            }

            put_packet_binary(s, buf, len + 1);

            break;

        }

#endif

        /* Unrecognised 'q' command.  */

        goto unknown_command;

    default:

    unknown_command:

        /* put empty packet */

        buf[0] = '\0';

        put_packet(s, buf);

        break;

    }

    return RS_IDLE;

}


av_cold void ff_volume_init_x86(VolumeContext *vol)

{

    int cpu_flags = av_get_cpu_flags();

    enum AVSampleFormat sample_fmt = av_get_packed_sample_fmt(vol->sample_fmt);

    if (sample_fmt == AV_SAMPLE_FMT_S16) {

        if (EXTERNAL_SSE2(cpu_flags) && vol->volume_i < 32768) {

            vol->scale_samples = ff_scale_samples_s16_sse2;

            vol->samples_align = 8;

        }

    } else if (sample_fmt == AV_SAMPLE_FMT_S32) {

        if (EXTERNAL_SSE2(cpu_flags)) {

            vol->scale_samples = ff_scale_samples_s32_sse2;

            vol->samples_align = 4;

        }

        if (EXTERNAL_SSSE3(cpu_flags) && cpu_flags & AV_CPU_FLAG_ATOM) {

            vol->scale_samples = ff_scale_samples_s32_ssse3_atom;

            vol->samples_align = 4;

        }

        if (EXTERNAL_AVX(cpu_flags)) {

            vol->scale_samples = ff_scale_samples_s32_avx;

            vol->samples_align = 8;

        }

    }

}


static void pxb_register_bus(PCIDevice *dev, PCIBus *pxb_bus, Error **errp)

{

    PCIBus *bus = dev->bus;

    int pxb_bus_num = pci_bus_num(pxb_bus);

    if (bus->parent_dev) {

        error_setg(errp, "PXB devices can be attached only to root bus");

        return;

    }

    QLIST_FOREACH(bus, &bus->child, sibling) {

        if (pci_bus_num(bus) == pxb_bus_num) {

            error_setg(errp, "Bus %d is already in use", pxb_bus_num);

            return;

        }

    }

    QLIST_INSERT_HEAD(&dev->bus->child, pxb_bus, sibling);

}


static void v9fs_flush(void *opaque)

{

    int16_t tag;

    size_t offset = 7;

    V9fsPDU *cancel_pdu;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "w", &tag);

    trace_v9fs_flush(pdu->tag, pdu->id, tag);

    QLIST_FOREACH(cancel_pdu, &s->active_list, next) {

        if (cancel_pdu->tag == tag) {

            break;

        }

    }

    if (cancel_pdu) {

        cancel_pdu->cancelled = 1;

        /*

         * Wait for pdu to complete.

         */

        qemu_co_queue_wait(&cancel_pdu->complete);

        cancel_pdu->cancelled = 0;

        free_pdu(pdu->s, cancel_pdu);

    }

    complete_pdu(s, pdu, 7);

    return;

}


static uint32_t reloc_pc24_val(tcg_insn_unit *pc, tcg_insn_unit *target)

{

    ptrdiff_t disp = tcg_ptr_byte_diff(target, pc);

    assert(in_range_b(disp));

    return disp & 0x3fffffc;

}


static void enable_interrupt(EEPRO100State * s)

{

    if (!s->int_stat) {

        logout("interrupt enabled\n");

        qemu_irq_raise(s->pci_dev->irq[0]);

        s->int_stat = 1;

    }

}


static abi_ulong load_elf_interp(struct elfhdr * interp_elf_ex,

                                 int interpreter_fd,

                                 abi_ulong *interp_load_addr,

                                 char bprm_buf[BPRM_BUF_SIZE])

{

    struct elf_phdr *elf_phdata  =  NULL;

    abi_ulong load_addr, load_bias, loaddr, hiaddr;

    int retval;

    abi_ulong error;

    int i;

    bswap_ehdr(interp_elf_ex);

    /* First of all, some simple consistency checks */

    if ((interp_elf_ex->e_type != ET_EXEC &&

         interp_elf_ex->e_type != ET_DYN) ||

        !elf_check_arch(interp_elf_ex->e_machine)) {

        return ~((abi_ulong)0UL);

    }

    /* Now read in all of the header information */

    if (sizeof(struct elf_phdr) * interp_elf_ex->e_phnum > TARGET_PAGE_SIZE)

        return ~(abi_ulong)0UL;

    elf_phdata =  (struct elf_phdr *)

        malloc(sizeof(struct elf_phdr) * interp_elf_ex->e_phnum);

    if (!elf_phdata)

        return ~((abi_ulong)0UL);

    /*

     * If the size of this structure has changed, then punt, since

     * we will be doing the wrong thing.

     */

    if (interp_elf_ex->e_phentsize != sizeof(struct elf_phdr)) {

        free(elf_phdata);

        return ~((abi_ulong)0UL);

    }

    i = interp_elf_ex->e_phnum * sizeof(struct elf_phdr);

    if (interp_elf_ex->e_phoff + i <= BPRM_BUF_SIZE) {

        memcpy(elf_phdata, bprm_buf + interp_elf_ex->e_phoff, i);

    } else {

        retval = pread(interpreter_fd, elf_phdata, i, interp_elf_ex->e_phoff);

        if (retval != i) {

            perror("load_elf_interp");

            exit(-1);

        }

    }

    bswap_phdr(elf_phdata, interp_elf_ex->e_phnum);

    /* Find the maximum size of the image and allocate an appropriate

       amount of memory to handle that.  */

    loaddr = -1, hiaddr = 0;

    for (i = 0; i < interp_elf_ex->e_phnum; ++i) {

        if (elf_phdata[i].p_type == PT_LOAD) {

            abi_ulong a = elf_phdata[i].p_vaddr;

            if (a < loaddr) {

                loaddr = a;

            }

            a += elf_phdata[i].p_memsz;

            if (a > hiaddr) {

                hiaddr = a;

            }

        }

    }

    load_addr = loaddr;

    if (interp_elf_ex->e_type == ET_DYN) {

        /* The image indicates that it can be loaded anywhere.  Find a

           location that can hold the memory space required.  If the

           image is pre-linked, LOADDR will be non-zero.  Since we do

           not supply MAP_FIXED here we'll use that address if and

           only if it remains available.  */

        load_addr = target_mmap(loaddr, hiaddr - loaddr, PROT_NONE,

                                MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,

                                -1, 0);

        if (load_addr == -1) {

            perror("mmap");

            exit(-1);

        }

    }

    load_bias = load_addr - loaddr;

    for (i = 0; i < interp_elf_ex->e_phnum; i++) {

        struct elf_phdr *eppnt = elf_phdata + i;

        if (eppnt->p_type == PT_LOAD) {

            abi_ulong vaddr, vaddr_po, vaddr_ps, vaddr_ef, vaddr_em;

            int elf_prot = 0;

            if (eppnt->p_flags & PF_R) elf_prot =  PROT_READ;

            if (eppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;

            if (eppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;

            vaddr = load_bias + eppnt->p_vaddr;

            vaddr_po = TARGET_ELF_PAGEOFFSET(vaddr);

            vaddr_ps = TARGET_ELF_PAGESTART(vaddr);

            error = target_mmap(vaddr_ps, eppnt->p_filesz + vaddr_po,

                                elf_prot, MAP_PRIVATE | MAP_FIXED,

                                interpreter_fd, eppnt->p_offset - vaddr_po);

            if (error == -1) {

                /* Real error */

                close(interpreter_fd);

                free(elf_phdata);

                return ~((abi_ulong)0UL);

            }

            vaddr_ef = vaddr + eppnt->p_filesz;

            vaddr_em = vaddr + eppnt->p_memsz;

            /* If the load segment requests extra zeros (e.g. bss), map it.  */

            if (vaddr_ef < vaddr_em) {

                zero_bss(vaddr_ef, vaddr_em, elf_prot);

            }

        }

    }

    if (qemu_log_enabled()) {

        load_symbols(interp_elf_ex, interpreter_fd, load_bias);

    }

    close(interpreter_fd);

    free(elf_phdata);

    *interp_load_addr = load_addr;

    return ((abi_ulong) interp_elf_ex->e_entry) + load_bias;

}


static int execute_command(BlockDriverState *bdrv,

                           SCSIGenericReq *r, int direction,

                           BlockCompletionFunc *complete)

{

    r->io_header.interface_id = 'S';

    r->io_header.dxfer_direction = direction;

    r->io_header.dxferp = r->buf;

    r->io_header.dxfer_len = r->buflen;

    r->io_header.cmdp = r->req.cmd.buf;

    r->io_header.cmd_len = r->req.cmd.len;

    r->io_header.mx_sb_len = sizeof(r->req.sense);

    r->io_header.sbp = r->req.sense;

    r->io_header.timeout = MAX_UINT;

    r->io_header.usr_ptr = r;

    r->io_header.flags |= SG_FLAG_DIRECT_IO;

    r->req.aiocb = bdrv_aio_ioctl(bdrv, SG_IO, &r->io_header, complete, r);

    if (r->req.aiocb == NULL) {

        return -EIO;

    }

    return 0;

}


void stq_phys_notdirty(target_phys_addr_t addr, uint64_t val)

{

    uint8_t *ptr;

    MemoryRegionSection *section;

    section = phys_page_find(addr >> TARGET_PAGE_BITS);

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

        addr = memory_region_section_addr(section, addr);

        if (memory_region_is_ram(section->mr)) {

            section = &phys_sections[phys_section_rom];

        }

#ifdef TARGET_WORDS_BIGENDIAN

        io_mem_write(section->mr, addr, val >> 32, 4);

        io_mem_write(section->mr, addr + 4, (uint32_t)val, 4);

#else

        io_mem_write(section->mr, addr, (uint32_t)val, 4);

        io_mem_write(section->mr, addr + 4, val >> 32, 4);

#endif

    } else {

        ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(section->mr)

                                & TARGET_PAGE_MASK)

                               + memory_region_section_addr(section, addr));

        stq_p(ptr, val);

    }

}


static void clear_program(MpegTSContext *ts, unsigned int programid)

{

    int i;

    clear_avprogram(ts, programid);

    for(i=0; i<ts->nb_prg; i++)

        if(ts->prg[i].id == programid)

            ts->prg[i].nb_pids = 0;

}


static void jpeg2000_flush(Jpeg2000DecoderContext *s)

{

    if (*s->buf == 0xff)

        s->buf++;

    s->bit_index = 8;

    s->buf++;

}


static void kvm_apic_mem_write(void *opaque, target_phys_addr_t addr,

                               uint64_t data, unsigned size)

{

    MSIMessage msg = { .address = addr, .data = data };

    int ret;

    ret = kvm_irqchip_send_msi(kvm_state, msg);

    if (ret < 0) {

        fprintf(stderr, "KVM: injection failed, MSI lost (%s)\n",

                strerror(-ret));

    }

}


void os_daemonize(void)

{

    if (daemonize) {

        pid_t pid;

        int fds[2];

        if (pipe(fds) == -1) {

            exit(1);

        }

        pid = fork();

        if (pid > 0) {

            uint8_t status;

            ssize_t len;

            close(fds[1]);

        again:

            len = read(fds[0], &status, 1);

            if (len == -1 && (errno == EINTR)) {

                goto again;

            }

            if (len != 1) {

                exit(1);

            }

            else if (status == 1) {

                fprintf(stderr, "Could not acquire pidfile\n");

                exit(1);

            } else {

                exit(0);

            }

            } else if (pid < 0) {

                exit(1);

            }

        close(fds[0]);

        daemon_pipe = fds[1];

        qemu_set_cloexec(daemon_pipe);

        setsid();

        pid = fork();

        if (pid > 0) {

            exit(0);

        } else if (pid < 0) {

            exit(1);

        }

        umask(027);

        signal(SIGTSTP, SIG_IGN);

        signal(SIGTTOU, SIG_IGN);

        signal(SIGTTIN, SIG_IGN);

    }

}


int cpu_signal_handler(int host_signum, void *pinfo,

                           void *puc)

{

    siginfo_t *info = pinfo;

    ucontext_t *uc = puc;

    uint32_t *pc = uc->uc_mcontext.sc_pc;

    uint32_t insn = *pc;

    int is_write = 0;

    /* XXX: need kernel patch to get write flag faster */

    switch (insn >> 26) {

    case 0x0d: /* stw */

    case 0x0e: /* stb */

    case 0x0f: /* stq_u */

    case 0x24: /* stf */

    case 0x25: /* stg */

    case 0x26: /* sts */

    case 0x27: /* stt */

    case 0x2c: /* stl */

    case 0x2d: /* stq */

    case 0x2e: /* stl_c */

    case 0x2f: /* stq_c */

        is_write = 1;

    }

    return handle_cpu_signal(pc, (unsigned long)info->si_addr,

                             is_write, &uc->uc_sigmask);

}


static uint32_t bitband_readw(void *opaque, target_phys_addr_t offset)

{

    uint32_t addr;

    uint16_t mask;

    uint16_t v;

    addr = bitband_addr(opaque, offset) & ~1;

    mask = (1 << ((offset >> 2) & 15));

    mask = tswap16(mask);

    cpu_physical_memory_read(addr, (uint8_t *)&v, 2);

    return (v & mask) != 0;

}


static void sd_set_ocr(SDState *sd)

{

    /* All voltages OK, card power-up OK, Standard Capacity SD Memory Card */

    sd->ocr = 0x80ffff00;

}


static uint32_t pxa2xx_rtc_read(void *opaque, target_phys_addr_t addr)

{

    PXA2xxRTCState *s = (PXA2xxRTCState *) opaque;

    switch (addr) {

    case RTTR:

        return s->rttr;

    case RTSR:

        return s->rtsr;

    case RTAR:

        return s->rtar;

    case RDAR1:

        return s->rdar1;

    case RDAR2:

        return s->rdar2;

    case RYAR1:

        return s->ryar1;

    case RYAR2:

        return s->ryar2;

    case SWAR1:

        return s->swar1;

    case SWAR2:

        return s->swar2;

    case PIAR:

        return s->piar;

    case RCNR:

        return s->last_rcnr + ((qemu_get_clock(rt_clock) - s->last_hz) << 15) /

                (1000 * ((s->rttr & 0xffff) + 1));

    case RDCR:

        return s->last_rdcr + ((qemu_get_clock(rt_clock) - s->last_hz) << 15) /

                (1000 * ((s->rttr & 0xffff) + 1));

    case RYCR:

        return s->last_rycr;

    case SWCR:

        if (s->rtsr & (1 << 12))

            return s->last_swcr + (qemu_get_clock(rt_clock) - s->last_sw) / 10;

        else

            return s->last_swcr;

    default:

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

        break;

    }

    return 0;

}


static int check_protocol_support(bool *has_ipv4, bool *has_ipv6)

{

#ifdef HAVE_IFADDRS_H

    struct ifaddrs *ifaddr = NULL, *ifa;

    struct addrinfo hints = { 0 };

    struct addrinfo *ai = NULL;

    int gaierr;

    *has_ipv4 = *has_ipv6 = false;

    if (getifaddrs(&ifaddr) < 0) {

        g_printerr("Failed to lookup interface addresses: %s\n",

                   strerror(errno));

        return -1;

    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {

        if (!ifa->ifa_addr) {

            continue;

        }

        if (ifa->ifa_addr->sa_family == AF_INET) {

            *has_ipv4 = true;

        }

        if (ifa->ifa_addr->sa_family == AF_INET6) {

            *has_ipv6 = true;

        }

    }

    freeifaddrs(ifaddr);

    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;

    hints.ai_family = AF_INET6;

    hints.ai_socktype = SOCK_STREAM;

    gaierr = getaddrinfo("::1", NULL, &hints, &ai);

    if (gaierr != 0) {

        if (gaierr == EAI_ADDRFAMILY ||

            gaierr == EAI_FAMILY ||

            gaierr == EAI_NONAME) {

            *has_ipv6 = false;

        } else {

            g_printerr("Failed to resolve ::1 address: %s\n",

                       gai_strerror(gaierr));

            return -1;

        }

    }

    freeaddrinfo(ai);

    return 0;

#else

    *has_ipv4 = *has_ipv6 = false;

    return -1;

#endif

}


static int init(AVFilterContext *ctx)

{

    EvalContext *eval = ctx->priv;

    char *args1 = av_strdup(eval->exprs);

    char *expr, *buf;

    int ret, i;

    if (!args1) {

        av_log(ctx, AV_LOG_ERROR, "Channels expressions list is empty\n");

        ret = eval->exprs ? AVERROR(ENOMEM) : AVERROR(EINVAL);

        goto end;

    }

    /* parse expressions */

    buf = args1;

    i = 0;

    while (i < FF_ARRAY_ELEMS(eval->expr) && (expr = av_strtok(buf, "|", &buf))) {

        ret = av_expr_parse(&eval->expr[i], expr, var_names,

                            NULL, NULL, NULL, NULL, 0, ctx);

        if (ret < 0)

            goto end;

        i++;

    }

    eval->nb_channels = i;

    if (eval->chlayout_str) {

        int n;

        ret = ff_parse_channel_layout(&eval->chlayout, eval->chlayout_str, ctx);

        if (ret < 0)

            goto end;

        n = av_get_channel_layout_nb_channels(eval->chlayout);

        if (n != eval->nb_channels) {

            av_log(ctx, AV_LOG_ERROR,

                   "Mismatch between the specified number of channels '%d' "

                   "and the number of channels '%d' in the specified channel layout '%s'\n",

                   eval->nb_channels, n, eval->chlayout_str);

            ret = AVERROR(EINVAL);

            goto end;

        }

    } else {

        /* guess channel layout from nb expressions/channels */

        eval->chlayout = av_get_default_channel_layout(eval->nb_channels);

        if (!eval->chlayout) {

            av_log(ctx, AV_LOG_ERROR, "Invalid number of channels '%d' provided\n",

                   eval->nb_channels);

            ret = AVERROR(EINVAL);

            goto end;

        }

    }

    if ((ret = ff_parse_sample_rate(&eval->sample_rate, eval->sample_rate_str, ctx)))

        goto end;

    eval->n = 0;

end:

    av_free(args1);

    return ret;

}


void OPPROTO op_addl_EDI_T0(void)

{

    EDI = (uint32_t)(EDI + T0);

}