void ff_h264_filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {

    const int mb_xy= mb_x + mb_y*h->mb_stride;

    const int mb_type = h->cur_pic.mb_type[mb_xy];

    const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;

    int first_vertical_edge_done = 0;

    av_unused int dir;

    int chroma = !(CONFIG_GRAY && (h->flags&CODEC_FLAG_GRAY));

    int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    int a = h->slice_alpha_c0_offset - qp_bd_offset;

    int b = h->slice_beta_offset - qp_bd_offset;

    if (FRAME_MBAFF(h)

            // and current and left pair do not have the same interlaced type

            && IS_INTERLACED(mb_type^h->left_type[LTOP])

            // and left mb is in available to us

            && h->left_type[LTOP]) {

        /* First vertical edge is different in MBAFF frames

         * There are 8 different bS to compute and 2 different Qp

         */

        DECLARE_ALIGNED(8, int16_t, bS)[8];

        int qp[2];

        int bqp[2];

        int rqp[2];

        int mb_qp, mbn0_qp, mbn1_qp;

        int i;

        first_vertical_edge_done = 1;

        if( IS_INTRA(mb_type) ) {

            AV_WN64A(&bS[0], 0x0004000400040004ULL);

            AV_WN64A(&bS[4], 0x0004000400040004ULL);

        } else {

            static const uint8_t offset[2][2][8]={

                {

                    {3+4*0, 3+4*0, 3+4*0, 3+4*0, 3+4*1, 3+4*1, 3+4*1, 3+4*1},

                    {3+4*2, 3+4*2, 3+4*2, 3+4*2, 3+4*3, 3+4*3, 3+4*3, 3+4*3},

                },{

                    {3+4*0, 3+4*1, 3+4*2, 3+4*3, 3+4*0, 3+4*1, 3+4*2, 3+4*3},

                    {3+4*0, 3+4*1, 3+4*2, 3+4*3, 3+4*0, 3+4*1, 3+4*2, 3+4*3},

                }

            };

            const uint8_t *off= offset[MB_FIELD(h)][mb_y&1];

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

                int j= MB_FIELD(h) ? i>>2 : i&1;

                int mbn_xy = h->left_mb_xy[LEFT(j)];

                int mbn_type= h->left_type[LEFT(j)];

                if( IS_INTRA( mbn_type ) )

                    bS[i] = 4;

                else{

                    bS[i] = 1 + !!(h->non_zero_count_cache[12+8*(i>>1)] |

                         ((!h->pps.cabac && IS_8x8DCT(mbn_type)) ?

                            (h->cbp_table[mbn_xy] & (((MB_FIELD(h) ? (i&2) : (mb_y&1)) ? 8 : 2) << 12))

                                                                       :

                            h->non_zero_count[mbn_xy][ off[i] ]));

                }

            }

        }

        mb_qp   = h->cur_pic.qscale_table[mb_xy];

        mbn0_qp = h->cur_pic.qscale_table[h->left_mb_xy[0]];

        mbn1_qp = h->cur_pic.qscale_table[h->left_mb_xy[1]];

        qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;

        bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +

                   get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;

        rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +

                   get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;

        qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;

        bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +

                   get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;

        rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +

                   get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;

        /* Filter edge */

        tprintf(h->avctx, "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d", mb_x, mb_y, qp[0], qp[1], bqp[0], bqp[1], rqp[0], rqp[1], linesize, uvlinesize);

        { int i; for (i = 0; i < 8; i++) tprintf(h->avctx, " bS[%d]:%d", i, bS[i]); tprintf(h->avctx, "\n"); }

        if (MB_FIELD(h)) {

            filter_mb_mbaff_edgev ( h, img_y                ,   linesize, bS  , 1, qp [0], a, b, 1 );

            filter_mb_mbaff_edgev ( h, img_y  + 8*  linesize,   linesize, bS+4, 1, qp [1], a, b, 1 );

            if (chroma){

                if (CHROMA444(h)) {

                    filter_mb_mbaff_edgev ( h, img_cb,                uvlinesize, bS  , 1, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cb + 8*uvlinesize, uvlinesize, bS+4, 1, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr,                uvlinesize, bS  , 1, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr + 8*uvlinesize, uvlinesize, bS+4, 1, rqp[1], a, b, 1 );

                } else if (CHROMA422(h)) {

                    filter_mb_mbaff_edgecv(h, img_cb,                uvlinesize, bS  , 1, bqp[0], a, b, 1);

                    filter_mb_mbaff_edgecv(h, img_cb + 8*uvlinesize, uvlinesize, bS+4, 1, bqp[1], a, b, 1);

                    filter_mb_mbaff_edgecv(h, img_cr,                uvlinesize, bS  , 1, rqp[0], a, b, 1);

                    filter_mb_mbaff_edgecv(h, img_cr + 8*uvlinesize, uvlinesize, bS+4, 1, rqp[1], a, b, 1);

                }else{

                    filter_mb_mbaff_edgecv( h, img_cb,                uvlinesize, bS  , 1, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cb + 4*uvlinesize, uvlinesize, bS+4, 1, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr,                uvlinesize, bS  , 1, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr + 4*uvlinesize, uvlinesize, bS+4, 1, rqp[1], a, b, 1 );

                }

            }

        }else{

            filter_mb_mbaff_edgev ( h, img_y              , 2*  linesize, bS  , 2, qp [0], a, b, 1 );

            filter_mb_mbaff_edgev ( h, img_y  +   linesize, 2*  linesize, bS+1, 2, qp [1], a, b, 1 );

            if (chroma){

                if (CHROMA444(h)) {

                    filter_mb_mbaff_edgev ( h, img_cb,              2*uvlinesize, bS  , 2, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cb + uvlinesize, 2*uvlinesize, bS+1, 2, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr,              2*uvlinesize, bS  , 2, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr + uvlinesize, 2*uvlinesize, bS+1, 2, rqp[1], a, b, 1 );

                }else{

                    filter_mb_mbaff_edgecv( h, img_cb,              2*uvlinesize, bS  , 2, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cb + uvlinesize, 2*uvlinesize, bS+1, 2, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr,              2*uvlinesize, bS  , 2, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr + uvlinesize, 2*uvlinesize, bS+1, 2, rqp[1], a, b, 1 );

                }

            }

        }

    }

#if CONFIG_SMALL

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

        filter_mb_dir(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, dir ? 0 : first_vertical_edge_done, a, b, chroma, dir);

#else

    filter_mb_dir(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, first_vertical_edge_done, a, b, chroma, 0);

    filter_mb_dir(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, 0,                        a, b, chroma, 1);

#endif

}


DIRAC_PIXOP(put, ff_put, mmx)

DIRAC_PIXOP(avg, ff_avg, mmx)

DIRAC_PIXOP(avg, ff_avg, mmxext)

void ff_put_dirac_pixels16_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h)

{

    if (h&3)

        ff_put_dirac_pixels16_c(dst, src, stride, h);

    else

    ff_put_pixels16_sse2(dst, src[0], stride, h);

}


static CharDriverState *qemu_chr_open_spice_vmc(const char *id,

                                                ChardevBackend *backend,

                                                ChardevReturn *ret,

                                                Error **errp)

{

    const char *type = backend->u.spicevmc->type;

    const char **psubtype = spice_server_char_device_recognized_subtypes();

    for (; *psubtype != NULL; ++psubtype) {

        if (strcmp(type, *psubtype) == 0) {

            break;

        }

    }

    if (*psubtype == NULL) {

        fprintf(stderr, "spice-qemu-char: unsupported type: %s\n", type);

        print_allowed_subtypes();

        return NULL;

    }

    return chr_open(type, spice_vmc_set_fe_open);

}


void acpi_build(PcGuestInfo *guest_info, AcpiBuildTables *tables)

{

    GArray *table_offsets;

    unsigned facs, dsdt, rsdt;

    AcpiCpuInfo cpu;

    AcpiPmInfo pm;

    AcpiMiscInfo misc;

    AcpiMcfgInfo mcfg;

    PcPciInfo pci;

    uint8_t *u;

    acpi_get_cpu_info(&cpu);

    acpi_get_pm_info(&pm);

    acpi_get_dsdt(&misc);

    acpi_get_hotplug_info(&misc);

    acpi_get_misc_info(&misc);

    acpi_get_pci_info(&pci);

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

                                        sizeof(uint32_t));

    ACPI_BUILD_DPRINTF(3, "init ACPI tables\n");

    bios_linker_loader_alloc(tables->linker, ACPI_BUILD_TABLE_FILE,

                             64 /* Ensure FACS is aligned */,

                             false /* high memory */);

    /*

     * FACS is pointed to by FADT.

     * We place it first since it's the only table that has alignment

     * requirements.

     */

    facs = tables->table_data->len;

    build_facs(tables->table_data, tables->linker, guest_info);

    /* DSDT is pointed to by FADT */

    dsdt = tables->table_data->len;

    build_dsdt(tables->table_data, tables->linker, &misc);

    /* ACPI tables pointed to by RSDT */

    acpi_add_table(table_offsets, tables->table_data);

    build_fadt(tables->table_data, tables->linker, &pm, facs, dsdt);

    acpi_add_table(table_offsets, tables->table_data);

    build_ssdt(tables->table_data, tables->linker, &cpu, &pm, &misc, &pci,

               guest_info);

    acpi_add_table(table_offsets, tables->table_data);

    build_madt(tables->table_data, tables->linker, &cpu, guest_info);

    acpi_add_table(table_offsets, tables->table_data);

    if (misc.has_hpet) {

        build_hpet(tables->table_data, tables->linker);

    }

    if (guest_info->numa_nodes) {

        acpi_add_table(table_offsets, tables->table_data);

        build_srat(tables->table_data, tables->linker, &cpu, guest_info);

    }

    if (acpi_get_mcfg(&mcfg)) {

        acpi_add_table(table_offsets, tables->table_data);

        build_mcfg_q35(tables->table_data, tables->linker, &mcfg);

    }

    /* Add tables supplied by user (if any) */

    for (u = acpi_table_first(); u; u = acpi_table_next(u)) {

        unsigned len = acpi_table_len(u);

        acpi_add_table(table_offsets, tables->table_data);

        g_array_append_vals(tables->table_data, u, len);

    }

    /* RSDT is pointed to by RSDP */

    rsdt = tables->table_data->len;

    build_rsdt(tables->table_data, tables->linker, table_offsets);

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

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

    /* We'll expose it all to Guest so align size to reduce

     * chance of size changes.

     * RSDP is small so it's easy to keep it immutable, no need to

     * bother with alignment.

     */

    acpi_align_size(tables->table_data, 0x1000);

    acpi_align_size(tables->linker, 0x1000);

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

    g_array_free(table_offsets, true);

}


static uint32_t xen_platform_ioport_readb(void *opaque, uint32_t addr)

{

    addr &= 0xff;

    if (addr == 0) {

        return platform_fixed_ioport_readb(opaque, XEN_PLATFORM_IOPORT);

    } else {

        return ~0u;

    }

}


static ssize_t mp_pacl_getxattr(FsContext *ctx, const char *path,

                                const char *name, void *value, size_t size)

{

    char buffer[PATH_MAX];

    return lgetxattr(rpath(ctx, path, buffer), MAP_ACL_ACCESS, value, size);

}


void ga_command_state_init(GAState *s, GACommandState *cs)

{

    if (vss_init(true)) {

        ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);

    }

}


int ff_vaapi_commit_slices(FFVAContext *vactx)

