static coroutine_fn void nbd_read_reply_entry(void *opaque)

{

    NBDClientSession *s = opaque;

    uint64_t i;

    int ret;

    for (;;) {

        assert(s->reply.handle == 0);

        ret = nbd_receive_reply(s->ioc, &s->reply);

        if (ret < 0) {

            break;

        }

        /* There's no need for a mutex on the receive side, because the

         * handler acts as a synchronization point and ensures that only

         * one coroutine is called until the reply finishes.

         */

        i = HANDLE_TO_INDEX(s, s->reply.handle);

        if (i >= MAX_NBD_REQUESTS || !s->recv_coroutine[i]) {

            break;

        }

        /* We're woken up by the recv_coroutine itself.  Note that there

         * is no race between yielding and reentering read_reply_co.  This

         * is because:

         *

         * - if recv_coroutine[i] runs on the same AioContext, it is only

         *   entered after we yield

         *

         * - if recv_coroutine[i] runs on a different AioContext, reentering

         *   read_reply_co happens through a bottom half, which can only

         *   run after we yield.

         */

        aio_co_wake(s->recv_coroutine[i]);

        qemu_coroutine_yield();

    }

    s->read_reply_co = NULL;

}


static int mp_pacl_removexattr(FsContext *ctx,

                               const char *path, const char *name)

{

    int ret;

    char buffer[PATH_MAX];

    ret  = lremovexattr(rpath(ctx, path, buffer), MAP_ACL_ACCESS);

    if (ret == -1 && errno == ENODATA) {

        /*

         * We don't get ENODATA error when trying to remove a

         * posix acl that is not present. So don't throw the error

         * even in case of mapped security model

         */

        errno = 0;

        ret = 0;

    }

    return ret;

}


float32 HELPER(ucf64_adds)(float32 a, float32 b, CPUUniCore32State *env)

{

    return float32_add(a, b, &env->ucf64.fp_status);

}


static void test_validate_fail_struct(TestInputVisitorData *data,

                                       const void *unused)

{

    TestStruct *p = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data, "{ 'integer': -42, 'boolean': true, 'string': 'foo', 'extra': 42 }");

    visit_type_TestStruct(v, NULL, &p, &err);

    error_free_or_abort(&err);

    g_assert(!p);

}


static int ram_load_postcopy(QEMUFile *f)

{

    int flags = 0, ret = 0;

    bool place_needed = false;

    bool matching_page_sizes = qemu_host_page_size == TARGET_PAGE_SIZE;

    MigrationIncomingState *mis = migration_incoming_get_current();

    /* Temporary page that is later 'placed' */

    void *postcopy_host_page = postcopy_get_tmp_page(mis);

    void *last_host = NULL;

    bool all_zero = false;

    while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {

        ram_addr_t addr;

        void *host = NULL;

        void *page_buffer = NULL;

        void *place_source = NULL;

        uint8_t ch;

        addr = qemu_get_be64(f);

        flags = addr & ~TARGET_PAGE_MASK;

        addr &= TARGET_PAGE_MASK;

        trace_ram_load_postcopy_loop((uint64_t)addr, flags);

        place_needed = false;

        if (flags & (RAM_SAVE_FLAG_COMPRESS | RAM_SAVE_FLAG_PAGE)) {

            host = host_from_stream_offset(f, addr, flags);

            if (!host) {

                error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);

                ret = -EINVAL;

                break;

            }

            page_buffer = host;

            /*

             * Postcopy requires that we place whole host pages atomically.

             * To make it atomic, the data is read into a temporary page

             * that's moved into place later.

             * The migration protocol uses,  possibly smaller, target-pages

             * however the source ensures it always sends all the components

             * of a host page in order.

             */

            page_buffer = postcopy_host_page +

                          ((uintptr_t)host & ~qemu_host_page_mask);

            /* If all TP are zero then we can optimise the place */

            if (!((uintptr_t)host & ~qemu_host_page_mask)) {

                all_zero = true;

            } else {

                /* not the 1st TP within the HP */

                if (host != (last_host + TARGET_PAGE_SIZE)) {

                    error_report("Non-sequential target page %p/%p",

                                  host, last_host);

                    ret = -EINVAL;

                    break;

                }

            }

            /*

             * If it's the last part of a host page then we place the host

             * page

             */

            place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &

                                     ~qemu_host_page_mask) == 0;

            place_source = postcopy_host_page;

        }

        last_host = host;

        switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {

        case RAM_SAVE_FLAG_COMPRESS:

            ch = qemu_get_byte(f);

            memset(page_buffer, ch, TARGET_PAGE_SIZE);

            if (ch) {

                all_zero = false;

            }

            break;

        case RAM_SAVE_FLAG_PAGE:

            all_zero = false;

            if (!place_needed || !matching_page_sizes) {

                qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);

            } else {

                /* Avoids the qemu_file copy during postcopy, which is

                 * going to do a copy later; can only do it when we

                 * do this read in one go (matching page sizes)

                 */

                qemu_get_buffer_in_place(f, (uint8_t **)&place_source,

                                         TARGET_PAGE_SIZE);

            }

            break;

        case RAM_SAVE_FLAG_EOS:

            /* normal exit */

            break;

        default:

            error_report("Unknown combination of migration flags: %#x"

                         " (postcopy mode)", flags);

            ret = -EINVAL;

        }

        if (place_needed) {

            /* This gets called at the last target page in the host page */

            if (all_zero) {

                ret = postcopy_place_page_zero(mis,

                                               host + TARGET_PAGE_SIZE -

                                               qemu_host_page_size);

            } else {

                ret = postcopy_place_page(mis, host + TARGET_PAGE_SIZE -

                                               qemu_host_page_size,

                                               place_source);

            }

        }

        if (!ret) {

            ret = qemu_file_get_error(f);

        }

    }

    return ret;

}


static uint64_t pmsav7_read(CPUARMState *env, const ARMCPRegInfo *ri)

{

    uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);

    if (!u32p) {

        return 0;

    }

    u32p += env->pmsav7.rnr;

    return *u32p;

}


static int gt64120_pci_init(PCIDevice *d)

{

    /* FIXME: Malta specific hw assumptions ahead */

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_MARVELL);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_MARVELL_GT6412X);

    pci_set_word(d->config + PCI_COMMAND, 0);

    pci_set_word(d->config + PCI_STATUS,

                 PCI_STATUS_FAST_BACK | PCI_STATUS_DEVSEL_MEDIUM);

    pci_set_byte(d->config + PCI_CLASS_REVISION, 0x10);

    pci_config_set_prog_interface(d->config, 0);

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_HOST);

    pci_set_long(d->config + PCI_BASE_ADDRESS_0, 0x00000008);

    pci_set_long(d->config + PCI_BASE_ADDRESS_1, 0x01000008);

    pci_set_long(d->config + PCI_BASE_ADDRESS_2, 0x1c000000);

    pci_set_long(d->config + PCI_BASE_ADDRESS_3, 0x1f000000);

    pci_set_long(d->config + PCI_BASE_ADDRESS_4, 0x14000000);

    pci_set_long(d->config + PCI_BASE_ADDRESS_5, 0x14000001);

    pci_set_byte(d->config + 0x3d, 0x01);

    return 0;

}