{

    VABufferID *slice_buf_ids;

    VABufferID slice_param_buf_id, slice_data_buf_id;

    if (vactx->slice_count == 0)

        return 0;

    slice_buf_ids =

        av_fast_realloc(vactx->slice_buf_ids,

                        &vactx->slice_buf_ids_alloc,

                        (vactx->n_slice_buf_ids + 2) * sizeof(slice_buf_ids[0]));

    if (!slice_buf_ids)

        return -1;

    vactx->slice_buf_ids = slice_buf_ids;

    slice_param_buf_id = 0;

    if (vaCreateBuffer(vactx->display, vactx->context_id,

                       VASliceParameterBufferType,

                       vactx->slice_param_size,

                       vactx->slice_count, vactx->slice_params,

                       &slice_param_buf_id) != VA_STATUS_SUCCESS)

        return -1;

    vactx->slice_count = 0;

    slice_data_buf_id = 0;

    if (vaCreateBuffer(vactx->display, vactx->context_id,

                       VASliceDataBufferType,

                       vactx->slice_data_size,

                       1, (void *)vactx->slice_data,

                       &slice_data_buf_id) != VA_STATUS_SUCCESS)

        return -1;

    vactx->slice_data = NULL;

    vactx->slice_data_size = 0;

    slice_buf_ids[vactx->n_slice_buf_ids++] = slice_param_buf_id;

    slice_buf_ids[vactx->n_slice_buf_ids++] = slice_data_buf_id;

    return 0;

}


static void dec_scall(DisasContext *dc)

{

    TCGv t0;

    int l1;

    if (dc->imm5 == 7) {

        LOG_DIS("scall\n");

    } else if (dc->imm5 == 2) {

        LOG_DIS("break\n");

    } else {

        cpu_abort(dc->env, "invalid opcode\n");

    }

    t0 = tcg_temp_new();

    l1 = gen_new_label();

    if (dc->imm5 == 7) {

        tcg_gen_movi_tl(cpu_pc, dc->pc);

        t_gen_raise_exception(dc, EXCP_SYSTEMCALL);

    } else {

        tcg_gen_movi_tl(cpu_pc, dc->pc);

        t_gen_raise_exception(dc, EXCP_BREAKPOINT);

    }

}


static void slavio_check_interrupts(void *opaque)

{

    CPUState *env;

    SLAVIO_INTCTLState *s = opaque;

    uint32_t pending = s->intregm_pending;

    unsigned int i, j, max = 0;

    pending &= ~s->intregm_disabled;

    if (pending && !(s->intregm_disabled & 0x80000000)) {

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

	    if (pending & (1 << i)) {

		if (max < s->intbit_to_level[i])

		    max = s->intbit_to_level[i];

	    }

	}

        env = s->cpu_envs[s->target_cpu];

        if (!env) {

	    DPRINTF("No CPU %d, not triggered (pending %x)\n", s->target_cpu, pending);

        }

	else {

            if (env->halted)

                env->halted = 0;

            if (env->interrupt_index == 0) {

                DPRINTF("Triggered CPU %d pil %d\n", s->target_cpu, max);

#ifdef DEBUG_IRQ_COUNT

                s->irq_count[max]++;

#endif

                env->interrupt_index = TT_EXTINT | max;

                cpu_interrupt(env, CPU_INTERRUPT_HARD);

            }

            else

                DPRINTF("Not triggered (pending %x), pending exception %x\n", pending, env->interrupt_index);

	}

    }

    else

	DPRINTF("Not triggered (pending %x), disabled %x\n", pending, s->intregm_disabled);

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

        max = 0;

        env = s->cpu_envs[i];

        if (!env)

            continue;

        for (j = 17; j < 32; j++) {

            if (s->intreg_pending[i] & (1 << j)) {

                if (max < j - 16)

                    max = j - 16;

            }

        }

	if (max > 0) {

            if (env->halted)

                env->halted = 0;

            if (env->interrupt_index == 0) {

                DPRINTF("Triggered softint %d for cpu %d (pending %x)\n", max, i, pending);

#ifdef DEBUG_IRQ_COUNT

                s->irq_count[max]++;

#endif

                env->interrupt_index = TT_EXTINT | max;

                cpu_interrupt(env, CPU_INTERRUPT_HARD);

            }

        }

    }

}


static int pci_add_option_rom(PCIDevice *pdev, bool is_default_rom)

{

    int size;

    char *path;

    void *ptr;

    char name[32];

    const VMStateDescription *vmsd;

    if (!pdev->romfile)

        return 0;

    if (strlen(pdev->romfile) == 0)

        return 0;

    if (!pdev->rom_bar) {

        /*

         * Load rom via fw_cfg instead of creating a rom bar,

         * for 0.11 compatibility.

         */

        int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);

        if (class == 0x0300) {

            rom_add_vga(pdev->romfile);

        } else {

            rom_add_option(pdev->romfile, -1);

        }

        return 0;

    }

    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);

    if (path == NULL) {

        path = g_strdup(pdev->romfile);

    }

    size = get_image_size(path);

    if (size < 0) {

        error_report("%s: failed to find romfile \"%s\"",

                     __FUNCTION__, pdev->romfile);

        g_free(path);

        return -1;

    }

    if (size & (size - 1)) {

        size = 1 << qemu_fls(size);

    }

    vmsd = qdev_get_vmsd(DEVICE(pdev));

    if (vmsd) {

        snprintf(name, sizeof(name), "%s.rom", vmsd->name);

    } else {

        snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));

    }

    pdev->has_rom = true;

    memory_region_init_ram(&pdev->rom, name, size);

    vmstate_register_ram(&pdev->rom, &pdev->qdev);

    ptr = memory_region_get_ram_ptr(&pdev->rom);

    load_image(path, ptr);

    g_free(path);

    if (is_default_rom) {

        /* Only the default rom images will be patched (if needed). */

        pci_patch_ids(pdev, ptr, size);

    }

    qemu_put_ram_ptr(ptr);

    pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);

    return 0;

}


static char *qemu_rbd_next_tok(int max_len,

                               char *src, char delim,

                               const char *name,

                               char **p, Error **errp)

{

    int l;

    char *end;

    *p = NULL;

    if (delim != '\0') {

        for (end = src; *end; ++end) {

            if (*end == delim) {

                break;

            }

            if (*end == '\\' && end[1] != '\0') {

                end++;

            }

        }

        if (*end == delim) {

            *p = end + 1;

            *end = '\0';

        }

    }

    l = strlen(src);

    if (l >= max_len) {

        error_setg(errp, "%s too long", name);

        return NULL;

    } else if (l == 0) {

        error_setg(errp, "%s too short", name);

        return NULL;

    }

    return src;

}


static int protocol_client_vencrypt_auth(VncState *vs, uint8_t *data, size_t len)

{

    int auth = read_u32(data, 0);

    if (auth != vs->vd->subauth) {

        VNC_DEBUG("Rejecting auth %d\n", auth);

        vnc_write_u8(vs, 0); /* Reject auth */

        vnc_flush(vs);

        vnc_client_error(vs);

    } else {

        VNC_DEBUG("Accepting auth %d, setting up TLS for handshake\n", auth);

        vnc_write_u8(vs, 1); /* Accept auth */

        vnc_flush(vs);

        if (vnc_tls_client_setup(vs, NEED_X509_AUTH(vs)) < 0) {

            VNC_DEBUG("Failed to setup TLS\n");

            return 0;

        }

        VNC_DEBUG("Start TLS VeNCrypt handshake process\n");

        if (vnc_start_vencrypt_handshake(vs) < 0) {

            VNC_DEBUG("Failed to start TLS handshake\n");

            return 0;

        }

    }

    return 0;

}


int64_t qemu_strtosz_metric(const char *nptr, char **end)

{

    return do_strtosz(nptr, end, 'B', 1000);

}


static int l2_load(BlockDriverState *bs, uint64_t l2_offset,

    uint64_t **l2_table)

{

    BDRVQcow2State *s = bs->opaque;

    int ret;

    ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset, (void**) l2_table);

    return ret;

}


static int mjpeg_decode_init(AVCodecContext *avctx)

{

    MJpegDecodeContext *s = avctx->priv_data;

    MpegEncContext s2;

    s->avctx = avctx;

    /* ugly way to get the idct & scantable */

    memset(&s2, 0, sizeof(MpegEncContext));

    s2.flags= avctx->flags;

    s2.avctx= avctx;

//    s2->out_format = FMT_MJPEG;

    s2.width = 8;

    s2.height = 8;

    if (MPV_common_init(&s2) < 0)

       return -1;

    s->scantable= s2.intra_scantable;

    s->idct_put= s2.idct_put;

    MPV_common_end(&s2);

    s->mpeg_enc_ctx_allocated = 0;

    s->buffer_size = 102400; /* smaller buffer should be enough,

				but photojpg files could ahive bigger sizes */

    s->buffer = av_malloc(s->buffer_size);

    if (!s->buffer)

	return -1;

    s->start_code = -1;

    s->first_picture = 1;

    s->org_width = avctx->width;

    s->org_height = avctx->height;

    build_vlc(&s->vlcs[0][0], bits_dc_luminance, val_dc_luminance, 12);

    build_vlc(&s->vlcs[0][1], bits_dc_chrominance, val_dc_chrominance, 12);

    build_vlc(&s->vlcs[1][0], bits_ac_luminance, val_ac_luminance, 251);

    build_vlc(&s->vlcs[1][1], bits_ac_chrominance, val_ac_chrominance, 251);

    if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)

    {

	printf("mjpeg: using external huffman table\n");

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

	mjpeg_decode_dht(s);

	/* should check for error - but dunno */

    }

    return 0;

}


static int pci_std_vga_initfn(PCIDevice *dev)

{

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

    VGACommonState *s = &d->vga;

    /* vga + console init */

    vga_common_init(s);

    vga_init(s, pci_address_space(dev), pci_address_space_io(dev), true);

    s->con = graphic_console_init(s->update, s->invalidate,

                                  s->screen_dump, s->text_update, s);

    /* XXX: VGA_RAM_SIZE must be a power of two */

    pci_register_bar(&d->dev, 0, PCI_BASE_ADDRESS_MEM_PREFETCH, &s->vram);

    /* mmio bar for vga register access */

    if (d->flags & (1 << PCI_VGA_FLAG_ENABLE_MMIO)) {

        memory_region_init(&d->mmio, "vga.mmio", 4096);

        memory_region_init_io(&d->ioport, &pci_vga_ioport_ops, d,

                              "vga ioports remapped", PCI_VGA_IOPORT_SIZE);

        memory_region_init_io(&d->bochs, &pci_vga_bochs_ops, d,

                              "bochs dispi interface", PCI_VGA_BOCHS_SIZE);

        memory_region_add_subregion(&d->mmio, PCI_VGA_IOPORT_OFFSET,

                                    &d->ioport);

        memory_region_add_subregion(&d->mmio, PCI_VGA_BOCHS_OFFSET,

                                    &d->bochs);

        pci_register_bar(&d->dev, 2, PCI_BASE_ADDRESS_SPACE_MEMORY, &d->mmio);

    }

    if (!dev->rom_bar) {

        /* compatibility with pc-0.13 and older */

        vga_init_vbe(s, pci_address_space(dev));

    }

    return 0;

}


static int tosa_dac_recv(I2CSlave *s)

{

    printf("%s: recv not supported!!!\n", __FUNCTION__);

    return -1;

}


static int waveformat_from_audio_settings (WAVEFORMATEX *wfx, audsettings_t *as)

{

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

    wfx->wFormatTag = WAVE_FORMAT_PCM;

    wfx->nChannels = as->nchannels;

    wfx->nSamplesPerSec = as->freq;

    wfx->nAvgBytesPerSec = as->freq << (as->nchannels == 2);

    wfx->nBlockAlign = 1 << (as->nchannels == 2);

    wfx->cbSize = 0;

    switch (as->fmt) {

    case AUD_FMT_S8:

    case AUD_FMT_U8:

        wfx->wBitsPerSample = 8;

        break;

    case AUD_FMT_S16:

    case AUD_FMT_U16:

        wfx->wBitsPerSample = 16;

        wfx->nAvgBytesPerSec <<= 1;

        wfx->nBlockAlign <<= 1;

        break;

    case AUD_FMT_S32:

    case AUD_FMT_U32:

        wfx->wBitsPerSample = 32;

        wfx->nAvgBytesPerSec <<= 2;

        wfx->nBlockAlign <<= 2;

        break;

    default:

        dolog ("Internal logic error: Bad audio format %d\n", as->freq);

        return -1;

    }

    return 0;

}


static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,

    int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

    BlockDriverCompletionFunc *cb, void *opaque)

{

    return bdrv_aio_readv(bs->file, sector_num, qiov, nb_sectors, cb, opaque);

}


static int blk_mig_save_dirty_block(Monitor *mon, QEMUFile *f, int is_async)

{

    BlkMigDevState *bmds;

    int ret = 0;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {

        if (mig_save_device_dirty(mon, f, bmds, is_async) == 0) {

            ret = 1;

            break;

        }

    }

    return ret;

}


float64 float64_sqrt( float64 a STATUS_PARAM )

{

    flag aSign;

    int16 aExp, zExp;

    bits64 aSig, zSig, doubleZSig;

    bits64 rem0, rem1, term0, term1;

    aSig = extractFloat64Frac( a );

    aExp = extractFloat64Exp( a );

    aSign = extractFloat64Sign( a );

    if ( aExp == 0x7FF ) {

        if ( aSig ) return propagateFloat64NaN( a, a STATUS_VAR );

        if ( ! aSign ) return a;

        float_raise( float_flag_invalid STATUS_VAR);

        return float64_default_nan;

    }

    if ( aSign ) {

        if ( ( aExp | aSig ) == 0 ) return a;

        float_raise( float_flag_invalid STATUS_VAR);

        return float64_default_nan;

    }

    if ( aExp == 0 ) {

        if ( aSig == 0 ) return 0;

        normalizeFloat64Subnormal( aSig, &aExp, &aSig );

    }

    zExp = ( ( aExp - 0x3FF )>>1 ) + 0x3FE;

    aSig |= LIT64( 0x0010000000000000 );

    zSig = estimateSqrt32( aExp, aSig>>21 );

    aSig <<= 9 - ( aExp & 1 );

    zSig = estimateDiv128To64( aSig, 0, zSig<<32 ) + ( zSig<<30 );

    if ( ( zSig & 0x1FF ) <= 5 ) {

        doubleZSig = zSig<<1;

        mul64To128( zSig, zSig, &term0, &term1 );

        sub128( aSig, 0, term0, term1, &rem0, &rem1 );

        while ( (sbits64) rem0 < 0 ) {

            --zSig;

            doubleZSig -= 2;

            add128( rem0, rem1, zSig>>63, doubleZSig | 1, &rem0, &rem1 );

        }

        zSig |= ( ( rem0 | rem1 ) != 0 );

    }

    return roundAndPackFloat64( 0, zExp, zSig STATUS_VAR );

}


static int dynticks_start_timer(struct qemu_alarm_timer *t)

{

    struct sigevent ev;

    timer_t host_timer;

    struct sigaction act;

    sigfillset(&act.sa_mask);

    act.sa_flags = 0;

    act.sa_handler = host_alarm_handler;

    sigaction(SIGALRM, &act, NULL);

    /*

     * Initialize ev struct to 0 to avoid valgrind complaining

     * about uninitialized data in timer_create call

     */

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

    ev.sigev_value.sival_int = 0;

    ev.sigev_notify = SIGEV_SIGNAL;

#ifdef SIGEV_THREAD_ID

    if (qemu_signalfd_available()) {

        ev.sigev_notify = SIGEV_THREAD_ID;

        ev._sigev_un._tid = qemu_get_thread_id();

    }

#endif /* SIGEV_THREAD_ID */

    ev.sigev_signo = SIGALRM;

    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {

        perror("timer_create");

        return -1;

    }

    t->timer = host_timer;

    return 0;

}


void sysbus_register_withprop(SysBusDeviceInfo *info)

{

    info->qdev.init = sysbus_device_init;

    info->qdev.bus_type = BUS_TYPE_SYSTEM;

    assert(info->qdev.size >= sizeof(SysBusDevice));

    qdev_register(&info->qdev);

}


int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)

{

    if (!timer_head)

        return 0;

    return (timer_head->expire_time <= current_time);

}


static int cbs_read_se_golomb(CodedBitstreamContext *ctx, BitstreamContext *bc,

                              const char *name, int32_t *write_to,

                              int32_t range_min, int32_t range_max)

{

    int32_t value;

    int position;

    if (ctx->trace_enable) {

        char bits[65];

        uint32_t v;

        unsigned int k;

        int i, j;

        position = bitstream_tell(bc);

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

            k = bitstream_read_bit(bc);

            bits[i] = k ? '1' : '0';

            if (k)

                break;

        }

        if (i >= 32) {

            av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid se-golomb "

                   "code found while reading %s: "

                   "more than 31 zeroes.\n", name);

            return AVERROR_INVALIDDATA;

        }

        v = 1;

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

            k = bitstream_read_bit(bc);

            bits[i + j + 1] = k ? '1' : '0';

            v = v << 1 | k;

        }

        bits[i + j + 1] = 0;

        if (v & 1)

            value = -(int32_t)(v / 2);

        else

            value = v / 2;

        ff_cbs_trace_syntax_element(ctx, position, name, bits, value);

    } else {

        value = get_se_golomb_long(bc);

    }

    if (value < range_min || value > range_max) {

        av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "

               "%"PRId32", but must be in [%"PRId32",%"PRId32"].\n",

               name, value, range_min, range_max);

        return AVERROR_INVALIDDATA;

    }

    *write_to = value;

    return 0;

}


void cpu_x86_cpuid(CPUX86State *env, uint32_t index,

                   uint32_t *eax, uint32_t *ebx,

                   uint32_t *ecx, uint32_t *edx)

{

    /* test if maximum index reached */

    if (index & 0x80000000) {

        if (index > env->cpuid_xlevel)

            index = env->cpuid_level;

    } else {

        if (index > env->cpuid_level)

            index = env->cpuid_level;

    }

    switch(index) {

    case 0:

        *eax = env->cpuid_level;

        *ebx = env->cpuid_vendor1;

        *edx = env->cpuid_vendor2;

        *ecx = env->cpuid_vendor3;

        /* sysenter isn't supported on compatibility mode on AMD.  and syscall

         * isn't supported in compatibility mode on Intel.  so advertise the

         * actuall cpu, and say goodbye to migration between different vendors

         * is you use compatibility mode. */

        if (kvm_enabled())

            host_cpuid(0, NULL, ebx, ecx, edx);

        break;

    case 1:

        *eax = env->cpuid_version;

        *ebx = (env->cpuid_apic_id << 24) | 8 << 8; /* CLFLUSH size in quad words, Linux wants it. */

        *ecx = env->cpuid_ext_features;

        *edx = env->cpuid_features;

        /* "Hypervisor present" bit required for Microsoft SVVP */

        if (kvm_enabled())

            *ecx |= (1 << 31);

        break;

    case 2:

        /* cache info: needed for Pentium Pro compatibility */

        *eax = 1;

        *ebx = 0;

        *ecx = 0;

        *edx = 0x2c307d;

        break;

    case 4:

        /* cache info: needed for Core compatibility */

        switch (*ecx) {

            case 0: /* L1 dcache info */

                *eax = 0x0000121;

                *ebx = 0x1c0003f;

                *ecx = 0x000003f;

                *edx = 0x0000001;

                break;

            case 1: /* L1 icache info */

                *eax = 0x0000122;

                *ebx = 0x1c0003f;

                *ecx = 0x000003f;

                *edx = 0x0000001;

                break;

            case 2: /* L2 cache info */

                *eax = 0x0000143;

                *ebx = 0x3c0003f;

                *ecx = 0x0000fff;

                *edx = 0x0000001;

                break;

            default: /* end of info */

                *eax = 0;

                *ebx = 0;

                *ecx = 0;

                *edx = 0;

                break;

        }

        break;

    case 5:

        /* mwait info: needed for Core compatibility */

        *eax = 0; /* Smallest monitor-line size in bytes */

        *ebx = 0; /* Largest monitor-line size in bytes */

        *ecx = CPUID_MWAIT_EMX | CPUID_MWAIT_IBE;

        *edx = 0;

        break;

    case 6:

        /* Thermal and Power Leaf */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    case 9:

        /* Direct Cache Access Information Leaf */

        *eax = 0; /* Bits 0-31 in DCA_CAP MSR */

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    case 0xA:

        /* Architectural Performance Monitoring Leaf */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    case 0x80000000:

        *eax = env->cpuid_xlevel;

        *ebx = env->cpuid_vendor1;

        *edx = env->cpuid_vendor2;

        *ecx = env->cpuid_vendor3;

        break;

    case 0x80000001:

        *eax = env->cpuid_features;

        *ebx = 0;

        *ecx = env->cpuid_ext3_features;

        *edx = env->cpuid_ext2_features;

        if (kvm_enabled()) {

            uint32_t h_eax, h_edx;

            host_cpuid(0x80000001, &h_eax, NULL, NULL, &h_edx);

            /* disable CPU features that the host does not support */

            /* long mode */

            if ((h_edx & 0x20000000) == 0 /* || !lm_capable_kernel */)

                *edx &= ~0x20000000;

            /* syscall */

            if ((h_edx & 0x00000800) == 0)

                *edx &= ~0x00000800;

            /* nx */

            if ((h_edx & 0x00100000) == 0)

                *edx &= ~0x00100000;

            /* disable CPU features that KVM cannot support */

            /* svm */

            *ecx &= ~4UL;

            /* 3dnow */

            *edx = ~0xc0000000;

        }

        break;

    case 0x80000002:

    case 0x80000003:

    case 0x80000004:

        *eax = env->cpuid_model[(index - 0x80000002) * 4 + 0];

        *ebx = env->cpuid_model[(index - 0x80000002) * 4 + 1];

        *ecx = env->cpuid_model[(index - 0x80000002) * 4 + 2];

        *edx = env->cpuid_model[(index - 0x80000002) * 4 + 3];

        break;

    case 0x80000005:

        /* cache info (L1 cache) */

        *eax = 0x01ff01ff;

        *ebx = 0x01ff01ff;

        *ecx = 0x40020140;

        *edx = 0x40020140;

        break;

    case 0x80000006:

        /* cache info (L2 cache) */

        *eax = 0;

        *ebx = 0x42004200;

        *ecx = 0x02008140;

        *edx = 0;

        break;

    case 0x80000008:

        /* virtual & phys address size in low 2 bytes. */

/* XXX: This value must match the one used in the MMU code. */

        if (env->cpuid_ext2_features & CPUID_EXT2_LM) {

            /* 64 bit processor */

#if defined(USE_KQEMU)

            *eax = 0x00003020;	/* 48 bits virtual, 32 bits physical */

#else

/* XXX: The physical address space is limited to 42 bits in exec.c. */

            *eax = 0x00003028;	/* 48 bits virtual, 40 bits physical */

#endif

        } else {

#if defined(USE_KQEMU)

            *eax = 0x00000020;	/* 32 bits physical */

#else

            if (env->cpuid_features & CPUID_PSE36)

                *eax = 0x00000024; /* 36 bits physical */

            else

                *eax = 0x00000020; /* 32 bits physical */

#endif

        }

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    case 0x8000000A:

        *eax = 0x00000001; /* SVM Revision */

        *ebx = 0x00000010; /* nr of ASIDs */

        *ecx = 0;

        *edx = 0; /* optional features */

        break;

    default:

        /* reserved values: zero */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    }

}