static int vtd_page_walk(VTDContextEntry *ce, uint64_t start, uint64_t end,

                         vtd_page_walk_hook hook_fn, void *private,

                         bool notify_unmap)

{

    dma_addr_t addr = vtd_ce_get_slpt_base(ce);

    uint32_t level = vtd_ce_get_level(ce);

    if (!vtd_iova_range_check(start, ce)) {

        return -VTD_FR_ADDR_BEYOND_MGAW;

    }

    if (!vtd_iova_range_check(end, ce)) {

        /* Fix end so that it reaches the maximum */

        end = vtd_iova_limit(ce);

    }

    return vtd_page_walk_level(addr, start, end, hook_fn, private,

                               level, true, true, notify_unmap);

}


static int omx_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                            const AVFrame *frame, int *got_packet)

{

    OMXCodecContext *s = avctx->priv_data;

    int ret = 0;

    OMX_BUFFERHEADERTYPE* buffer;

    OMX_ERRORTYPE err;

    if (frame) {

        uint8_t *dst[4];

        int linesize[4];

        int need_copy;

        buffer = get_buffer(&s->input_mutex, &s->input_cond,

                            &s->num_free_in_buffers, s->free_in_buffers, 1);

        buffer->nFilledLen = av_image_fill_arrays(dst, linesize, buffer->pBuffer, avctx->pix_fmt, s->stride, s->plane_size, 1);

        if (s->input_zerocopy) {

            uint8_t *src[4] = { NULL };

            int src_linesize[4];

            av_image_fill_arrays(src, src_linesize, frame->data[0], avctx->pix_fmt, s->stride, s->plane_size, 1);

            if (frame->linesize[0] == src_linesize[0] &&

                frame->linesize[1] == src_linesize[1] &&

                frame->linesize[2] == src_linesize[2] &&

                frame->data[1] == src[1] &&

                frame->data[2] == src[2]) {

                // If the input frame happens to have all planes stored contiguously,

                // with the right strides, just clone the frame and set the OMX

                // buffer header to point to it

                AVFrame *local = av_frame_clone(frame);

                if (!local) {

                    // Return the buffer to the queue so it's not lost

                    append_buffer(&s->input_mutex, &s->input_cond, &s->num_free_in_buffers, s->free_in_buffers, buffer);

                    return AVERROR(ENOMEM);

                } else {

                    buffer->pAppPrivate = local;

                    buffer->pOutputPortPrivate = NULL;

                    buffer->pBuffer = local->data[0];

                    need_copy = 0;

                }

            } else {

                // If not, we need to allocate a new buffer with the right

                // size and copy the input frame into it.

                uint8_t *buf = av_malloc(av_image_get_buffer_size(avctx->pix_fmt, s->stride, s->plane_size, 1));

                if (!buf) {

                    // Return the buffer to the queue so it's not lost

                    append_buffer(&s->input_mutex, &s->input_cond, &s->num_free_in_buffers, s->free_in_buffers, buffer);

                    return AVERROR(ENOMEM);

                } else {

                    buffer->pAppPrivate = buf;

                    // Mark that pAppPrivate is an av_malloc'ed buffer, not an AVFrame

                    buffer->pOutputPortPrivate = (void*) 1;

                    buffer->pBuffer = buf;

                    need_copy = 1;

                    buffer->nFilledLen = av_image_fill_arrays(dst, linesize, buffer->pBuffer, avctx->pix_fmt, s->stride, s->plane_size, 1);

                }

            }

        } else {

            need_copy = 1;

        }

        if (need_copy)

            av_image_copy(dst, linesize, (const uint8_t**) frame->data, frame->linesize, avctx->pix_fmt, avctx->width, avctx->height);

        buffer->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;

        buffer->nOffset = 0;

        // Convert the timestamps to microseconds; some encoders can ignore

        // the framerate and do VFR bit allocation based on timestamps.

        buffer->nTimeStamp = to_omx_ticks(av_rescale_q(frame->pts, avctx->time_base, AV_TIME_BASE_Q));

        err = OMX_EmptyThisBuffer(s->handle, buffer);

        if (err != OMX_ErrorNone) {

            append_buffer(&s->input_mutex, &s->input_cond, &s->num_free_in_buffers, s->free_in_buffers, buffer);

            av_log(avctx, AV_LOG_ERROR, "OMX_EmptyThisBuffer failed: %x\n", err);

            return AVERROR_UNKNOWN;

        }

        s->num_in_frames++;

    }

    while (!*got_packet && ret == 0) {

        // Only wait for output if flushing and not all frames have been output

        buffer = get_buffer(&s->output_mutex, &s->output_cond,

                            &s->num_done_out_buffers, s->done_out_buffers,

                            !frame && s->num_out_frames < s->num_in_frames);

        if (!buffer)

            break;

        if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG && avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {

            if ((ret = av_reallocp(&avctx->extradata, avctx->extradata_size + buffer->nFilledLen + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {

                avctx->extradata_size = 0;

                goto end;

            }

            memcpy(avctx->extradata + avctx->extradata_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);

            avctx->extradata_size += buffer->nFilledLen;

            memset(avctx->extradata + avctx->extradata_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);

        } else {

            if (buffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME)

                s->num_out_frames++;

            if (!(buffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) || !pkt->data) {

                // If the output packet isn't preallocated, just concatenate everything in our

                // own buffer

                int newsize = s->output_buf_size + buffer->nFilledLen + AV_INPUT_BUFFER_PADDING_SIZE;

                if ((ret = av_reallocp(&s->output_buf, newsize)) < 0) {

                    s->output_buf_size = 0;

                    goto end;

                }

                memcpy(s->output_buf + s->output_buf_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);

                s->output_buf_size += buffer->nFilledLen;

                if (buffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) {

                    if ((ret = av_packet_from_data(pkt, s->output_buf, s->output_buf_size)) < 0) {

                        av_freep(&s->output_buf);

                        s->output_buf_size = 0;

                        goto end;

                    }

                    s->output_buf = NULL;

                    s->output_buf_size = 0;

                }

            } else {

                // End of frame, and the caller provided a preallocated frame

                if ((ret = ff_alloc_packet2(avctx, pkt, s->output_buf_size + buffer->nFilledLen, 0)) < 0) {

                    av_log(avctx, AV_LOG_ERROR, "Error getting output packet of size %d.\n",

                           (int)(s->output_buf_size + buffer->nFilledLen));

                    goto end;

                }

                memcpy(pkt->data, s->output_buf, s->output_buf_size);

                memcpy(pkt->data + s->output_buf_size, buffer->pBuffer + buffer->nOffset, buffer->nFilledLen);

                av_freep(&s->output_buf);

                s->output_buf_size = 0;

            }

            if (buffer->nFlags & OMX_BUFFERFLAG_ENDOFFRAME) {

                pkt->pts = av_rescale_q(from_omx_ticks(buffer->nTimeStamp), AV_TIME_BASE_Q, avctx->time_base);

                // We don't currently enable B-frames for the encoders, so set

                // pkt->dts = pkt->pts. (The calling code behaves worse if the encoder

                // doesn't set the dts).

                pkt->dts = pkt->pts;

                if (buffer->nFlags & OMX_BUFFERFLAG_SYNCFRAME)

                    pkt->flags |= AV_PKT_FLAG_KEY;

                *got_packet = 1;

            }

        }

end:

        err = OMX_FillThisBuffer(s->handle, buffer);

        if (err != OMX_ErrorNone) {

            append_buffer(&s->output_mutex, &s->output_cond, &s->num_done_out_buffers, s->done_out_buffers, buffer);

            av_log(avctx, AV_LOG_ERROR, "OMX_FillThisBuffer failed: %x\n", err);

            ret = AVERROR_UNKNOWN;

        }

    }

    return ret;

}


void kvm_arm_reset_vcpu(ARMCPU *cpu)

{

    /* Feed the kernel back its initial register state */

    memmove(cpu->cpreg_values, cpu->cpreg_reset_values,

            cpu->cpreg_array_len * sizeof(cpu->cpreg_values[0]));

    if (!write_list_to_kvmstate(cpu)) {

        abort();

    }

}


static void vmsvga_update_display(void *opaque)

{

    struct vmsvga_state_s *s = opaque;

    DisplaySurface *surface;

    bool dirty = false;

    if (!s->enable) {

        s->vga.hw_ops->gfx_update(&s->vga);

        return;

    }

    vmsvga_check_size(s);

    surface = qemu_console_surface(s->vga.con);

    vmsvga_fifo_run(s);

    vmsvga_update_rect_flush(s);

    /*

     * Is it more efficient to look at vram VGA-dirty bits or wait

     * for the driver to issue SVGA_CMD_UPDATE?

     */

    if (memory_region_is_logging(&s->vga.vram)) {

        vga_sync_dirty_bitmap(&s->vga);

        dirty = memory_region_get_dirty(&s->vga.vram, 0,

            surface_stride(surface) * surface_height(surface),

            DIRTY_MEMORY_VGA);

    }

    if (s->invalidated || dirty) {

        s->invalidated = 0;

        dpy_gfx_update(s->vga.con, 0, 0,

                   surface_width(surface), surface_height(surface));

    }

    if (dirty) {

        memory_region_reset_dirty(&s->vga.vram, 0,

            surface_stride(surface) * surface_height(surface),

            DIRTY_MEMORY_VGA);

    }

}


static void bdrv_io_limits_intercept(BlockDriverState *bs,

                                     int nb_sectors,

                                     bool is_write)

{

    /* does this io must wait */

    bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);

    /* if must wait or any request of this type throttled queue the IO */

    if (must_wait ||

        !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {

        qemu_co_queue_wait(&bs->throttled_reqs[is_write]);

    }

    /* the IO will be executed, do the accounting */

    throttle_account(&bs->throttle_state,

                     is_write,

                     nb_sectors * BDRV_SECTOR_SIZE);

    /* if the next request must wait -> do nothing */

    if (throttle_schedule_timer(&bs->throttle_state, is_write)) {

        return;

    }

    /* else queue next request for execution */

    qemu_co_queue_next(&bs->throttled_reqs[is_write]);

}


static void ide_cfata_identify(IDEState *s)

{

    uint16_t *p;

    uint32_t cur_sec;

    p = (uint16_t *) s->identify_data;

    if (s->identify_set)

        goto fill_buffer;

    memset(p, 0, sizeof(s->identify_data));

    cur_sec = s->cylinders * s->heads * s->sectors;

    put_le16(p + 0, 0x848a);			/* CF Storage Card signature */

    put_le16(p + 1, s->cylinders);		/* Default cylinders */

    put_le16(p + 3, s->heads);			/* Default heads */

    put_le16(p + 6, s->sectors);		/* Default sectors per track */

    put_le16(p + 7, s->nb_sectors >> 16);	/* Sectors per card */

    put_le16(p + 8, s->nb_sectors);		/* Sectors per card */

    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */

    put_le16(p + 22, 0x0004);			/* ECC bytes */

    padstr((char *) (p + 23), s->version, 8);	/* Firmware Revision */

    padstr((char *) (p + 27), "QEMU MICRODRIVE", 40);/* Model number */

#if MAX_MULT_SECTORS > 1

    put_le16(p + 47, 0x8000 | MAX_MULT_SECTORS);

#else

    put_le16(p + 47, 0x0000);

#endif

    put_le16(p + 49, 0x0f00);			/* Capabilities */

    put_le16(p + 51, 0x0002);			/* PIO cycle timing mode */

    put_le16(p + 52, 0x0001);			/* DMA cycle timing mode */

    put_le16(p + 53, 0x0003);			/* Translation params valid */

    put_le16(p + 54, s->cylinders);		/* Current cylinders */

    put_le16(p + 55, s->heads);			/* Current heads */

    put_le16(p + 56, s->sectors);		/* Current sectors */

    put_le16(p + 57, cur_sec);			/* Current capacity */

    put_le16(p + 58, cur_sec >> 16);		/* Current capacity */

    if (s->mult_sectors)			/* Multiple sector setting */

        put_le16(p + 59, 0x100 | s->mult_sectors);

    put_le16(p + 60, s->nb_sectors);		/* Total LBA sectors */

    put_le16(p + 61, s->nb_sectors >> 16);	/* Total LBA sectors */

    put_le16(p + 63, 0x0203);			/* Multiword DMA capability */

    put_le16(p + 64, 0x0001);			/* Flow Control PIO support */

    put_le16(p + 65, 0x0096);			/* Min. Multiword DMA cycle */

    put_le16(p + 66, 0x0096);			/* Rec. Multiword DMA cycle */

    put_le16(p + 68, 0x00b4);			/* Min. PIO cycle time */

    put_le16(p + 82, 0x400c);			/* Command Set supported */

    put_le16(p + 83, 0x7068);			/* Command Set supported */

    put_le16(p + 84, 0x4000);			/* Features supported */

    put_le16(p + 85, 0x000c);			/* Command Set enabled */

    put_le16(p + 86, 0x7044);			/* Command Set enabled */

    put_le16(p + 87, 0x4000);			/* Features enabled */

    put_le16(p + 91, 0x4060);			/* Current APM level */

    put_le16(p + 129, 0x0002);			/* Current features option */

    put_le16(p + 130, 0x0005);			/* Reassigned sectors */

    put_le16(p + 131, 0x0001);			/* Initial power mode */

    put_le16(p + 132, 0x0000);			/* User signature */

    put_le16(p + 160, 0x8100);			/* Power requirement */

    put_le16(p + 161, 0x8001);			/* CF command set */

    s->identify_set = 1;

fill_buffer:

    memcpy(s->io_buffer, p, sizeof(s->identify_data));

}


static void test_qga_file_ops(gconstpointer fix)

{

    const TestFixture *fixture = fix;

    const unsigned char helloworld[] = "Hello World!\n";

    const char *b64;

    gchar *cmd, *path, *enc;

    unsigned char *dec;

    QDict *ret, *val;

    int64_t id, eof;

    gsize count;

    FILE *f;

    char tmp[100];

    /* open */

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-file-open',"

                 " 'arguments': { 'path': 'foo', 'mode': 'w+' } }");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    id = qdict_get_int(ret, "return");

    QDECREF(ret);

    enc = g_base64_encode(helloworld, sizeof(helloworld));

    /* write */

    cmd = g_strdup_printf("{'execute': 'guest-file-write',"

                          " 'arguments': { 'handle': %" PRId64 ","

                          " 'buf-b64': '%s' } }", id, enc);

    ret = qmp_fd(fixture->fd, cmd);

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    g_assert_cmpint(count, ==, sizeof(helloworld));

    g_assert_cmpint(eof, ==, 0);

    QDECREF(ret);

    g_free(cmd);

    /* flush */

    cmd = g_strdup_printf("{'execute': 'guest-file-flush',"

                          " 'arguments': {'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    QDECREF(ret);

    g_free(cmd);

    /* close */

    cmd = g_strdup_printf("{'execute': 'guest-file-close',"

                          " 'arguments': {'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    QDECREF(ret);

    g_free(cmd);

    /* check content */

    path = g_build_filename(fixture->test_dir, "foo", NULL);

    f = fopen(path, "r");

    g_assert_nonnull(f);

    count = fread(tmp, 1, sizeof(tmp), f);

    g_assert_cmpint(count, ==, sizeof(helloworld));

    tmp[count] = 0;

    g_assert_cmpstr(tmp, ==, (char *)helloworld);

    fclose(f);

    /* open */

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-file-open',"

                 " 'arguments': { 'path': 'foo', 'mode': 'r' } }");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    id = qdict_get_int(ret, "return");

    QDECREF(ret);

    /* read */

    cmd = g_strdup_printf("{'execute': 'guest-file-read',"

                          " 'arguments': { 'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    b64 = qdict_get_str(val, "buf-b64");

    g_assert_cmpint(count, ==, sizeof(helloworld));

    g_assert(eof);

    g_assert_cmpstr(b64, ==, enc);

    QDECREF(ret);

    g_free(cmd);

    g_free(enc);

    /* read eof */

    cmd = g_strdup_printf("{'execute': 'guest-file-read',"

                          " 'arguments': { 'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    b64 = qdict_get_str(val, "buf-b64");

    g_assert_cmpint(count, ==, 0);

    g_assert(eof);

    g_assert_cmpstr(b64, ==, "");

    QDECREF(ret);

    g_free(cmd);

    /* seek */

    cmd = g_strdup_printf("{'execute': 'guest-file-seek',"

                          " 'arguments': { 'handle': %" PRId64 ", "

                          " 'offset': %d, 'whence': %d } }",

                          id, 6, SEEK_SET);

    ret = qmp_fd(fixture->fd, cmd);

    qmp_assert_no_error(ret);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "position");

    eof = qdict_get_bool(val, "eof");

    g_assert_cmpint(count, ==, 6);

    g_assert(!eof);

    QDECREF(ret);

    g_free(cmd);

    /* partial read */

    cmd = g_strdup_printf("{'execute': 'guest-file-read',"

                          " 'arguments': { 'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    b64 = qdict_get_str(val, "buf-b64");

    g_assert_cmpint(count, ==, sizeof(helloworld) - 6);

    g_assert(eof);

    dec = g_base64_decode(b64, &count);

    g_assert_cmpint(count, ==, sizeof(helloworld) - 6);

    g_assert_cmpmem(dec, count, helloworld + 6, sizeof(helloworld) - 6);

    g_free(dec);

    QDECREF(ret);

    g_free(cmd);

    /* close */

    cmd = g_strdup_printf("{'execute': 'guest-file-close',"

                          " 'arguments': {'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    QDECREF(ret);

    g_free(cmd);

}


static inline uint64_t tcg_opc_movi_a(int qp, TCGReg dst, int64_t src)

{

    assert(src == sextract64(src, 0, 22));

    return tcg_opc_a5(qp, OPC_ADDL_A5, dst, src, TCG_REG_R0);

}


bool qemu_clock_run_timers(QEMUClockType type)

{

    return timerlist_run_timers(main_loop_tlg.tl[type]);

}


static int net_slirp_init(VLANState *vlan, const char *model, const char *name)

{

    if (!slirp_inited) {

        slirp_inited = 1;

        slirp_init(slirp_restrict, slirp_ip);

    }

    slirp_vc = qemu_new_vlan_client(vlan, model, name,

                                    slirp_receive, NULL, NULL, NULL);

    slirp_vc->info_str[0] = '\0';

    return 0;

}


static int assigned_device_pci_cap_init(PCIDevice *pci_dev, Error **errp)

{

    AssignedDevice *dev = PCI_ASSIGN(pci_dev);

    PCIRegion *pci_region = dev->real_device.regions;

    int ret, pos;

    /* Clear initial capabilities pointer and status copied from hw */

    pci_set_byte(pci_dev->config + PCI_CAPABILITY_LIST, 0);

    pci_set_word(pci_dev->config + PCI_STATUS,

                 pci_get_word(pci_dev->config + PCI_STATUS) &

                 ~PCI_STATUS_CAP_LIST);

    /* Expose MSI capability

     * MSI capability is the 1st capability in capability config */

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSI, 0);

    if (pos != 0 && kvm_check_extension(kvm_state, KVM_CAP_ASSIGN_DEV_IRQ)) {

        if (verify_irqchip_in_kernel(errp) < 0) {

            return -ENOTSUP;

        }

        dev->dev.cap_present |= QEMU_PCI_CAP_MSI;

        dev->cap.available |= ASSIGNED_DEVICE_CAP_MSI;

        /* Only 32-bit/no-mask currently supported */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSI, pos, 10,

                                  errp);

        if (ret < 0) {

            return ret;

        }

        pci_dev->msi_cap = pos;

        pci_set_word(pci_dev->config + pos + PCI_MSI_FLAGS,

                     pci_get_word(pci_dev->config + pos + PCI_MSI_FLAGS) &

                     PCI_MSI_FLAGS_QMASK);

        pci_set_long(pci_dev->config + pos + PCI_MSI_ADDRESS_LO, 0);

        pci_set_word(pci_dev->config + pos + PCI_MSI_DATA_32, 0);

        /* Set writable fields */

        pci_set_word(pci_dev->wmask + pos + PCI_MSI_FLAGS,

                     PCI_MSI_FLAGS_QSIZE | PCI_MSI_FLAGS_ENABLE);

        pci_set_long(pci_dev->wmask + pos + PCI_MSI_ADDRESS_LO, 0xfffffffc);

        pci_set_word(pci_dev->wmask + pos + PCI_MSI_DATA_32, 0xffff);

    }

    /* Expose MSI-X capability */

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_MSIX, 0);

    if (pos != 0 && kvm_device_msix_supported(kvm_state)) {

        int bar_nr;

        uint32_t msix_table_entry;

        uint16_t msix_max;

        if (verify_irqchip_in_kernel(errp) < 0) {

            return -ENOTSUP;

        }

        dev->dev.cap_present |= QEMU_PCI_CAP_MSIX;

        dev->cap.available |= ASSIGNED_DEVICE_CAP_MSIX;

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_MSIX, pos, 12,

                                  errp);

        if (ret < 0) {

            return ret;

        }

        pci_dev->msix_cap = pos;

        msix_max = (pci_get_word(pci_dev->config + pos + PCI_MSIX_FLAGS) &

                    PCI_MSIX_FLAGS_QSIZE) + 1;

        msix_max = MIN(msix_max, KVM_MAX_MSIX_PER_DEV);

        pci_set_word(pci_dev->config + pos + PCI_MSIX_FLAGS, msix_max - 1);

        /* Only enable and function mask bits are writable */

        pci_set_word(pci_dev->wmask + pos + PCI_MSIX_FLAGS,

                     PCI_MSIX_FLAGS_ENABLE | PCI_MSIX_FLAGS_MASKALL);

        msix_table_entry = pci_get_long(pci_dev->config + pos + PCI_MSIX_TABLE);

        bar_nr = msix_table_entry & PCI_MSIX_FLAGS_BIRMASK;

        msix_table_entry &= ~PCI_MSIX_FLAGS_BIRMASK;

        dev->msix_table_addr = pci_region[bar_nr].base_addr + msix_table_entry;

        dev->msix_table_size = msix_max * sizeof(MSIXTableEntry);

        dev->msix_max = msix_max;

    }

    /* Minimal PM support, nothing writable, device appears to NAK changes */

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PM, 0);

    if (pos) {

        uint16_t pmc;

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, pos, PCI_PM_SIZEOF,

                                  errp);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, PCI_PM_SIZEOF);

        pmc = pci_get_word(pci_dev->config + pos + PCI_CAP_FLAGS);

        pmc &= (PCI_PM_CAP_VER_MASK | PCI_PM_CAP_DSI);

        pci_set_word(pci_dev->config + pos + PCI_CAP_FLAGS, pmc);

        /* assign_device will bring the device up to D0, so we don't need

         * to worry about doing that ourselves here. */

        pci_set_word(pci_dev->config + pos + PCI_PM_CTRL,

                     PCI_PM_CTRL_NO_SOFT_RESET);

        pci_set_byte(pci_dev->config + pos + PCI_PM_PPB_EXTENSIONS, 0);

        pci_set_byte(pci_dev->config + pos + PCI_PM_DATA_REGISTER, 0);

    }

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_EXP, 0);

    if (pos) {

        uint8_t version, size = 0;

        uint16_t type, devctl, lnksta;

        uint32_t devcap, lnkcap;

        version = pci_get_byte(pci_dev->config + pos + PCI_EXP_FLAGS);

        version &= PCI_EXP_FLAGS_VERS;

        if (version == 1) {

            size = 0x14;

        } else if (version == 2) {

            /*

             * Check for non-std size, accept reduced size to 0x34,

             * which is what bcm5761 implemented, violating the

             * PCIe v3.0 spec that regs should exist and be read as 0,

             * not optionally provided and shorten the struct size.

             */

            size = MIN(0x3c, PCI_CONFIG_SPACE_SIZE - pos);

            if (size < 0x34) {

                error_setg(errp, "Invalid size PCIe cap-id 0x%x",

                           PCI_CAP_ID_EXP);

                return -EINVAL;

            } else if (size != 0x3c) {

                error_report("WARNING, %s: PCIe cap-id 0x%x has "

                             "non-standard size 0x%x; std size should be 0x3c",

                             __func__, PCI_CAP_ID_EXP, size);

            }

        } else if (version == 0) {

            uint16_t vid, did;

            vid = pci_get_word(pci_dev->config + PCI_VENDOR_ID);

            did = pci_get_word(pci_dev->config + PCI_DEVICE_ID);

            if (vid == PCI_VENDOR_ID_INTEL && did == 0x10ed) {

                /*

                 * quirk for Intel 82599 VF with invalid PCIe capability

                 * version, should really be version 2 (same as PF)

                 */

                size = 0x3c;

            }

        }

        if (size == 0) {

            error_setg(errp, "Unsupported PCI express capability version %d",

                       version);

            return -EINVAL;

        }

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_EXP, pos, size,

                                  errp);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, size);

        type = pci_get_word(pci_dev->config + pos + PCI_EXP_FLAGS);

        type = (type & PCI_EXP_FLAGS_TYPE) >> 4;

        if (type != PCI_EXP_TYPE_ENDPOINT &&

            type != PCI_EXP_TYPE_LEG_END && type != PCI_EXP_TYPE_RC_END) {

            error_setg(errp, "Device assignment only supports endpoint "

                       "assignment, device type %d", type);

            return -EINVAL;

        }

        /* capabilities, pass existing read-only copy

         * PCI_EXP_FLAGS_IRQ: updated by hardware, should be direct read */

        /* device capabilities: hide FLR */

        devcap = pci_get_long(pci_dev->config + pos + PCI_EXP_DEVCAP);

        devcap &= ~PCI_EXP_DEVCAP_FLR;

        pci_set_long(pci_dev->config + pos + PCI_EXP_DEVCAP, devcap);

        /* device control: clear all error reporting enable bits, leaving

         *                 only a few host values.  Note, these are

         *                 all writable, but not passed to hw.

         */

        devctl = pci_get_word(pci_dev->config + pos + PCI_EXP_DEVCTL);

        devctl = (devctl & (PCI_EXP_DEVCTL_READRQ | PCI_EXP_DEVCTL_PAYLOAD)) |

                  PCI_EXP_DEVCTL_RELAX_EN | PCI_EXP_DEVCTL_NOSNOOP_EN;

        pci_set_word(pci_dev->config + pos + PCI_EXP_DEVCTL, devctl);

        devctl = PCI_EXP_DEVCTL_BCR_FLR | PCI_EXP_DEVCTL_AUX_PME;

        pci_set_word(pci_dev->wmask + pos + PCI_EXP_DEVCTL, ~devctl);

        /* Clear device status */

        pci_set_word(pci_dev->config + pos + PCI_EXP_DEVSTA, 0);

        /* Link capabilities, expose links and latencues, clear reporting */

        lnkcap = pci_get_long(pci_dev->config + pos + PCI_EXP_LNKCAP);

        lnkcap &= (PCI_EXP_LNKCAP_SLS | PCI_EXP_LNKCAP_MLW |

                   PCI_EXP_LNKCAP_ASPMS | PCI_EXP_LNKCAP_L0SEL |

                   PCI_EXP_LNKCAP_L1EL);

        pci_set_long(pci_dev->config + pos + PCI_EXP_LNKCAP, lnkcap);

        /* Link control, pass existing read-only copy.  Should be writable? */

        /* Link status, only expose current speed and width */

        lnksta = pci_get_word(pci_dev->config + pos + PCI_EXP_LNKSTA);

        lnksta &= (PCI_EXP_LNKSTA_CLS | PCI_EXP_LNKSTA_NLW);

        pci_set_word(pci_dev->config + pos + PCI_EXP_LNKSTA, lnksta);

        if (version >= 2) {

            /* Slot capabilities, control, status - not needed for endpoints */

            pci_set_long(pci_dev->config + pos + PCI_EXP_SLTCAP, 0);

            pci_set_word(pci_dev->config + pos + PCI_EXP_SLTCTL, 0);

            pci_set_word(pci_dev->config + pos + PCI_EXP_SLTSTA, 0);

            /* Root control, capabilities, status - not needed for endpoints */

            pci_set_word(pci_dev->config + pos + PCI_EXP_RTCTL, 0);

            pci_set_word(pci_dev->config + pos + PCI_EXP_RTCAP, 0);

            pci_set_long(pci_dev->config + pos + PCI_EXP_RTSTA, 0);

            /* Device capabilities/control 2, pass existing read-only copy */

            /* Link control 2, pass existing read-only copy */

        }

    }

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_PCIX, 0);

    if (pos) {

        uint16_t cmd;

        uint32_t status;

        /* Only expose the minimum, 8 byte capability */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_PCIX, pos, 8,

                                  errp);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, 8);

        /* Command register, clear upper bits, including extended modes */

        cmd = pci_get_word(pci_dev->config + pos + PCI_X_CMD);

        cmd &= (PCI_X_CMD_DPERR_E | PCI_X_CMD_ERO | PCI_X_CMD_MAX_READ |

                PCI_X_CMD_MAX_SPLIT);

        pci_set_word(pci_dev->config + pos + PCI_X_CMD, cmd);

        /* Status register, update with emulated PCI bus location, clear

         * error bits, leave the rest. */

        status = pci_get_long(pci_dev->config + pos + PCI_X_STATUS);

        status &= ~(PCI_X_STATUS_BUS | PCI_X_STATUS_DEVFN);

        status |= pci_get_bdf(pci_dev);

        status &= ~(PCI_X_STATUS_SPL_DISC | PCI_X_STATUS_UNX_SPL |

                    PCI_X_STATUS_SPL_ERR);

        pci_set_long(pci_dev->config + pos + PCI_X_STATUS, status);

    }

    pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VPD, 0);

    if (pos) {

        /* Direct R/W passthrough */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_VPD, pos, 8,

                                  errp);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, 8);

        /* direct write for cap content */

        assigned_dev_direct_config_write(dev, pos + 2, 6);

    }

    /* Devices can have multiple vendor capabilities, get them all */

    for (pos = 0; (pos = pci_find_cap_offset(pci_dev, PCI_CAP_ID_VNDR, pos));

        pos += PCI_CAP_LIST_NEXT) {

        uint8_t len = pci_get_byte(pci_dev->config + pos + PCI_CAP_FLAGS);

        /* Direct R/W passthrough */

        ret = pci_add_capability(pci_dev, PCI_CAP_ID_VNDR, pos, len,

                                  errp);

        if (ret < 0) {

            return ret;

        }

        assigned_dev_setup_cap_read(dev, pos, len);

        /* direct write for cap content */

        assigned_dev_direct_config_write(dev, pos + 2, len - 2);

    }

    /* If real and virtual capability list status bits differ, virtualize the

     * access. */

    if ((pci_get_word(pci_dev->config + PCI_STATUS) & PCI_STATUS_CAP_LIST) !=

        (assigned_dev_pci_read_byte(pci_dev, PCI_STATUS) &

         PCI_STATUS_CAP_LIST)) {

        dev->emulate_config_read[PCI_STATUS] |= PCI_STATUS_CAP_LIST;

    }

    return 0;

}