static uint32_t isa_mmio_readl(void *opaque, target_phys_addr_t addr)

{

    return cpu_inl(addr & IOPORTS_MASK);

}


static always_inline int _pte_check (mmu_ctx_t *ctx, int is_64b,

                                     target_ulong pte0, target_ulong pte1,

                                     int h, int rw)

{

    target_ulong ptem, mmask;

    int access, ret, pteh, ptev;

    access = 0;

    ret = -1;

    /* Check validity and table match */

#if defined(TARGET_PPC64)

    if (is_64b) {

        ptev = pte64_is_valid(pte0);

        pteh = (pte0 >> 1) & 1;

    } else

#endif

    {

        ptev = pte_is_valid(pte0);

        pteh = (pte0 >> 6) & 1;

    }

    if (ptev && h == pteh) {

        /* Check vsid & api */

#if defined(TARGET_PPC64)

        if (is_64b) {

            ptem = pte0 & PTE64_PTEM_MASK;

            mmask = PTE64_CHECK_MASK;

        } else

#endif

        {

            ptem = pte0 & PTE_PTEM_MASK;

            mmask = PTE_CHECK_MASK;

        }

        if (ptem == ctx->ptem) {

            if (ctx->raddr != (target_ulong)-1) {

                /* all matches should have equal RPN, WIMG & PP */

                if ((ctx->raddr & mmask) != (pte1 & mmask)) {

                    if (loglevel != 0)

                        fprintf(logfile, "Bad RPN/WIMG/PP\n");

                    return -3;

                }

            }

            /* Compute access rights */

            if (ctx->key == 0) {

                access = PAGE_READ;

                if ((pte1 & 0x00000003) != 0x3)

                    access |= PAGE_WRITE;

            } else {

                switch (pte1 & 0x00000003) {

                case 0x0:

                    access = 0;

                    break;

                case 0x1:

                case 0x3:

                    access = PAGE_READ;

                    break;

                case 0x2:

                    access = PAGE_READ | PAGE_WRITE;

                    break;

                }

            }

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            if ((rw == 0 && (access & PAGE_READ)) ||

                (rw == 1 && (access & PAGE_WRITE))) {

                /* Access granted */

#if defined (DEBUG_MMU)

                if (loglevel != 0)

                    fprintf(logfile, "PTE access granted !\n");

#endif

                ret = 0;

            } else {

                /* Access right violation */

#if defined (DEBUG_MMU)

                if (loglevel != 0)

                    fprintf(logfile, "PTE access rejected\n");

#endif

                ret = -2;

            }

        }

    }

    return ret;

}


void qmp_block_job_resume(const char *device, Error **errp)

{

    BlockJob *job = find_block_job(device);

    if (!job) {

        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);

        return;

    }

    trace_qmp_block_job_resume(job);

    block_job_resume(job);

}


int AUD_write (SWVoiceOut *sw, void *buf, int size)

{

    int bytes;

    if (!sw) {

        /* XXX: Consider options */

        return size;

    }

    if (!sw->hw->enabled) {

        dolog ("Writing to disabled voice %s\n", SW_NAME (sw));

        return 0;

    }

    bytes = sw->hw->pcm_ops->write (sw, buf, size);

    return bytes;

}


static void option_rom_setup_reset(target_phys_addr_t addr, unsigned size)

{

    RomResetData *rrd = qemu_malloc(sizeof *rrd);

    rrd->data = qemu_malloc(size);

    cpu_physical_memory_read(addr, rrd->data, size);

    rrd->addr = addr;

    rrd->size = size;

    qemu_register_reset(option_rom_reset, rrd);

}


static uint32_t drc_unisolate_physical(sPAPRDRConnector *drc)

{

    /* cannot unisolate a non-existent resource, and, or resources

     * which are in an 'UNUSABLE' allocation state. (PAPR 2.7,

     * 13.5.3.5)

     */

    if (!drc->dev) {

        return RTAS_OUT_NO_SUCH_INDICATOR;

    }

    drc->isolation_state = SPAPR_DR_ISOLATION_STATE_UNISOLATED;

    return RTAS_OUT_SUCCESS;

}


static void monitor_command_cb(Monitor *mon, const char *cmdline, void *opaque)

{

    monitor_suspend(mon);

    handle_user_command(mon, cmdline);

    monitor_resume(mon);

}


static void dct_unquantize_mpeg1_c(MpegEncContext *s,

                                   DCTELEM *block, int n, int qscale)

{

    int i, level, nCoeffs;

    const UINT16 *quant_matrix;

    if(s->alternate_scan) nCoeffs= 64;

    else nCoeffs= s->block_last_index[n]+1;

    if (s->mb_intra) {

        if (n < 4)

            block[0] = block[0] * s->y_dc_scale;

        else

            block[0] = block[0] * s->c_dc_scale;

        /* XXX: only mpeg1 */

        quant_matrix = s->intra_matrix;

        for(i=1;i<nCoeffs;i++) {

            int j= zigzag_direct[i];

            level = block[j];

            if (level) {

                if (level < 0) {

                    level = -level;

                    level = (int)(level * qscale * quant_matrix[j]) >> 3;

                    level = (level - 1) | 1;

                    level = -level;

                } else {

                    level = (int)(level * qscale * quant_matrix[j]) >> 3;

                    level = (level - 1) | 1;

                }

#ifdef PARANOID

                if (level < -2048 || level > 2047)

                    fprintf(stderr, "unquant error %d %d\n", i, level);

#endif

                block[j] = level;

            }

        }

    } else {

        i = 0;

        quant_matrix = s->non_intra_matrix;

        for(;i<nCoeffs;i++) {

            int j= zigzag_direct[i];

            level = block[j];

            if (level) {

                if (level < 0) {

                    level = -level;

                    level = (((level << 1) + 1) * qscale *

                             ((int) (quant_matrix[j]))) >> 4;

                    level = (level - 1) | 1;

                    level = -level;

                } else {

                    level = (((level << 1) + 1) * qscale *

                             ((int) (quant_matrix[j]))) >> 4;

                    level = (level - 1) | 1;

                }

#ifdef PARANOID

                if (level < -2048 || level > 2047)

                    fprintf(stderr, "unquant error %d %d\n", i, level);

#endif

                block[j] = level;

            }

        }

    }

}


static void balloon_stats_get_all(Object *obj, struct Visitor *v,

                                  void *opaque, const char *name, Error **errp)

{

    Error *err = NULL;

    VirtIOBalloon *s = opaque;

    int i;

    if (!s->stats_last_update) {

        error_setg(errp, "guest hasn't updated any stats yet");

        return;

    }

    visit_start_struct(v, NULL, "guest-stats", name, 0, &err);

    if (err) {

        goto out;

    }

    visit_type_int(v, &s->stats_last_update, "last-update", &err);

    visit_start_struct(v, NULL, NULL, "stats", 0, &err);

    if (err) {

        goto out_end;

    }

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

        visit_type_int64(v, (int64_t *) &s->stats[i], balloon_stat_names[i],

                         &err);

    }

    visit_end_struct(v, &err);

out_end:

    visit_end_struct(v, &err);

out:

    error_propagate(errp, err);

}


void qemuio_add_command(const cmdinfo_t *ci)

{

    cmdtab = g_realloc(cmdtab, ++ncmds * sizeof(*cmdtab));

    cmdtab[ncmds - 1] = *ci;

    qsort(cmdtab, ncmds, sizeof(*cmdtab), compare_cmdname);

}


static void max_x86_cpu_initfn(Object *obj)

{

    X86CPU *cpu = X86_CPU(obj);

    CPUX86State *env = &cpu->env;

    KVMState *s = kvm_state;

    /* We can't fill the features array here because we don't know yet if

     * "migratable" is true or false.

     */

    cpu->max_features = true;

    if (kvm_enabled()) {

        X86CPUDefinition host_cpudef = { };

        uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;

        host_vendor_fms(host_cpudef.vendor, &host_cpudef.family,

                        &host_cpudef.model, &host_cpudef.stepping);

        cpu_x86_fill_model_id(host_cpudef.model_id);

        x86_cpu_load_def(cpu, &host_cpudef, &error_abort);

        env->cpuid_min_level =

            kvm_arch_get_supported_cpuid(s, 0x0, 0, R_EAX);

        env->cpuid_min_xlevel =

            kvm_arch_get_supported_cpuid(s, 0x80000000, 0, R_EAX);

        env->cpuid_min_xlevel2 =

            kvm_arch_get_supported_cpuid(s, 0xC0000000, 0, R_EAX);

        if (lmce_supported()) {

            object_property_set_bool(OBJECT(cpu), true, "lmce", &error_abort);

        }

    } else {

        object_property_set_str(OBJECT(cpu), CPUID_VENDOR_AMD,

                                "vendor", &error_abort);

        object_property_set_int(OBJECT(cpu), 6, "family", &error_abort);

        object_property_set_int(OBJECT(cpu), 6, "model", &error_abort);

        object_property_set_int(OBJECT(cpu), 3, "stepping", &error_abort);

        object_property_set_str(OBJECT(cpu),

                                "QEMU TCG CPU version " QEMU_HW_VERSION,

                                "model-id", &error_abort);

    }

    object_property_set_bool(OBJECT(cpu), true, "pmu", &error_abort);

}


static int vfio_get_device(VFIOGroup *group, const char *name, VFIODevice *vdev)

{

    struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };

    struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };

    int ret, i;

    ret = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);

    if (ret < 0) {

        error_report("vfio: error getting device %s from group %d: %m\n",

                     name, group->groupid);

        error_report("Verify all devices in group %d are bound to vfio-pci "

                     "or pci-stub and not already in use\n", group->groupid);

        return ret;

    }

    vdev->fd = ret;

    vdev->group = group;

    QLIST_INSERT_HEAD(&group->device_list, vdev, next);

    /* Sanity check device */

    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_INFO, &dev_info);

    if (ret) {

        error_report("vfio: error getting device info: %m\n");

        goto error;

    }

    DPRINTF("Device %s flags: %u, regions: %u, irgs: %u\n", name,

            dev_info.flags, dev_info.num_regions, dev_info.num_irqs);

    if (!(dev_info.flags & VFIO_DEVICE_FLAGS_PCI)) {

        error_report("vfio: Um, this isn't a PCI device\n");

        goto error;

    }

    vdev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);

    if (!vdev->reset_works) {

        error_report("Warning, device %s does not support reset\n", name);

    }

    if (dev_info.num_regions != VFIO_PCI_NUM_REGIONS) {

        error_report("vfio: unexpected number of io regions %u\n",

                     dev_info.num_regions);

        goto error;

    }

    if (dev_info.num_irqs != VFIO_PCI_NUM_IRQS) {

        error_report("vfio: unexpected number of irqs %u\n", dev_info.num_irqs);

        goto error;

    }

    for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {

        reg_info.index = i;

        ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);

        if (ret) {

            error_report("vfio: Error getting region %d info: %m\n", i);

            goto error;

        }

        DPRINTF("Device %s region %d:\n", name, i);

        DPRINTF("  size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",

                (unsigned long)reg_info.size, (unsigned long)reg_info.offset,

                (unsigned long)reg_info.flags);

        vdev->bars[i].flags = reg_info.flags;

        vdev->bars[i].size = reg_info.size;

        vdev->bars[i].fd_offset = reg_info.offset;

        vdev->bars[i].fd = vdev->fd;

        vdev->bars[i].nr = i;

    }

    reg_info.index = VFIO_PCI_ROM_REGION_INDEX;

    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);

    if (ret) {

        error_report("vfio: Error getting ROM info: %m\n");

        goto error;

    }

    DPRINTF("Device %s ROM:\n", name);

    DPRINTF("  size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",

            (unsigned long)reg_info.size, (unsigned long)reg_info.offset,

            (unsigned long)reg_info.flags);

    vdev->rom_size = reg_info.size;

    vdev->rom_offset = reg_info.offset;

    reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;

    ret = ioctl(vdev->fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);

    if (ret) {

        error_report("vfio: Error getting config info: %m\n");

        goto error;

    }

    DPRINTF("Device %s config:\n", name);

    DPRINTF("  size: 0x%lx, offset: 0x%lx, flags: 0x%lx\n",

            (unsigned long)reg_info.size, (unsigned long)reg_info.offset,

            (unsigned long)reg_info.flags);

    vdev->config_size = reg_info.size;

    vdev->config_offset = reg_info.offset;

error:

    if (ret) {

        QLIST_REMOVE(vdev, next);

        vdev->group = NULL;

        close(vdev->fd);

    }

    return ret;

}


static int parse_inputs(const char **buf, AVFilterInOut **currInputs,

                        AVFilterInOut **openLinks, AVClass *log_ctx)

{

    int pad = 0;

    while(**buf == '[') {

        char *name = parse_link_name(buf, log_ctx);

        AVFilterInOut *match;

        if(!name)

            return -1;

        /* First check if the label is not in the openLinks list */

        match = extract_inout(name, openLinks);

        if(match) {

            /* A label of a open link. Make it one of the inputs of the next

               filter */

            if(match->type != LinkTypeOut) {

                av_log(log_ctx, AV_LOG_ERROR,

                       "Label \"%s\" appears twice as input!\n", match->name);

                return -1;

            }

        } else {

            /* Not in the list, so add it as an input */

            match = av_mallocz(sizeof(AVFilterInOut));

            match->name    = name;

            match->type    = LinkTypeIn;

            match->pad_idx = pad;

        }

        insert_inout(currInputs, match);

        *buf += consume_whitespace(*buf);

        pad++;

    }

    return pad;

}


static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,

                                   Error **errp)

{

    const char *buf;

    int bdrv_flags = 0;

    int on_read_error, on_write_error;

    BlockBackend *blk;

    BlockDriverState *bs;

    ThrottleConfig cfg;

    int snapshot = 0;

    Error *error = NULL;

    QemuOpts *opts;

    const char *id;

    bool has_driver_specific_opts;

    BlockdevDetectZeroesOptions detect_zeroes =

        BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;

    const char *throttling_group = NULL;

    /* Check common options by copying from bs_opts to opts, all other options

     * stay in bs_opts for processing by bdrv_open(). */

    id = qdict_get_try_str(bs_opts, "id");

    opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);

    if (error) {

        error_propagate(errp, error);

        goto err_no_opts;

    }

    qemu_opts_absorb_qdict(opts, bs_opts, &error);

    if (error) {

        error_propagate(errp, error);

        goto early_err;

    }

    if (id) {

        qdict_del(bs_opts, "id");

    }

    has_driver_specific_opts = !!qdict_size(bs_opts);

    /* extract parameters */

    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);

    account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);

    account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);

    extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,

                                    &detect_zeroes, &error);

    if (error) {

        error_propagate(errp, error);

        goto early_err;

    }

    if ((buf = qemu_opt_get(opts, "format")) != NULL) {

        if (is_help_option(buf)) {

            error_printf("Supported formats:");

            bdrv_iterate_format(bdrv_format_print, NULL);

            error_printf("\n");

            goto early_err;

        }

        if (qdict_haskey(bs_opts, "driver")) {

            error_setg(errp, "Cannot specify both 'driver' and 'format'");

            goto early_err;

        }

        qdict_put(bs_opts, "driver", qstring_from_str(buf));

    }

    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;

    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {

        on_write_error = parse_block_error_action(buf, 0, &error);

        if (error) {

            error_propagate(errp, error);

            goto early_err;

        }

    }

    on_read_error = BLOCKDEV_ON_ERROR_REPORT;

    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {

        on_read_error = parse_block_error_action(buf, 1, &error);

        if (error) {

            error_propagate(errp, error);

            goto early_err;

        }

    }

    if (snapshot) {

        /* always use cache=unsafe with snapshot */

        bdrv_flags &= ~BDRV_O_CACHE_MASK;

        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);

    }

    /* init */

    if ((!file || !*file) && !has_driver_specific_opts) {

        BlockBackendRootState *blk_rs;

        blk = blk_new(qemu_opts_id(opts), errp);

        if (!blk) {

            goto early_err;

        }

        blk_rs = blk_get_root_state(blk);

        blk_rs->open_flags    = bdrv_flags;

        blk_rs->read_only     = !(bdrv_flags & BDRV_O_RDWR);

        blk_rs->detect_zeroes = detect_zeroes;

        if (throttle_enabled(&cfg)) {

            if (!throttling_group) {

                throttling_group = blk_name(blk);

            }

            blk_rs->throttle_group = g_strdup(throttling_group);

            blk_rs->throttle_state = throttle_group_incref(throttling_group);

            blk_rs->throttle_state->cfg = cfg;

        }

        QDECREF(bs_opts);

    } else {

        if (file && !*file) {

            file = NULL;

        }

        blk = blk_new_open(qemu_opts_id(opts), file, NULL, bs_opts, bdrv_flags,

                           errp);

        if (!blk) {

            goto err_no_bs_opts;

        }

        bs = blk_bs(blk);

        bs->detect_zeroes = detect_zeroes;

        /* disk I/O throttling */

        if (throttle_enabled(&cfg)) {

            if (!throttling_group) {

                throttling_group = blk_name(blk);

            }

            bdrv_io_limits_enable(bs, throttling_group);

            bdrv_set_io_limits(bs, &cfg);

        }

        if (bdrv_key_required(bs)) {

            autostart = 0;

        }

        block_acct_init(blk_get_stats(blk), account_invalid, account_failed);

    }

    blk_set_on_error(blk, on_read_error, on_write_error);

err_no_bs_opts:

    qemu_opts_del(opts);

    return blk;

early_err:

    qemu_opts_del(opts);

err_no_opts:

    QDECREF(bs_opts);

    return NULL;

}


static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,

                                        AVFilterInOut *in)

{

    AVFilterContext *last_filter;

    const AVFilter *buffer_filt = avfilter_get_by_name("buffer");

    InputStream *ist = ifilter->ist;

    InputFile     *f = input_files[ist->file_index];

    AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :

                                         ist->st->time_base;

    AVRational fr = ist->framerate;

    AVRational sar;

    AVBPrint args;

    char name[255];

    int ret, pad_idx = 0;

    int64_t tsoffset = 0;

    AVBufferSrcParameters *par = av_buffersrc_parameters_alloc();

    if (!par)

        return AVERROR(ENOMEM);

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

    par->format = AV_PIX_FMT_NONE;

    if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {

        av_log(NULL, AV_LOG_ERROR, "Cannot connect video filter to audio input\n");

        return AVERROR(EINVAL);

    }

    if (!fr.num)

        fr = av_guess_frame_rate(input_files[ist->file_index]->ctx, ist->st, NULL);

    if (ist->dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {

        ret = sub2video_prepare(ist);

        if (ret < 0)

            return ret;

    }

    sar = ist->st->sample_aspect_ratio.num ?

          ist->st->sample_aspect_ratio :

          ist->dec_ctx->sample_aspect_ratio;

    if(!sar.den)

        sar = (AVRational){0,1};

    av_bprint_init(&args, 0, 1);

    av_bprintf(&args,

             "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"

             "pixel_aspect=%d/%d:sws_param=flags=%d", ist->resample_width,

             ist->resample_height,

             ist->hwaccel_retrieve_data ? ist->hwaccel_retrieved_pix_fmt : ist->resample_pix_fmt,

             tb.num, tb.den, sar.num, sar.den,

             SWS_BILINEAR + ((ist->dec_ctx->flags&AV_CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));

    if (fr.num && fr.den)

        av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);

    snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,

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

    if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,

                                            args.str, NULL, fg->graph)) < 0)

        return ret;

    par->hw_frames_ctx = ist->hw_frames_ctx;

    ret = av_buffersrc_parameters_set(ifilter->filter, par);

    if (ret < 0)

        return ret;

    av_freep(&par);

    last_filter = ifilter->filter;

    if (ist->autorotate) {

        double theta = get_rotation(ist->st);

        if (fabs(theta - 90) < 1.0) {

            ret = insert_filter(&last_filter, &pad_idx, "transpose", "clock");

        } else if (fabs(theta - 180) < 1.0) {

            ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);

            if (ret < 0)

                return ret;

            ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);

        } else if (fabs(theta - 270) < 1.0) {

            ret = insert_filter(&last_filter, &pad_idx, "transpose", "cclock");

        } else if (fabs(theta) > 1.0) {

            char rotate_buf[64];

            snprintf(rotate_buf, sizeof(rotate_buf), "%f*PI/180", theta);

            ret = insert_filter(&last_filter, &pad_idx, "rotate", rotate_buf);

        }

        if (ret < 0)

            return ret;

    }

    if (ist->framerate.num) {

        AVFilterContext *setpts;

        snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",

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

        if ((ret = avfilter_graph_create_filter(&setpts,

                                                avfilter_get_by_name("setpts"),

                                                name, "N", NULL,

                                                fg->graph)) < 0)

            return ret;

        if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)

            return ret;

        last_filter = setpts;

    }

    if (do_deinterlace) {

        AVFilterContext *yadif;

        snprintf(name, sizeof(name), "deinterlace input from stream %d:%d",

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

        if ((ret = avfilter_graph_create_filter(&yadif,

                                                avfilter_get_by_name("yadif"),

                                                name, "", NULL,

                                                fg->graph)) < 0)

            return ret;

        if ((ret = avfilter_link(last_filter, 0, yadif, 0)) < 0)

            return ret;

        last_filter = yadif;

    }

    snprintf(name, sizeof(name), "trim for input stream %d:%d",

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

    if (copy_ts) {

        tsoffset = f->start_time == AV_NOPTS_VALUE ? 0 : f->start_time;

        if (!start_at_zero && f->ctx->start_time != AV_NOPTS_VALUE)

            tsoffset += f->ctx->start_time;

    }

    ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?

                      AV_NOPTS_VALUE : tsoffset, f->recording_time,

                      &last_filter, &pad_idx, name);

    if (ret < 0)

        return ret;

    if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)

        return ret;

    return 0;

}