static inline void gen_intermediate_code_internal(UniCore32CPU *cpu,

        TranslationBlock *tb, bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUUniCore32State *env = &cpu->env;

    DisasContext dc1, *dc = &dc1;

    CPUBreakpoint *bp;

    uint16_t *gen_opc_end;

    int j, lj;

    target_ulong pc_start;

    uint32_t next_page_start;

    int num_insns;

    int max_insns;

    /* generate intermediate code */

    num_temps = 0;

    pc_start = tb->pc;

    dc->tb = tb;

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    dc->is_jmp = DISAS_NEXT;

    dc->pc = pc_start;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->condjmp = 0;

    cpu_F0s = tcg_temp_new_i32();

    cpu_F1s = tcg_temp_new_i32();

    cpu_F0d = tcg_temp_new_i64();

    cpu_F1d = tcg_temp_new_i64();

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    lj = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

#ifndef CONFIG_USER_ONLY

    if ((env->uncached_asr & ASR_M) == ASR_MODE_USER) {

        dc->user = 1;

    } else {

        dc->user = 0;

    }

#endif

    gen_tb_start();

    do {

        if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) {

            QTAILQ_FOREACH(bp, &cs->breakpoints, entry) {

                if (bp->pc == dc->pc) {

                    gen_set_pc_im(dc->pc);

                    gen_exception(EXCP_DEBUG);

                    dc->is_jmp = DISAS_JUMP;

                    /* Advance PC so that clearing the breakpoint will

                       invalidate this TB.  */

                    dc->pc += 2; /* FIXME */

                    goto done_generating;

                }

            }

        }

        if (search_pc) {

            j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j) {

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

                }

            }

            tcg_ctx.gen_opc_pc[lj] = dc->pc;

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = num_insns;

        }

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        disas_uc32_insn(env, dc);

        if (num_temps) {

            fprintf(stderr, "Internal resource leak before %08x\n", dc->pc);

            num_temps = 0;

        }

        if (dc->condjmp && !dc->is_jmp) {

            gen_set_label(dc->condlabel);

            dc->condjmp = 0;

        }

        /* Translation stops when a conditional branch is encountered.

         * Otherwise the subsequent code could get translated several times.

         * Also stop translation when a page boundary is reached.  This

         * ensures prefetch aborts occur at the right place.  */

        num_insns++;

    } while (!dc->is_jmp && tcg_ctx.gen_opc_ptr < gen_opc_end &&

             !cs->singlestep_enabled &&

             !singlestep &&

             dc->pc < next_page_start &&

             num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        if (dc->condjmp) {

            /* FIXME:  This can theoretically happen with self-modifying

               code.  */

            cpu_abort(cs, "IO on conditional branch instruction");

        }

        gen_io_end();

    }

    /* At this stage dc->condjmp will only be set when the skipped

       instruction was a conditional branch or trap, and the PC has

       already been written.  */

    if (unlikely(cs->singlestep_enabled)) {

        /* Make sure the pc is updated, and raise a debug exception.  */

        if (dc->condjmp) {

            if (dc->is_jmp == DISAS_SYSCALL) {

                gen_exception(UC32_EXCP_PRIV);

            } else {

                gen_exception(EXCP_DEBUG);

            }

            gen_set_label(dc->condlabel);

        }

        if (dc->condjmp || !dc->is_jmp) {

            gen_set_pc_im(dc->pc);

            dc->condjmp = 0;

        }

        if (dc->is_jmp == DISAS_SYSCALL && !dc->condjmp) {

            gen_exception(UC32_EXCP_PRIV);

        } else {

            gen_exception(EXCP_DEBUG);

        }

    } else {

        /* While branches must always occur at the end of an IT block,

           there are a few other things that can cause us to terminate

           the TB in the middel of an IT block:

            - Exception generating instructions (bkpt, swi, undefined).

            - Page boundaries.

            - Hardware watchpoints.

           Hardware breakpoints have already been handled and skip this code.

         */

        switch (dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, dc->pc);

            break;

        default:

        case DISAS_JUMP:

        case DISAS_UPDATE:

            /* indicate that the hash table must be used to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        case DISAS_SYSCALL:

            gen_exception(UC32_EXCP_PRIV);

            break;

        }

        if (dc->condjmp) {

            gen_set_label(dc->condlabel);

            gen_goto_tb(dc, 1, dc->pc);

            dc->condjmp = 0;

        }

    }

done_generating:

    gen_tb_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("----------------\n");

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(env, pc_start, dc->pc - pc_start, 0);

        qemu_log("\n");

    }

#endif

    if (search_pc) {

        j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        lj++;

        while (lj <= j) {

            tcg_ctx.gen_opc_instr_start[lj++] = 0;

        }

    } else {

        tb->size = dc->pc - pc_start;

        tb->icount = num_insns;

    }

}


static int commit_bitstream_and_slice_buffer(AVCodecContext *avctx,

                                             DECODER_BUFFER_DESC *bs,

                                             DECODER_BUFFER_DESC *sc)

{

    const struct MpegEncContext *s = avctx->priv_data;

    AVDXVAContext *ctx = avctx->hwaccel_context;

    struct dxva2_picture_context *ctx_pic =

        s->current_picture_ptr->hwaccel_picture_private;

    const int is_field = s->picture_structure != PICT_FRAME;

    const unsigned mb_count = s->mb_width * (s->mb_height >> is_field);

    void     *dxva_data_ptr;

    uint8_t  *dxva_data, *current, *end;

    unsigned dxva_size;

    unsigned i;

    unsigned type;

#if CONFIG_D3D11VA

    if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD) {

        type = D3D11_VIDEO_DECODER_BUFFER_BITSTREAM;

        if (FAILED(ID3D11VideoContext_GetDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context,

                                                       D3D11VA_CONTEXT(ctx)->decoder,

                                                       type,

                                                       &dxva_size, &dxva_data_ptr)))

            return -1;

    }

#endif

#if CONFIG_DXVA2

    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {

        type = DXVA2_BitStreamDateBufferType;

        if (FAILED(IDirectXVideoDecoder_GetBuffer(DXVA2_CONTEXT(ctx)->decoder,

                                                  type,

                                                  &dxva_data_ptr, &dxva_size)))

            return -1;

    }

#endif

    dxva_data = dxva_data_ptr;

    current = dxva_data;

    end = dxva_data + dxva_size;

    for (i = 0; i < ctx_pic->slice_count; i++) {

        DXVA_SliceInfo *slice = &ctx_pic->slice[i];

        unsigned position = slice->dwSliceDataLocation;

        unsigned size     = slice->dwSliceBitsInBuffer / 8;

        if (size > end - current) {

            av_log(avctx, AV_LOG_ERROR, "Failed to build bitstream");

            break;

        }

        slice->dwSliceDataLocation = current - dxva_data;

        if (i < ctx_pic->slice_count - 1)

            slice->wNumberMBsInSlice =

                slice[1].wNumberMBsInSlice - slice[0].wNumberMBsInSlice;

        else

            slice->wNumberMBsInSlice =

                mb_count - slice[0].wNumberMBsInSlice;

        memcpy(current, &ctx_pic->bitstream[position], size);

        current += size;

    }

#if CONFIG_D3D11VA

    if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD)

        if (FAILED(ID3D11VideoContext_ReleaseDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder, type)))

            return -1;

#endif

#if CONFIG_DXVA2

    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)

        if (FAILED(IDirectXVideoDecoder_ReleaseBuffer(DXVA2_CONTEXT(ctx)->decoder, type)))

            return -1;

#endif

    if (i < ctx_pic->slice_count)

        return -1;

#if CONFIG_D3D11VA

    if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD) {

        D3D11_VIDEO_DECODER_BUFFER_DESC *dsc11 = bs;

        memset(dsc11, 0, sizeof(*dsc11));

        dsc11->BufferType           = type;

        dsc11->DataSize             = current - dxva_data;

        dsc11->NumMBsInBuffer       = mb_count;

        type = D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL;

    }

#endif

#if CONFIG_DXVA2

    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {

        DXVA2_DecodeBufferDesc *dsc2 = bs;

        memset(dsc2, 0, sizeof(*dsc2));

        dsc2->CompressedBufferType = type;

        dsc2->DataSize             = current - dxva_data;

        dsc2->NumMBsInBuffer       = mb_count;

        type = DXVA2_SliceControlBufferType;

    }

#endif

    return ff_dxva2_commit_buffer(avctx, ctx, sc,

                                  type,

                                  ctx_pic->slice,

                                  ctx_pic->slice_count * sizeof(*ctx_pic->slice),

                                  mb_count);

}


static void piix4_reset(void *opaque)

{

	PIIX4PMState *s = opaque;

	uint8_t *pci_conf = s->dev.config;

	pci_conf[0x58] = 0;

	pci_conf[0x59] = 0;

	pci_conf[0x5a] = 0;

	pci_conf[0x5b] = 0;

}


static void vgafb_write(void *opaque, target_phys_addr_t addr, uint64_t value,

                        unsigned size)

{

    MilkymistVgafbState *s = opaque;

    trace_milkymist_vgafb_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_CTRL:

        s->regs[addr] = value;

        vgafb_resize(s);

        break;

    case R_HSYNC_START:

    case R_HSYNC_END:

    case R_HSCAN:

    case R_VSYNC_START:

    case R_VSYNC_END:

    case R_VSCAN:

    case R_BURST_COUNT:

    case R_DDC:

    case R_SOURCE_CLOCK:

        s->regs[addr] = value;

        break;

    case R_BASEADDRESS:

        if (value & 0x1f) {

            error_report("milkymist_vgafb: framebuffer base address have to "

                     "be 32 byte aligned");

            break;

        }

        s->regs[addr] = value & s->fb_mask;

        s->invalidate = 1;

        break;

    case R_HRES:

    case R_VRES:

        s->regs[addr] = value;

        vgafb_resize(s);

        break;

    case R_BASEADDRESS_ACT:

        error_report("milkymist_vgafb: write to read-only register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    default:

        error_report("milkymist_vgafb: write access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

}


static int get_phys_addr_v5(CPUARMState *env, uint32_t address, int access_type,

                            ARMMMUIdx mmu_idx, hwaddr *phys_ptr,

                            int *prot, target_ulong *page_size)

{

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

    int code;

    uint32_t table;

    uint32_t desc;

    int type;

    int ap;

    int domain = 0;

    int domain_prot;

    hwaddr phys_addr;

    uint32_t dacr;

    /* Pagetable walk.  */

    /* Lookup l1 descriptor.  */

    if (!get_level1_table_address(env, mmu_idx, &table, address)) {

        /* Section translation fault if page walk is disabled by PD0 or PD1 */

        code = 5;

        goto do_fault;

    }

    desc = ldl_phys(cs->as, table);

    type = (desc & 3);

    domain = (desc >> 5) & 0x0f;

    if (regime_el(env, mmu_idx) == 1) {

        dacr = env->cp15.dacr_ns;

    } else {

        dacr = env->cp15.dacr_s;

    }

    domain_prot = (dacr >> (domain * 2)) & 3;

    if (type == 0) {

        /* Section translation fault.  */

        code = 5;

        goto do_fault;

    }

    if (domain_prot == 0 || domain_prot == 2) {

        if (type == 2)

            code = 9; /* Section domain fault.  */

        else

            code = 11; /* Page domain fault.  */

        goto do_fault;

    }

    if (type == 2) {

        /* 1Mb section.  */

        phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);

        ap = (desc >> 10) & 3;

        code = 13;

        *page_size = 1024 * 1024;

    } else {

        /* Lookup l2 entry.  */

        if (type == 1) {

            /* Coarse pagetable.  */

            table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);

        } else {

            /* Fine pagetable.  */

            table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);

        }

        desc = ldl_phys(cs->as, table);

        switch (desc & 3) {

        case 0: /* Page translation fault.  */

            code = 7;

            goto do_fault;

        case 1: /* 64k page.  */

            phys_addr = (desc & 0xffff0000) | (address & 0xffff);

            ap = (desc >> (4 + ((address >> 13) & 6))) & 3;

            *page_size = 0x10000;

            break;

        case 2: /* 4k page.  */

            phys_addr = (desc & 0xfffff000) | (address & 0xfff);

            ap = (desc >> (4 + ((address >> 9) & 6))) & 3;

            *page_size = 0x1000;

            break;

        case 3: /* 1k page.  */

            if (type == 1) {

                if (arm_feature(env, ARM_FEATURE_XSCALE)) {

                    phys_addr = (desc & 0xfffff000) | (address & 0xfff);

                } else {

                    /* Page translation fault.  */

                    code = 7;

                    goto do_fault;

                }

            } else {

                phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);

            }

            ap = (desc >> 4) & 3;

            *page_size = 0x400;

            break;

        default:

            /* Never happens, but compiler isn't smart enough to tell.  */

            abort();

        }

        code = 15;

    }

    *prot = check_ap(env, mmu_idx, ap, domain_prot, access_type);

    if (!*prot) {

        /* Access permission fault.  */

        goto do_fault;

    }

    *prot |= PAGE_EXEC;

    *phys_ptr = phys_addr;

    return 0;

do_fault:

    return code | (domain << 4);

}


static void qjson_initfn(Object *obj)

{

    QJSON *json = QJSON(obj);

    json->str = qstring_from_str("{ ");

    json->omit_comma = true;

}


cac_applet_pki_reset(VCard *card, int channel)

{

    VCardAppletPrivate *applet_private = NULL;

    CACPKIAppletData *pki_applet = NULL;

    applet_private = vcard_get_current_applet_private(card, channel);

    assert(applet_private);

    pki_applet = &(applet_private->u.pki_data);

    pki_applet->cert_buffer = NULL;

    if (pki_applet->sign_buffer) {

        g_free(pki_applet->sign_buffer);

        pki_applet->sign_buffer = NULL;

    }

    pki_applet->cert_buffer_len = 0;

    pki_applet->sign_buffer_len = 0;

    return VCARD_DONE;

}


static void coroutine_fn bdrv_rw_co_entry(void *opaque)

{

    RwCo *rwco = opaque;

    if (!rwco->is_write) {

        rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,

                                      rwco->qiov->size, rwco->qiov,

                                      rwco->flags);

    } else {

        rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,

                                       rwco->qiov->size, rwco->qiov,

                                       rwco->flags);

    }

}


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

{

    help_cmd(argv[1]);

}