static void do_video_stats(OutputStream *ost, int frame_size)

{

    AVCodecContext *enc;

    int frame_number;

    double ti1, bitrate, avg_bitrate;

    /* this is executed just the first time do_video_stats is called */

    if (!vstats_file) {

        vstats_file = fopen(vstats_filename, "w");

        if (!vstats_file) {

            perror("fopen");

            exit(1);

        }

    }

    enc = ost->st->codec;

    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {

        frame_number = ost->frame_number;

        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);

        if (enc->flags&CODEC_FLAG_PSNR)

            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));

        fprintf(vstats_file,"f_size= %6d ", frame_size);

        /* compute pts value */

        ti1 = ost->sync_opts * av_q2d(enc->time_base);

        if (ti1 < 0.01)

            ti1 = 0.01;

        bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;

        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;

        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",

               (double)video_size / 1024, ti1, bitrate, avg_bitrate);

        fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));

    }

}


void intra_predict(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb,

                   int mb_x, int mb_y)

{

    AVCodecContext *avctx = s->avctx;

    int x, y, mode, nnz, tr;

    // for the first row, we need to run xchg_mb_border to init the top edge to 127

    // otherwise, skip it if we aren't going to deblock

    if (!(avctx->flags & CODEC_FLAG_EMU_EDGE && !mb_y) && (s->deblock_filter || !mb_y))

        xchg_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2],

                       s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,

                       s->filter.simple, 1);

    if (mb->mode < MODE_I4x4) {

        if (avctx->flags & CODEC_FLAG_EMU_EDGE) { // tested

            mode = check_intra_pred8x8_mode_emuedge(mb->mode, mb_x, mb_y);

        } else {

            mode = check_intra_pred8x8_mode(mb->mode, mb_x, mb_y);

        }

        s->hpc.pred16x16[mode](dst[0], s->linesize);

    } else {

        uint8_t *ptr = dst[0];

        uint8_t *intra4x4 = s->intra4x4_pred_mode_mb;

        uint8_t tr_top[4] = { 127, 127, 127, 127 };

        // all blocks on the right edge of the macroblock use bottom edge

        // the top macroblock for their topright edge

        uint8_t *tr_right = ptr - s->linesize + 16;

        // if we're on the right edge of the frame, said edge is extended

        // from the top macroblock

        if (mb_x == s->mb_width-1) {

            tr = tr_right[-1]*0x01010101;

            tr_right = (uint8_t *)&tr;

        }

        if (mb->skip)

            AV_ZERO128(s->non_zero_count_cache);

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

            uint8_t *topright = ptr + 4 - s->linesize;

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

                int copy = 0, linesize = s->linesize;

                uint8_t *dst = ptr+4*x;

                DECLARE_ALIGNED(4, uint8_t, copy_dst)[5*8];

                if ((y == 0 || x == 3) && mb_y == 0 && avctx->flags & CODEC_FLAG_EMU_EDGE) {

                    topright = tr_top;

                } else if (x == 3)

                    topright = tr_right;

                if (avctx->flags & CODEC_FLAG_EMU_EDGE) { // mb_x+x or mb_y+y is a hack but works

                    mode = check_intra_pred4x4_mode_emuedge(intra4x4[x], mb_x + x, mb_y + y, &copy);

                    if (copy) {

                        dst = copy_dst + 12;

                        linesize = 8;

                        if (!(mb_y + y)) {

                            copy_dst[3] = 127U;

                            * (uint32_t *) (copy_dst + 4) = 127U * 0x01010101U;

                        } else {

                            * (uint32_t *) (copy_dst + 4) = * (uint32_t *) (ptr+4*x-s->linesize);

                            if (!(mb_x + x)) {

                                copy_dst[3] = 129U;

                            } else {

                                copy_dst[3] = ptr[4*x-s->linesize-1];

                            }

                        }

                        if (!(mb_x + x)) {

                            copy_dst[11] =

                            copy_dst[19] =

                            copy_dst[27] =

                            copy_dst[35] = 129U;

                        } else {

                            copy_dst[11] = ptr[4*x              -1];

                            copy_dst[19] = ptr[4*x+s->linesize  -1];

                            copy_dst[27] = ptr[4*x+s->linesize*2-1];

                            copy_dst[35] = ptr[4*x+s->linesize*3-1];

                        }

                    }

                } else {

                    mode = intra4x4[x];

                }

                s->hpc.pred4x4[mode](dst, topright, linesize);

                if (copy) {

                    * (uint32_t *) (ptr+4*x)               = * (uint32_t *) (copy_dst + 12);

                    * (uint32_t *) (ptr+4*x+s->linesize)   = * (uint32_t *) (copy_dst + 20);

                    * (uint32_t *) (ptr+4*x+s->linesize*2) = * (uint32_t *) (copy_dst + 28);

                    * (uint32_t *) (ptr+4*x+s->linesize*3) = * (uint32_t *) (copy_dst + 36);

                }

                nnz = s->non_zero_count_cache[y][x];

                if (nnz) {

                    if (nnz == 1)

                        s->vp8dsp.vp8_idct_dc_add(ptr+4*x, s->block[y][x], s->linesize);

                    else

                        s->vp8dsp.vp8_idct_add(ptr+4*x, s->block[y][x], s->linesize);

                }

                topright += 4;

            }

            ptr   += 4*s->linesize;

            intra4x4 += 4;

        }

    }

    if (avctx->flags & CODEC_FLAG_EMU_EDGE) {

        mode = check_intra_pred8x8_mode_emuedge(s->chroma_pred_mode, mb_x, mb_y);

    } else {

        mode = check_intra_pred8x8_mode(s->chroma_pred_mode, mb_x, mb_y);

    }

    s->hpc.pred8x8[mode](dst[1], s->uvlinesize);

    s->hpc.pred8x8[mode](dst[2], s->uvlinesize);

    if (!(avctx->flags & CODEC_FLAG_EMU_EDGE && !mb_y) && (s->deblock_filter || !mb_y))

        xchg_mb_border(s->top_border[mb_x+1], dst[0], dst[1], dst[2],

                       s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,

                       s->filter.simple, 0);

}


Aml *aml_buffer(void)

{

    Aml *var = aml_bundle(0x11 /* BufferOp */, AML_BUFFER);

    return var;

}


static hwaddr ppc_hash64_pteg_search(PowerPCCPU *cpu, hwaddr hash,

                                     ppc_slb_t *slb, target_ulong ptem,

                                     ppc_hash_pte64_t *pte)

{

    CPUPPCState *env = &cpu->env;

    int i;

    uint64_t token;

    target_ulong pte0, pte1;

    target_ulong pte_index;

    pte_index = (hash & env->htab_mask) * HPTES_PER_GROUP;

    token = ppc_hash64_start_access(cpu, pte_index);

    if (!token) {

        return -1;

    }

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

        pte0 = ppc_hash64_load_hpte0(cpu, token, i);

        pte1 = ppc_hash64_load_hpte1(cpu, token, i);

        /* This compares V, B, H (secondary) and the AVPN */

        if (HPTE64_V_COMPARE(pte0, ptem)) {

            unsigned pshift = hpte_page_shift(slb->sps, pte0, pte1);

            /*

             * If there is no match, ignore the PTE, it could simply

             * be for a different segment size encoding and the

             * architecture specifies we should not match. Linux will

             * potentially leave behind PTEs for the wrong base page

             * size when demoting segments.

             */

            if (pshift == 0) {

                continue;

            }

            /* We don't do anything with pshift yet as qemu TLB only deals

             * with 4K pages anyway

             */

            pte->pte0 = pte0;

            pte->pte1 = pte1;

            ppc_hash64_stop_access(cpu, token);

            return (pte_index + i) * HASH_PTE_SIZE_64;

        }

    }

    ppc_hash64_stop_access(cpu, token);

    /*

     * We didn't find a valid entry.

     */

    return -1;

}


static int qxl_init_common(PCIQXLDevice *qxl)

{

    uint8_t* config = qxl->pci.config;

    uint32_t pci_device_rev;

    uint32_t io_size;

    qxl->mode = QXL_MODE_UNDEFINED;

    qxl->generation = 1;

    qxl->num_memslots = NUM_MEMSLOTS;

    qemu_mutex_init(&qxl->track_lock);

    qemu_mutex_init(&qxl->async_lock);

    qxl->current_async = QXL_UNDEFINED_IO;

    qxl->guest_bug = 0;

    switch (qxl->revision) {

    case 1: /* spice 0.4 -- qxl-1 */

        pci_device_rev = QXL_REVISION_STABLE_V04;

        io_size = 8;

        break;

    case 2: /* spice 0.6 -- qxl-2 */

        pci_device_rev = QXL_REVISION_STABLE_V06;

        io_size = 16;

        break;

    case 3: /* qxl-3 */

        pci_device_rev = QXL_REVISION_STABLE_V10;

        io_size = 32; /* PCI region size must be pow2 */

        break;

/* 0x000b01 == 0.11.1 */

#if SPICE_SERVER_VERSION >= 0x000b01 && \

        defined(CONFIG_QXL_IO_MONITORS_CONFIG_ASYNC)

    case 4: /* qxl-4 */

        pci_device_rev = QXL_REVISION_STABLE_V12;

        io_size = msb_mask(QXL_IO_RANGE_SIZE * 2 - 1);

        break;

#endif

    default:

        error_report("Invalid revision %d for qxl device (max %d)",

                     qxl->revision, QXL_DEFAULT_REVISION);

        return -1;

    }

    pci_set_byte(&config[PCI_REVISION_ID], pci_device_rev);

    pci_set_byte(&config[PCI_INTERRUPT_PIN], 1);

    qxl->rom_size = qxl_rom_size();

    memory_region_init_ram(&qxl->rom_bar, "qxl.vrom", qxl->rom_size);

    vmstate_register_ram(&qxl->rom_bar, &qxl->pci.qdev);

    init_qxl_rom(qxl);

    init_qxl_ram(qxl);

    qxl->guest_surfaces.cmds = g_new0(QXLPHYSICAL, qxl->ssd.num_surfaces);

    memory_region_init_ram(&qxl->vram_bar, "qxl.vram", qxl->vram_size);

    vmstate_register_ram(&qxl->vram_bar, &qxl->pci.qdev);

    memory_region_init_alias(&qxl->vram32_bar, "qxl.vram32", &qxl->vram_bar,

                             0, qxl->vram32_size);

    memory_region_init_io(&qxl->io_bar, &qxl_io_ops, qxl,

                          "qxl-ioports", io_size);

    if (qxl->id == 0) {

        vga_dirty_log_start(&qxl->vga);

    }

    memory_region_set_flush_coalesced(&qxl->io_bar);

    pci_register_bar(&qxl->pci, QXL_IO_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_IO, &qxl->io_bar);

    pci_register_bar(&qxl->pci, QXL_ROM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->rom_bar);

    pci_register_bar(&qxl->pci, QXL_RAM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vga.vram);

    pci_register_bar(&qxl->pci, QXL_VRAM_RANGE_INDEX,

                     PCI_BASE_ADDRESS_SPACE_MEMORY, &qxl->vram32_bar);

    if (qxl->vram32_size < qxl->vram_size) {

        /*

         * Make the 64bit vram bar show up only in case it is

         * configured to be larger than the 32bit vram bar.

         */

        pci_register_bar(&qxl->pci, QXL_VRAM64_RANGE_INDEX,

                         PCI_BASE_ADDRESS_SPACE_MEMORY |

                         PCI_BASE_ADDRESS_MEM_TYPE_64 |

                         PCI_BASE_ADDRESS_MEM_PREFETCH,

                         &qxl->vram_bar);

    }

    /* print pci bar details */

    dprint(qxl, 1, "ram/%s: %d MB [region 0]\n",

           qxl->id == 0 ? "pri" : "sec",

           qxl->vga.vram_size / (1024*1024));

    dprint(qxl, 1, "vram/32: %d MB [region 1]\n",

           qxl->vram32_size / (1024*1024));

    dprint(qxl, 1, "vram/64: %d MB %s\n",

           qxl->vram_size / (1024*1024),

           qxl->vram32_size < qxl->vram_size ? "[region 4]" : "[unmapped]");

    qxl->ssd.qxl.base.sif = &qxl_interface.base;

    qxl->ssd.qxl.id = qxl->id;

    qemu_spice_add_interface(&qxl->ssd.qxl.base);

    qemu_add_vm_change_state_handler(qxl_vm_change_state_handler, qxl);

    init_pipe_signaling(qxl);

    qxl_reset_state(qxl);

    qxl->update_area_bh = qemu_bh_new(qxl_render_update_area_bh, qxl);

    return 0;

}


static void create_header64(DumpState *s, Error **errp)
{
    DiskDumpHeader64 *dh = NULL;
    KdumpSubHeader64 *kh = NULL;
    size_t size;
    uint32_t block_size;
    uint32_t sub_hdr_size;
    uint32_t bitmap_blocks;
    uint32_t status = 0;
    uint64_t offset_note;
    Error *local_err = NULL;
    /* write common header, the version of kdump-compressed format is 6th */
    size = sizeof(DiskDumpHeader64);
    dh = g_malloc0(size);
    strncpy(dh->signature, KDUMP_SIGNATURE, strlen(KDUMP_SIGNATURE));
    dh->header_version = cpu_to_dump32(s, 6);
    block_size = s->dump_info.page_size;
    dh->block_size = cpu_to_dump32(s, block_size);
    sub_hdr_size = sizeof(struct KdumpSubHeader64) + s->note_size;
    sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);
    dh->sub_hdr_size = cpu_to_dump32(s, sub_hdr_size);
    /* dh->max_mapnr may be truncated, full 64bit is in kh.max_mapnr_64 */
    dh->max_mapnr = cpu_to_dump32(s, MIN(s->max_mapnr, UINT_MAX));
    dh->nr_cpus = cpu_to_dump32(s, s->nr_cpus);
    bitmap_blocks = DIV_ROUND_UP(s->len_dump_bitmap, block_size) * 2;
    dh->bitmap_blocks = cpu_to_dump32(s, bitmap_blocks);
    strncpy(dh->utsname.machine, ELF_MACHINE_UNAME, sizeof(dh->utsname.machine));
    if (s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) {
        status |= DUMP_DH_COMPRESSED_ZLIB;
#ifdef CONFIG_LZO
    if (s->flag_compress & DUMP_DH_COMPRESSED_LZO) {
        status |= DUMP_DH_COMPRESSED_LZO;
#endif
#ifdef CONFIG_SNAPPY
    if (s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) {
        status |= DUMP_DH_COMPRESSED_SNAPPY;
#endif
    dh->status = cpu_to_dump32(s, status);
    if (write_buffer(s->fd, 0, dh, size) < 0) {
        error_setg(errp, "dump: failed to write disk dump header");
        goto out;
    /* write sub header */
    size = sizeof(KdumpSubHeader64);
    kh = g_malloc0(size);
    /* 64bit max_mapnr_64 */
    kh->max_mapnr_64 = cpu_to_dump64(s, s->max_mapnr);
    kh->phys_base = cpu_to_dump64(s, s->dump_info.phys_base);
    kh->dump_level = cpu_to_dump32(s, DUMP_LEVEL);
    offset_note = DISKDUMP_HEADER_BLOCKS * block_size + size;
    kh->offset_note = cpu_to_dump64(s, offset_note);
    kh->note_size = cpu_to_dump64(s, s->note_size);
    if (write_buffer(s->fd, DISKDUMP_HEADER_BLOCKS *
                     block_size, kh, size) < 0) {
        error_setg(errp, "dump: failed to write kdump sub header");
        goto out;
    /* write note */
    s->note_buf = g_malloc0(s->note_size);
    s->note_buf_offset = 0;
    /* use s->note_buf to store notes temporarily */
    write_elf64_notes(buf_write_note, s, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        goto out;
    if (write_buffer(s->fd, offset_note, s->note_buf,
                     s->note_size) < 0) {
        error_setg(errp, "dump: failed to write notes");
        goto out;
    /* get offset of dump_bitmap */
    s->offset_dump_bitmap = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size) *
                             block_size;
    /* get offset of page */
    s->offset_page = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size + bitmap_blocks) *
                     block_size;
out:
    g_free(dh);
    g_free(kh);
    g_free(s->note_buf);


static void test_rtas_get_time_of_day(void)

{

    QOSState *qs;

    struct tm tm;

    uint32_t ns;

    uint64_t ret;

    time_t t1, t2;

    qs = qtest_spapr_boot("-machine pseries");

    g_assert(qs != NULL);

    t1 = time(NULL);

    ret = qrtas_get_time_of_day(qs->alloc, &tm, &ns);

    g_assert_cmpint(ret, ==, 0);

    t2 = mktimegm(&tm);

    g_assert(t2 - t1 < 5); /* 5 sec max to run the test */

    qtest_shutdown(qs);

}


int qemu_opts_set(QemuOptsList *list, const char *id,

                  const char *name, const char *value)

{

    QemuOpts *opts;

    opts = qemu_opts_create(list, id, 1);

    if (opts == NULL) {

        return -1;

    }

    return qemu_opt_set(opts, name, value);

}


static int parse_icy(HTTPContext *s, const char *tag, const char *p)
{
    int len = 4 + strlen(p) + strlen(tag);
    int is_first = !s->icy_metadata_headers;
    int ret;
    if (s->icy_metadata_headers)
        len += strlen(s->icy_metadata_headers);
    if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
        return ret;
    av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
    return 0;
}


static av_cold void decode_init_vlc(void){

    static int done = 0;

    if (!done) {

        int i;

        done = 1;

        init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,

                 &chroma_dc_coeff_token_len [0], 1, 1,

                 &chroma_dc_coeff_token_bits[0], 1, 1, 1);

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

            init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,

                     &coeff_token_len [i][0], 1, 1,

                     &coeff_token_bits[i][0], 1, 1, 1);

        }

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

            init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,

                     &chroma_dc_total_zeros_len [i][0], 1, 1,

                     &chroma_dc_total_zeros_bits[i][0], 1, 1, 1);

        }

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

            init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16,

                     &total_zeros_len [i][0], 1, 1,

                     &total_zeros_bits[i][0], 1, 1, 1);

        }

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

            init_vlc(&run_vlc[i], RUN_VLC_BITS, 7,

                     &run_len [i][0], 1, 1,

                     &run_bits[i][0], 1, 1, 1);

        }

        init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,

                 &run_len [6][0], 1, 1,

                 &run_bits[6][0], 1, 1, 1);

    }

}


static USBDevice *usb_serial_init(USBBus *bus, const char *filename)

{

    USBDevice *dev;

    CharDriverState *cdrv;

    uint32_t vendorid = 0, productid = 0;

    char label[32];

    static int index;

    while (*filename && *filename != ':') {

        const char *p;

        char *e;

        if (strstart(filename, "vendorid=", &p)) {

            vendorid = strtol(p, &e, 16);

            if (e == p || (*e && *e != ',' && *e != ':')) {

                error_report("bogus vendor ID %s", p);

                return NULL;

            }

            filename = e;

        } else if (strstart(filename, "productid=", &p)) {

            productid = strtol(p, &e, 16);

            if (e == p || (*e && *e != ',' && *e != ':')) {

                error_report("bogus product ID %s", p);

                return NULL;

            }

            filename = e;

        } else {

            error_report("unrecognized serial USB option %s", filename);

            return NULL;

        }

        while(*filename == ',')

            filename++;

    }

    if (!*filename) {

        error_report("character device specification needed");

        return NULL;

    }

    filename++;

    snprintf(label, sizeof(label), "usbserial%d", index++);

    cdrv = qemu_chr_new(label, filename, NULL);

    if (!cdrv)

        return NULL;

    dev = usb_create(bus, "usb-serial");

    qdev_prop_set_chr(&dev->qdev, "chardev", cdrv);

    if (vendorid)

        qdev_prop_set_uint16(&dev->qdev, "vendorid", vendorid);

    if (productid)

        qdev_prop_set_uint16(&dev->qdev, "productid", productid);

    qdev_init_nofail(&dev->qdev);

    return dev;

}


static int32_t virtio_net_flush_tx(VirtIONet *n, VirtQueue *vq)

{

    VirtQueueElement elem;

    int32_t num_packets = 0;

    if (!(n->vdev.status & VIRTIO_CONFIG_S_DRIVER_OK)) {

        return num_packets;

    }

    if (n->async_tx.elem.out_num) {

        virtio_queue_set_notification(n->tx_vq, 0);

        return num_packets;

    }

    while (virtqueue_pop(vq, &elem)) {

        ssize_t ret, len = 0;

        unsigned int out_num = elem.out_num;

        struct iovec *out_sg = &elem.out_sg[0];

        unsigned hdr_len;

        /* hdr_len refers to the header received from the guest */

        hdr_len = n->mergeable_rx_bufs ?

            sizeof(struct virtio_net_hdr_mrg_rxbuf) :

            sizeof(struct virtio_net_hdr);

        if (out_num < 1 || out_sg->iov_len != hdr_len) {

            error_report("virtio-net header not in first element");

            exit(1);

        }

        /* ignore the header if GSO is not supported */

        if (!n->has_vnet_hdr) {

            out_num--;

            out_sg++;

            len += hdr_len;

        } else if (n->mergeable_rx_bufs) {

            /* tapfd expects a struct virtio_net_hdr */

            hdr_len -= sizeof(struct virtio_net_hdr);

            out_sg->iov_len -= hdr_len;

            len += hdr_len;

        }

        ret = qemu_sendv_packet_async(&n->nic->nc, out_sg, out_num,

                                      virtio_net_tx_complete);

        if (ret == 0) {

            virtio_queue_set_notification(n->tx_vq, 0);

            n->async_tx.elem = elem;

            n->async_tx.len  = len;

            return -EBUSY;

        }

        len += ret;

        virtqueue_push(vq, &elem, len);

        virtio_notify(&n->vdev, vq);

        if (++num_packets >= n->tx_burst) {

            break;

        }

    }

    return num_packets;

}


static int vmdk_read(BlockDriverState *bs, int64_t sector_num,

                    uint8_t *buf, int nb_sectors)

{

    BDRVVmdkState *s = bs->opaque;

    int ret;

    uint64_t n, index_in_cluster;

    VmdkExtent *extent = NULL;

    uint64_t cluster_offset;

    while (nb_sectors > 0) {

        extent = find_extent(s, sector_num, extent);

        if (!extent) {

            return -EIO;

        }

        ret = get_cluster_offset(

                            bs, extent, NULL,

                            sector_num << 9, 0, &cluster_offset);

        index_in_cluster = sector_num % extent->cluster_sectors;

        n = extent->cluster_sectors - index_in_cluster;

        if (n > nb_sectors) {

            n = nb_sectors;

        }

        if (ret) {

            /* if not allocated, try to read from parent image, if exist */

            if (bs->backing_hd) {

                if (!vmdk_is_cid_valid(bs)) {

                    return -EINVAL;

                }

                ret = bdrv_read(bs->backing_hd, sector_num, buf, n);

                if (ret < 0) {

                    return ret;

                }

            } else {

                memset(buf, 0, 512 * n);

            }

        } else {

            ret = vmdk_read_extent(extent,

                            cluster_offset, index_in_cluster * 512,

                            buf, n);

            if (ret) {

                return ret;

            }

        }

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

    }

    return 0;

}


static void gen_mfsr(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    t0 = tcg_const_tl(SR(ctx->opcode));

    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

#endif

}


void fd_start_incoming_migration(const char *infd, Error **errp)

{

    int fd;

    QEMUFile *f;

    DPRINTF("Attempting to start an incoming migration via fd\n");

    fd = strtol(infd, NULL, 0);

    f = qemu_fdopen(fd, "rb");

    if(f == NULL) {

        error_setg_errno(errp, errno, "failed to open the source descriptor");

        return;

    }

    qemu_set_fd_handler2(fd, NULL, fd_accept_incoming_migration, NULL, f);

}


int cpu_ppc_handle_mmu_fault (CPUState *env, target_ulong address, int rw,

                              int mmu_idx, int is_softmmu)

{

    mmu_ctx_t ctx;

    int access_type;

    int ret = 0;

    if (rw == 2) {

        /* code access */

        rw = 0;

        access_type = ACCESS_CODE;

    } else {

        /* data access */

        /* XXX: put correct access by using cpu_restore_state()

           correctly */

        access_type = ACCESS_INT;

        //        access_type = env->access_type;

    }

    ret = get_physical_address(env, &ctx, address, rw, access_type, 1);

    if (ret == 0) {

        ret = tlb_set_page_exec(env, address & TARGET_PAGE_MASK,

                                ctx.raddr & TARGET_PAGE_MASK, ctx.prot,

                                mmu_idx, is_softmmu);

    } else if (ret < 0) {

#if defined (DEBUG_MMU)

        if (loglevel != 0)

            cpu_dump_state(env, logfile, fprintf, 0);

#endif

        if (access_type == ACCESS_CODE) {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    env->error_code = 1 << 18;

                    env->spr[SPR_IMISS] = address;

                    env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;

                    goto tlb_miss;

                case POWERPC_MMU_SOFT_74xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    goto tlb_miss_74xx;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_ITLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    env->spr[SPR_40x_ESR] = 0x00000000;

                    break;

                case POWERPC_MMU_32B:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_64B:

#endif

                    env->exception_index = POWERPC_EXCP_ISI;

                    env->error_code = 0x40000000;

                    break;

                case POWERPC_MMU_BOOKE:

                    /* XXX: TODO */

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

                    return -1;

                case POWERPC_MMU_BOOKE_FSL:

                    /* XXX: TODO */

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

                    return -1;

                case POWERPC_MMU_REAL_4xx:

                    cpu_abort(env, "PowerPC 401 should never raise any MMU "

                              "exceptions\n");

                    return -1;

                default:

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

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x08000000;

                break;

            case -3:

                /* No execute protection violation */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

            case -4:

                /* Direct store exception */

                /* No code fetch is allowed in direct-store areas */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                env->exception_index = POWERPC_EXCP_ISEG;

                env->error_code = 0;

                break;

#endif

            }

        } else {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                        env->error_code = 1 << 16;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                        env->error_code = 0;

                    }

                    env->spr[SPR_DMISS] = address;

                    env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;

                tlb_miss:

                    env->error_code |= ctx.key << 19;

                    env->spr[SPR_HASH1] = ctx.pg_addr[0];

                    env->spr[SPR_HASH2] = ctx.pg_addr[1];

                    break;

                case POWERPC_MMU_SOFT_74xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                    }

                tlb_miss_74xx:

                    /* Implement LRU algorithm */

                    env->error_code = ctx.key << 19;

                    env->spr[SPR_TLBMISS] = (address & ~((target_ulong)0x3)) |

                        ((env->last_way + 1) & (env->nb_ways - 1));

                    env->spr[SPR_PTEHI] = 0x80000000 | ctx.ptem;

                    break;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_DTLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    if (rw)

                        env->spr[SPR_40x_ESR] = 0x00800000;

                    else

                        env->spr[SPR_40x_ESR] = 0x00000000;

                    break;

                case POWERPC_MMU_32B:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_64B:

#endif

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x42000000;

                    else

                        env->spr[SPR_DSISR] = 0x40000000;

                    break;

                case POWERPC_MMU_BOOKE:

                    /* XXX: TODO */

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

                    return -1;

                case POWERPC_MMU_BOOKE_FSL:

                    /* XXX: TODO */

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

                    return -1;

                case POWERPC_MMU_REAL_4xx:

                    cpu_abort(env, "PowerPC 401 should never raise any MMU "

                              "exceptions\n");

                    return -1;

                default:

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

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_DSI;

                env->error_code = 0;

                env->spr[SPR_DAR] = address;

                if (rw == 1)

                    env->spr[SPR_DSISR] = 0x0A000000;

                else

                    env->spr[SPR_DSISR] = 0x08000000;

                break;

            case -4:

                /* Direct store exception */

                switch (access_type) {

                case ACCESS_FLOAT:

                    /* Floating point load/store */

                    env->exception_index = POWERPC_EXCP_ALIGN;

                    env->error_code = POWERPC_EXCP_ALIGN_FP;

                    env->spr[SPR_DAR] = address;

                    break;

                case ACCESS_RES:

                    /* lwarx, ldarx or stwcx. */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x06000000;

                    else

                        env->spr[SPR_DSISR] = 0x04000000;

                    break;

                case ACCESS_EXT:

                    /* eciwx or ecowx */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x06100000;

                    else

                        env->spr[SPR_DSISR] = 0x04100000;

                    break;

                default:

                    printf("DSI: invalid exception (%d)\n", ret);

                    env->exception_index = POWERPC_EXCP_PROGRAM;

                    env->error_code =

                        POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL;

                    env->spr[SPR_DAR] = address;

                    break;

                }

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                env->exception_index = POWERPC_EXCP_DSEG;

                env->error_code = 0;

                env->spr[SPR_DAR] = address;

                break;

#endif

            }

        }

#if 0

        printf("%s: set exception to %d %02x\n", __func__,

               env->exception, env->error_code);

#endif

        ret = 1;

    }

    return ret;

}


void do_POWER_rac (void)

{

#if 0

    mmu_ctx_t ctx;

    /* We don't have to generate many instances of this instruction,

     * as rac is supervisor only.

     */

    if (get_physical_address(env, &ctx, T0, 0, ACCESS_INT, 1) == 0)

        T0 = ctx.raddr;

#endif

}


hwaddr s390_cpu_get_phys_page_debug(CPUState *cs, vaddr vaddr)

{

    S390CPU *cpu = S390_CPU(cs);

    CPUS390XState *env = &cpu->env;

    target_ulong raddr;

    int prot;

    uint64_t asc = env->psw.mask & PSW_MASK_ASC;

    /* 31-Bit mode */

    if (!(env->psw.mask & PSW_MASK_64)) {

        vaddr &= 0x7fffffff;

    }

    mmu_translate(env, vaddr, MMU_INST_FETCH, asc, &raddr, &prot, false);

    return raddr;

}


static void msix_handle_mask_update(PCIDevice *dev, int vector)

{

    if (!msix_is_masked(dev, vector) && msix_is_pending(dev, vector)) {

        msix_clr_pending(dev, vector);

        msix_notify(dev, vector);

    }

}


static int dct_quantize_c(MpegEncContext *s,

                        DCTELEM *block, int n,

                        int qscale, int *overflow)

{

    int i, j, level, last_non_zero, q;

    const int *qmat;

    int bias;

    int max=0;

    unsigned int threshold1, threshold2;

    av_fdct (block);

    /* we need this permutation so that we correct the IDCT

       permutation. will be moved into DCT code */

    block_permute(block);

    if (s->mb_intra) {

        if (!s->h263_aic) {

            if (n < 4)

                q = s->y_dc_scale;

            else

                q = s->c_dc_scale;

            q = q << 3;

        } else

            /* For AIC we skip quant/dequant of INTRADC */

            q = 1 << 3;

        /* note: block[0] is assumed to be positive */

        block[0] = (block[0] + (q >> 1)) / q;

        i = 1;

        last_non_zero = 0;

        qmat = s->q_intra_matrix[qscale];

        bias= s->intra_quant_bias<<(QMAT_SHIFT - 3 - QUANT_BIAS_SHIFT);

    } else {

        i = 0;

        last_non_zero = -1;

        qmat = s->q_inter_matrix[qscale];

        bias= s->inter_quant_bias<<(QMAT_SHIFT - 3 - QUANT_BIAS_SHIFT);

    }

    threshold1= (1<<(QMAT_SHIFT - 3)) - bias - 1;

    threshold2= threshold1<<1;

    for(;i<64;i++) {

        j = zigzag_direct[i];

        level = block[j];

        level = level * qmat[j];

//        if(   bias+level >= (1<<(QMAT_SHIFT - 3))

//           || bias-level >= (1<<(QMAT_SHIFT - 3))){

        if(((unsigned)(level+threshold1))>threshold2){

            if(level>0){

                level= (bias + level)>>(QMAT_SHIFT - 3);

                block[j]= level;

            }else{

                level= (bias - level)>>(QMAT_SHIFT - 3);

                block[j]= -level;

            }

            max |=level;

            last_non_zero = i;

        }else{

            block[j]=0;

        }

    }

    *overflow= s->max_qcoeff < max; //overflow might have happend

    return last_non_zero;

}


static void radix_sort(RCCMPEntry *data, int size)

{

    int buckets[RADIX_PASSES][NBUCKETS];

    RCCMPEntry *tmp = av_malloc_array(size, sizeof(*tmp));

    radix_count(data, size, buckets);

    radix_sort_pass(tmp, data, size, buckets[0], 0);

    radix_sort_pass(data, tmp, size, buckets[1], 1);

    if (buckets[2][NBUCKETS - 1] || buckets[3][NBUCKETS - 1]) {

        radix_sort_pass(tmp, data, size, buckets[2], 2);

        radix_sort_pass(data, tmp, size, buckets[3], 3);

    }

    av_free(tmp);

}


static inline void mix_3f_1r_to_stereo(AC3DecodeContext *ctx)

{

    int i;

    float (*output)[256] = ctx->audio_block.block_output;

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

        output[1][i] += (output[2][i] + output[4][i]);

        output[2][i] += (output[3][i] + output[4][i]);

    }

    memset(output[3], 0, sizeof(output[3]));

    memset(output[4], 0, sizeof(output[4]));

}


static int check(AVIOContext *pb, int64_t pos, uint32_t *ret_header)

{

    int64_t ret = avio_seek(pb, pos, SEEK_SET);

    unsigned header;

    MPADecodeHeader sd;

    if (ret < 0)

        return ret;

    header = avio_rb32(pb);

    if (ff_mpa_check_header(header) < 0)

        return -1;

    if (avpriv_mpegaudio_decode_header(&sd, header) == 1)

        return -1;

    if (ret_header)

        *ret_header = header;

    return sd.frame_size;

}


void ff_put_h264_qpel4_mc30_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_hz_qrt_4w_msa(src - 2, stride, dst, stride, 4, 1);

}