static void tricore_testboard_init(MachineState *machine, int board_id)

{

    TriCoreCPU *cpu;

    CPUTriCoreState *env;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ext_cram = g_new(MemoryRegion, 1);

    MemoryRegion *ext_dram = g_new(MemoryRegion, 1);

    MemoryRegion *int_cram = g_new(MemoryRegion, 1);

    MemoryRegion *int_dram = g_new(MemoryRegion, 1);

    MemoryRegion *pcp_data = g_new(MemoryRegion, 1);

    MemoryRegion *pcp_text = g_new(MemoryRegion, 1);

    if (!machine->cpu_model) {

        machine->cpu_model = "tc1796";

    }

    cpu = cpu_tricore_init(machine->cpu_model);

    env = &cpu->env;

    if (!cpu) {

        error_report("Unable to find CPU definition");

        exit(1);

    }

    memory_region_init_ram(ext_cram, NULL, "powerlink_ext_c.ram", 2*1024*1024, &error_abort);

    vmstate_register_ram_global(ext_cram);

    memory_region_init_ram(ext_dram, NULL, "powerlink_ext_d.ram", 4*1024*1024, &error_abort);

    vmstate_register_ram_global(ext_dram);

    memory_region_init_ram(int_cram, NULL, "powerlink_int_c.ram", 48*1024, &error_abort);

    vmstate_register_ram_global(int_cram);

    memory_region_init_ram(int_dram, NULL, "powerlink_int_d.ram", 48*1024, &error_abort);

    vmstate_register_ram_global(int_dram);

    memory_region_init_ram(pcp_data, NULL, "powerlink_pcp_data.ram", 16*1024, &error_abort);

    vmstate_register_ram_global(pcp_data);

    memory_region_init_ram(pcp_text, NULL, "powerlink_pcp_text.ram", 32*1024, &error_abort);

    vmstate_register_ram_global(pcp_text);

    memory_region_add_subregion(sysmem, 0x80000000, ext_cram);

    memory_region_add_subregion(sysmem, 0xa1000000, ext_dram);

    memory_region_add_subregion(sysmem, 0xd4000000, int_cram);

    memory_region_add_subregion(sysmem, 0xd0000000, int_dram);

    memory_region_add_subregion(sysmem, 0xf0050000, pcp_data);

    memory_region_add_subregion(sysmem, 0xf0060000, pcp_text);

    tricoretb_binfo.ram_size = machine->ram_size;

    tricoretb_binfo.kernel_filename = machine->kernel_filename;

    if (machine->kernel_filename) {

        tricore_load_kernel(env);

    }

}


static uint64_t pxa2xx_cm_read(void *opaque, hwaddr addr,

                               unsigned size)

{

    PXA2xxState *s = (PXA2xxState *) opaque;

    switch (addr) {

    case CCCR:

    case CKEN:

    case OSCC:

        return s->cm_regs[addr >> 2];

    case CCSR:

        return s->cm_regs[CCCR >> 2] | (3 << 28);

    default:

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

        break;

    }

    return 0;

}


static int mxf_write_header_metadata_sets(AVFormatContext *s)

{

    AVStream *st;

    MXFStreamContext *sc = NULL;

    int i;

    mxf_write_preface(s);

    mxf_write_identification(s);

    mxf_write_content_storage(s);

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

        st = s->streams[i];

        sc = av_mallocz(sizeof(MXFStreamContext));

        if (!sc)

            return AVERROR(ENOMEM);

        st->priv_data = sc;

        // set pts information

        if (st->codec->codec_type == CODEC_TYPE_VIDEO)

            av_set_pts_info(st, 64, 1, st->codec->time_base.den);

        else if (st->codec->codec_type == CODEC_TYPE_AUDIO)

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

    }

    mxf_build_structural_metadata(s, MaterialPackage);

    mxf_build_structural_metadata(s, SourcePackage);

    return 0;

}


int av_opencl_buffer_write_image(cl_mem dst_cl_buf, size_t cl_buffer_size, int dst_cl_offset,

                                                    uint8_t **src_data, int *plane_size, int plane_num)

{

    int i, buffer_size = 0;

    uint8_t *temp;

    cl_int status;

    void *mapped;

    if ((unsigned int)plane_num > 8) {

        return AVERROR(EINVAL);

    }

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

        buffer_size += plane_size[i];

    }

    if (buffer_size > cl_buffer_size) {

        av_log(&openclutils, AV_LOG_ERROR, "Cannot write image to OpenCL buffer: buffer too small\n");

        return AVERROR(EINVAL);

    }

    mapped = clEnqueueMapBuffer(gpu_env.command_queue, dst_cl_buf,

                                      CL_TRUE,CL_MAP_WRITE, 0, buffer_size + dst_cl_offset,

                                      0, NULL, NULL, &status);

    if (status != CL_SUCCESS) {

        av_log(&openclutils, AV_LOG_ERROR, "Could not map OpenCL buffer: %s\n", opencl_errstr(status));

        return AVERROR_EXTERNAL;

    }

    temp = mapped;

    temp += dst_cl_offset;

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

        memcpy(temp, src_data[i], plane_size[i]);

        temp += plane_size[i];

    }

    status = clEnqueueUnmapMemObject(gpu_env.command_queue, dst_cl_buf, mapped, 0, NULL, NULL);

    if (status != CL_SUCCESS) {

        av_log(&openclutils, AV_LOG_ERROR, "Could not unmap OpenCL buffer: %s\n", opencl_errstr(status));

        return AVERROR_EXTERNAL;

    }

    return 0;

}


int ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size)

{

    int id;

    id = avio_rl16(pb);

    codec->codec_type = AVMEDIA_TYPE_AUDIO;

    codec->channels = avio_rl16(pb);

    codec->sample_rate = avio_rl32(pb);

    codec->bit_rate = avio_rl32(pb) * 8;

    codec->block_align = avio_rl16(pb);

    if (size == 14) {  /* We're dealing with plain vanilla WAVEFORMAT */

        codec->bits_per_coded_sample = 8;

    }else

        codec->bits_per_coded_sample = avio_rl16(pb);

    if (id == 0xFFFE) {

        codec->codec_tag = 0;

    } else {

        codec->codec_tag = id;

        codec->codec_id = ff_wav_codec_get_id(id, codec->bits_per_coded_sample);

    }

    if (size >= 18) {  /* We're obviously dealing with WAVEFORMATEX */

        int cbSize = avio_rl16(pb); /* cbSize */

        size -= 18;

        cbSize = FFMIN(size, cbSize);

        if (cbSize >= 22 && id == 0xfffe) { /* WAVEFORMATEXTENSIBLE */

            ff_asf_guid subformat;

            codec->bits_per_coded_sample = avio_rl16(pb);

            codec->channel_layout = avio_rl32(pb); /* dwChannelMask */

            ff_get_guid(pb, &subformat);

            if (!memcmp(subformat + 4, (const uint8_t[]){FF_MEDIASUBTYPE_BASE_GUID}, 12)) {

                codec->codec_tag = AV_RL32(subformat);

                codec->codec_id = ff_wav_codec_get_id(codec->codec_tag, codec->bits_per_coded_sample);

            } else {

                codec->codec_id = ff_codec_guid_get_id(ff_codec_wav_guids, subformat);

                if (!codec->codec_id)

                    av_log(codec, AV_LOG_WARNING, "unknown subformat:"FF_PRI_GUID"\n", FF_ARG_GUID(subformat));

            }

            cbSize -= 22;

            size -= 22;

        }

        codec->extradata_size = cbSize;

        if (cbSize > 0) {

            av_free(codec->extradata);

            codec->extradata = av_mallocz(codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!codec->extradata)

                return AVERROR(ENOMEM);

            avio_read(pb, codec->extradata, codec->extradata_size);

            size -= cbSize;

        }

        /* It is possible for the chunk to contain garbage at the end */

        if (size > 0)

            avio_skip(pb, size);

    }

    if (codec->codec_id == CODEC_ID_AAC_LATM) {

        /* channels and sample_rate values are those prior to applying SBR and/or PS */

        codec->channels    = 0;

        codec->sample_rate = 0;

    }

    /* override bits_per_coded_sample for G.726 */

    if (codec->codec_id == CODEC_ID_ADPCM_G726)

        codec->bits_per_coded_sample = codec->bit_rate / codec->sample_rate;

    return 0;

}


static int r3d_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    R3DContext *r3d = s->priv_data;

    Atom atom;

    int err = 0;

    while (!err) {

        if (read_atom(s, &atom) < 0) {

            err = -1;

            break;

        }

        switch (atom.tag) {

        case MKTAG('R','E','D','V'):

            if (s->streams[0]->discard == AVDISCARD_ALL)

                goto skip;

            if (!(err = r3d_read_redv(s, pkt, &atom)))

                return 0;

            break;

        case MKTAG('R','E','D','A'):

            if (!r3d->audio_channels)

                return -1;

            if (s->streams[1]->discard == AVDISCARD_ALL)

                goto skip;

            if (!(err = r3d_read_reda(s, pkt, &atom)))

                return 0;

            break;

        default:

        skip:

            avio_skip(s->pb, atom.size-8);

        }

    }

    return err;

}


PPC_OP(test_ctrz_true)

{

    T0 = (regs->ctr == 0 && (T0 & PARAM(1)) != 0);

    RETURN();

}


static void monitor_control_event(void *opaque, int event)

{

    if (event == CHR_EVENT_OPENED) {

        QObject *data;

        Monitor *mon = opaque;

        mon->mc->command_mode = 0;

        json_message_parser_init(&mon->mc->parser, handle_qmp_command);

        data = get_qmp_greeting();

        monitor_json_emitter(mon, data);

        qobject_decref(data);

    }

}


void cpu_ppc_reset (void *opaque)

{

    CPUPPCState *env;

    target_ulong msr;

    env = opaque;

    msr = (target_ulong)0;

#if defined(TARGET_PPC64)

    msr |= (target_ulong)0 << MSR_HV; /* Should be 1... */

#endif

    msr |= (target_ulong)0 << MSR_AP; /* TO BE CHECKED */

    msr |= (target_ulong)0 << MSR_SA; /* TO BE CHECKED */

    msr |= (target_ulong)1 << MSR_EP;

#if defined (DO_SINGLE_STEP) && 0

    /* Single step trace mode */

    msr |= (target_ulong)1 << MSR_SE;

    msr |= (target_ulong)1 << MSR_BE;

#endif

#if defined(CONFIG_USER_ONLY)

    msr |= (target_ulong)1 << MSR_FP; /* Allow floating point usage */

    msr |= (target_ulong)1 << MSR_PR;

#else

    env->nip = env->hreset_vector | env->excp_prefix;

    if (env->mmu_model != POWERPC_MMU_REAL_4xx)

        ppc_tlb_invalidate_all(env);

#endif

    env->msr = msr;

    hreg_compute_hflags(env);

    env->reserve = -1;

    /* Be sure no exception or interrupt is pending */

    env->pending_interrupts = 0;

    env->exception_index = POWERPC_EXCP_NONE;

    env->error_code = 0;

    /* Flush all TLBs */

    tlb_flush(env, 1);

}


static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, const char *tcstr)

{

    int ret;

    MOVMuxContext *mov  = s->priv_data;

    MOVTrack *track     = &mov->tracks[index];

    AVStream *src_st    = s->streams[src_index];

    AVTimecode tc;

    AVPacket pkt    = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};

    AVRational rate = find_fps(s, src_st);

    /* compute the frame number */

    ret = av_timecode_init_from_string(&tc, rate, tcstr, s);

    if (ret < 0)

        return ret;

    /* tmcd track based on video stream */

    track->mode      = mov->mode;

    track->tag       = MKTAG('t','m','c','d');

    track->src_track = src_index;

    track->timescale = mov->tracks[src_index].timescale;

    if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)

        track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;

    /* set st to src_st for metadata access*/

    track->st = src_st;

    /* encode context: tmcd data stream */

    track->enc = avcodec_alloc_context3(NULL);

    track->enc->codec_type = AVMEDIA_TYPE_DATA;

    track->enc->codec_tag  = track->tag;

    track->enc->time_base  = av_inv_q(rate);

    /* the tmcd track just contains one packet with the frame number */

    pkt.data = av_malloc(pkt.size);

    AV_WB32(pkt.data, tc.start);

    ret = ff_mov_write_packet(s, &pkt);

    av_free(pkt.data);

    return ret;

}


static int rv40_decode_intra_types(RV34DecContext *r, GetBitContext *gb, int8_t *dst)

{

    MpegEncContext *s = &r->s;

    int i, j, k, v;

    int A, B, C;

    int pattern;

    int8_t *ptr;

    for(i = 0; i < 4; i++, dst += r->intra_types_stride){

        if(!i && s->first_slice_line){

            pattern = get_vlc2(gb, aic_top_vlc.table, AIC_TOP_BITS, 1);

            dst[0] = (pattern >> 2) & 2;

            dst[1] = (pattern >> 1) & 2;

            dst[2] =  pattern       & 2;

            dst[3] = (pattern << 1) & 2;

            continue;

        }

        ptr = dst;

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

            /* Coefficients are read using VLC chosen by the prediction pattern

             * The first one (used for retrieving a pair of coefficients) is

             * constructed from the top, top right and left coefficients

             * The second one (used for retrieving only one coefficient) is

             * top + 10 * left.

             */

            A = ptr[-r->intra_types_stride + 1]; // it won't be used for the last coefficient in a row

            B = ptr[-r->intra_types_stride];

            C = ptr[-1];

            pattern = A + (B << 4) + (C << 8);

            for(k = 0; k < MODE2_PATTERNS_NUM; k++)

                if(pattern == rv40_aic_table_index[k])

                    break;

            if(j < 3 && k < MODE2_PATTERNS_NUM){ //pattern is found, decoding 2 coefficients

                v = get_vlc2(gb, aic_mode2_vlc[k].table, AIC_MODE2_BITS, 2);

                *ptr++ = v/9;

                *ptr++ = v%9;

                j++;

            }else{

                if(B != -1 && C != -1)

                    v = get_vlc2(gb, aic_mode1_vlc[B + C*10].table, AIC_MODE1_BITS, 1);

                else{ // tricky decoding

                    v = 0;

                    switch(C){

                    case -1: // code 0 -> 1, 1 -> 0

                        if(B < 2)

                            v = get_bits1(gb) ^ 1;

                        break;

                    case  0:

                    case  2: // code 0 -> 2, 1 -> 0

                        v = (get_bits1(gb) ^ 1) << 1;

                        break;

                    }

                }

                *ptr++ = v;

            }

        }

    }

    return 0;

}


void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)

{

    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    /* virtio-1 compliant devices cannot change the alignment */

    if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {

        error_report("tried to modify queue alignment for virtio-1 device");

        return;

    }

    /* Check that the transport told us it was going to do this

     * (so a buggy transport will immediately assert rather than

     * silently failing to migrate this state)

     */

    assert(k->has_variable_vring_alignment);

    vdev->vq[n].vring.align = align;

    virtio_queue_update_rings(vdev, n);

}


static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)

{

    int64_t ref = pkt->dts;

    if (ref == AV_NOPTS_VALUE)

        ref = pkt->pts;

    if (ref == AV_NOPTS_VALUE)

        return 0;

    ref &= (1LL<<st->pts_wrap_bits)-1;

    if (s->correct_ts_overflow && st->pts_wrap_bits < 63 &&

        st->pts_wrap_reference == AV_NOPTS_VALUE) {

        int i;

        // reference time stamp should be 60 s before first time stamp

        int64_t pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);

        // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset

        int pts_wrap_behavior = (ref < (1LL<<st->pts_wrap_bits) - (1LL<<st->pts_wrap_bits-3)) ||

            (ref < (1LL<<st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?

            AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;

        AVProgram *first_program = av_find_program_from_stream(s, NULL, stream_index);

        if (!first_program) {

            int default_stream_index = av_find_default_stream_index(s);

            if (s->streams[default_stream_index]->pts_wrap_reference == AV_NOPTS_VALUE) {

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

                    s->streams[i]->pts_wrap_reference = pts_wrap_reference;

                    s->streams[i]->pts_wrap_behavior = pts_wrap_behavior;

                }

            }

            else {

                st->pts_wrap_reference = s->streams[default_stream_index]->pts_wrap_reference;

                st->pts_wrap_behavior = s->streams[default_stream_index]->pts_wrap_behavior;

            }

        }

        else {

            AVProgram *program = first_program;

            while (program) {

                if (program->pts_wrap_reference != AV_NOPTS_VALUE) {

                    pts_wrap_reference = program->pts_wrap_reference;

                    pts_wrap_behavior = program->pts_wrap_behavior;

                    break;

                }

                program = av_find_program_from_stream(s, program, stream_index);

            }

            // update every program with differing pts_wrap_reference

            program = first_program;

            while(program) {

                if (program->pts_wrap_reference != pts_wrap_reference) {

                    for (i=0; i<program->nb_stream_indexes; i++) {

                        s->streams[program->stream_index[i]]->pts_wrap_reference = pts_wrap_reference;

                        s->streams[program->stream_index[i]]->pts_wrap_behavior = pts_wrap_behavior;

                    }

                    program->pts_wrap_reference = pts_wrap_reference;

                    program->pts_wrap_behavior = pts_wrap_behavior;

                }

                program = av_find_program_from_stream(s, program, stream_index);

            }

        }

        return 1;

    }

    return 0;

}


static void action_command(EEPRO100State *s)

{

    for (;;) {

        bool bit_el;

        bool bit_s;

        bool bit_i;

        bool bit_nc;

        uint16_t ok_status = STATUS_OK;

        s->cb_address = s->cu_base + s->cu_offset;

        read_cb(s);

        bit_el = ((s->tx.command & COMMAND_EL) != 0);

        bit_s = ((s->tx.command & COMMAND_S) != 0);

        bit_i = ((s->tx.command & COMMAND_I) != 0);

        bit_nc = ((s->tx.command & COMMAND_NC) != 0);

#if 0

        bool bit_sf = ((s->tx.command & COMMAND_SF) != 0);

#endif

        s->cu_offset = s->tx.link;

        TRACE(OTHER,

              logout("val=(cu start), status=0x%04x, command=0x%04x, link=0x%08x\n",

                     s->tx.status, s->tx.command, s->tx.link));

        switch (s->tx.command & COMMAND_CMD) {

        case CmdNOp:

            /* Do nothing. */

            break;

        case CmdIASetup:

            cpu_physical_memory_read(s->cb_address + 8, &s->conf.macaddr.a[0], 6);

            TRACE(OTHER, logout("macaddr: %s\n", nic_dump(&s->conf.macaddr.a[0], 6)));

            break;

        case CmdConfigure:

            cpu_physical_memory_read(s->cb_address + 8, &s->configuration[0],

                                     sizeof(s->configuration));

            TRACE(OTHER, logout("configuration: %s\n", nic_dump(&s->configuration[0], 16)));

            break;

        case CmdMulticastList:

            set_multicast_list(s);

            break;

        case CmdTx:

            if (bit_nc) {

                missing("CmdTx: NC = 0");

                ok_status = 0;

                break;

            }

            tx_command(s);

            break;

        case CmdTDR:

            TRACE(OTHER, logout("load microcode\n"));

            /* Starting with offset 8, the command contains

             * 64 dwords microcode which we just ignore here. */

            break;

        case CmdDiagnose:

            TRACE(OTHER, logout("diagnose\n"));

            /* Make sure error flag is not set. */

            s->tx.status = 0;

            break;

        default:

            missing("undefined command");

            ok_status = 0;

            break;

        }

        /* Write new status. */

        stw_phys(s->cb_address, s->tx.status | ok_status | STATUS_C);

        if (bit_i) {

            /* CU completed action. */

            eepro100_cx_interrupt(s);

        }

        if (bit_el) {

            /* CU becomes idle. Terminate command loop. */

            set_cu_state(s, cu_idle);

            eepro100_cna_interrupt(s);

            break;

        } else if (bit_s) {

            /* CU becomes suspended. Terminate command loop. */

            set_cu_state(s, cu_suspended);

            eepro100_cna_interrupt(s);

            break;

        } else {

            /* More entries in list. */

            TRACE(OTHER, logout("CU list with at least one more entry\n"));

        }

    }

    TRACE(OTHER, logout("CU list empty\n"));

    /* List is empty. Now CU is idle or suspended. */

}


void SwScale_YV12slice(unsigned char* srcptr[],int stride[], int srcSliceY ,

			     int srcSliceH, uint8_t* dstptr[], int dststride, int dstbpp,

			     int srcW, int srcH, int dstW, int dstH){

#ifdef RUNTIME_CPUDETECT

#ifdef CAN_COMPILE_X86_ASM

	// ordered per speed fasterst first

	if(gCpuCaps.hasMMX2)

		SwScale_YV12slice_MMX2(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

	else if(gCpuCaps.has3DNow)

		SwScale_YV12slice_3DNow(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

	else if(gCpuCaps.hasMMX)

		SwScale_YV12slice_MMX(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

	else

		SwScale_YV12slice_C(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

#else

		SwScale_YV12slice_C(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

#endif

#else //RUNTIME_CPUDETECT

#ifdef HAVE_MMX2

		SwScale_YV12slice_MMX2(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

#elif defined (HAVE_3DNOW)

		SwScale_YV12slice_3DNow(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

#elif defined (HAVE_MMX)

		SwScale_YV12slice_MMX(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

#else

		SwScale_YV12slice_C(srcptr, stride, srcSliceY, srcSliceH, dstptr, dststride, dstbpp, srcW, srcH, dstW, dstH);

#endif

#endif //!RUNTIME_CPUDETECT

}


int ppc_hash64_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,

                                int mmu_idx)

{

    struct mmu_ctx_hash64 ctx;

    int access_type;

    int ret = 0;

    if (rw == 2) {

        /* code access */

        rw = 0;

        access_type = ACCESS_CODE;

    } else {

        /* data access */

        access_type = env->access_type;

    }

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

    if (ret == 0) {

        tlb_set_page(env, address & TARGET_PAGE_MASK,

                     ctx.raddr & TARGET_PAGE_MASK, ctx.prot,

                     mmu_idx, TARGET_PAGE_SIZE);

        ret = 0;

    } else if (ret < 0) {

        LOG_MMU_STATE(env);

        if (access_type == ACCESS_CODE) {

            switch (ret) {

            case -1:

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x40000000;

                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 -5:

                /* No match in segment table */

                env->exception_index = POWERPC_EXCP_ISEG;

                env->error_code = 0;

                break;

            }

        } else {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                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 -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 -5:

                /* No match in segment table */

                env->exception_index = POWERPC_EXCP_DSEG;

                env->error_code = 0;

                env->spr[SPR_DAR] = address;

                break;

            }

        }

#if 0

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

               env->exception, env->error_code);

#endif

        ret = 1;

    }

    return ret;

}


static void isa_mmio_writew(void *opaque, target_phys_addr_t addr,

                               uint32_t val)

{

    cpu_outw(addr & IOPORTS_MASK, val);

}


static int flic_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             uint8_t *buf, int buf_size)

{

    FlicDecodeContext *s = (FlicDecodeContext *)avctx->priv_data;

    int stream_ptr = 0;

    int stream_ptr_after_color_chunk;

    int pixel_ptr;

    int palette_ptr;

    unsigned char palette_idx1;

    unsigned char palette_idx2;

    unsigned int frame_size;

    int num_chunks;

    unsigned int chunk_size;

    int chunk_type;

    int i, j;

    int color_packets;

    int color_changes;

    int color_shift;

    unsigned char r, g, b;

    int lines;

    int compressed_lines;

    int starting_line;

    signed short line_packets;

    int y_ptr;

    signed char byte_run;

    int pixel_skip;

    int pixel_countdown;

    unsigned char *pixels;

    int pixel_limit;

    s->frame.reference = 1;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, &s->frame) < 0) {

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

        return -1;

    }

    pixels = s->frame.data[0];

    pixel_limit = s->avctx->height * s->frame.linesize[0];

    frame_size = LE_32(&buf[stream_ptr]);

    stream_ptr += 6;  /* skip the magic number */

    num_chunks = LE_16(&buf[stream_ptr]);

    stream_ptr += 10;  /* skip padding */

    frame_size -= 16;

    /* iterate through the chunks */

    while ((frame_size > 0) && (num_chunks > 0)) {

        chunk_size = LE_32(&buf[stream_ptr]);

        stream_ptr += 4;

        chunk_type = LE_16(&buf[stream_ptr]);

        stream_ptr += 2;

        switch (chunk_type) {

        case FLI_256_COLOR:

        case FLI_COLOR:

            stream_ptr_after_color_chunk = stream_ptr + chunk_size - 6;

            s->new_palette = 1;

            /* check special case: If this file is from the Magic Carpet

             * game and uses 6-bit colors even though it reports 256-color

             * chunks in a 0xAF12-type file (fli_type is set to 0xAF13 during

             * initialization) */

            if ((chunk_type == FLI_256_COLOR) && (s->fli_type != 0xAF13))

                color_shift = 0;

            else

                color_shift = 2;

            /* set up the palette */

            color_packets = LE_16(&buf[stream_ptr]);

            stream_ptr += 2;

            palette_ptr = 0;

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

                /* first byte is how many colors to skip */

                palette_ptr += buf[stream_ptr++];

                /* next byte indicates how many entries to change */

                color_changes = buf[stream_ptr++];

                /* if there are 0 color changes, there are actually 256 */

                if (color_changes == 0)

                    color_changes = 256;

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

                    /* wrap around, for good measure */

                    if ((unsigned)palette_ptr >= 256)

                        palette_ptr = 0;

                    r = buf[stream_ptr++] << color_shift;

                    g = buf[stream_ptr++] << color_shift;

                    b = buf[stream_ptr++] << color_shift;

                    s->palette[palette_ptr++] = (r << 16) | (g << 8) | b;

                }

            }

            /* color chunks sometimes have weird 16-bit alignment issues;

             * therefore, take the hardline approach and set the stream_ptr

             * to the value calculated w.r.t. the size specified by the color

             * chunk header */

            stream_ptr = stream_ptr_after_color_chunk;

            break;

        case FLI_DELTA:

            y_ptr = 0;

            compressed_lines = LE_16(&buf[stream_ptr]);

            stream_ptr += 2;

            while (compressed_lines > 0) {

                line_packets = LE_16(&buf[stream_ptr]);

                stream_ptr += 2;

                if (line_packets < 0) {

                    line_packets = -line_packets;

                    y_ptr += line_packets * s->frame.linesize[0];

                } else {

                    compressed_lines--;

                    pixel_ptr = y_ptr;

                    pixel_countdown = s->avctx->width;

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

                        /* account for the skip bytes */

                        pixel_skip = buf[stream_ptr++];

                        pixel_ptr += pixel_skip;

                        pixel_countdown -= pixel_skip;

                        byte_run = buf[stream_ptr++];

                        if (byte_run < 0) {

                            byte_run = -byte_run;

                            palette_idx1 = buf[stream_ptr++];

                            palette_idx2 = buf[stream_ptr++];

                            for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {

                                pixels[pixel_ptr++] = palette_idx1;

                                pixels[pixel_ptr++] = palette_idx2;

                            }

                        } else {

                            for (j = 0; j < byte_run * 2; j++, pixel_countdown--) {

                                palette_idx1 = buf[stream_ptr++];

                                pixels[pixel_ptr++] = palette_idx1;

                            }

                        }

                    }

                    y_ptr += s->frame.linesize[0];

                }

            }

            break;

        case FLI_LC:

            /* line compressed */

            starting_line = LE_16(&buf[stream_ptr]);

            stream_ptr += 2;

            y_ptr = 0;

            y_ptr += starting_line * s->frame.linesize[0];

            compressed_lines = LE_16(&buf[stream_ptr]);

            stream_ptr += 2;

            while (compressed_lines > 0) {

                pixel_ptr = y_ptr;

                pixel_countdown = s->avctx->width;

                line_packets = buf[stream_ptr++];

                if (line_packets > 0) {

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

                        /* account for the skip bytes */

                        pixel_skip = buf[stream_ptr++];

                        pixel_ptr += pixel_skip;

                        pixel_countdown -= pixel_skip;

                        byte_run = buf[stream_ptr++];

                        if (byte_run > 0) {

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                palette_idx1 = buf[stream_ptr++];

                                pixels[pixel_ptr++] = palette_idx1;

                            }

                        } else {

                            byte_run = -byte_run;

                            palette_idx1 = buf[stream_ptr++];

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                pixels[pixel_ptr++] = palette_idx1;

                            }

                        }

                    }

                }

                y_ptr += s->frame.linesize[0];

                compressed_lines--;

            }

            break;

        case FLI_BLACK:

            /* set the whole frame to color 0 (which is usually black) */

            memset(pixels, 0,

                s->frame.linesize[0] * s->avctx->height);

            break;

        case FLI_BRUN:

            /* Byte run compression: This chunk type only occurs in the first

             * FLI frame and it will update the entire frame. */

            y_ptr = 0;

            for (lines = 0; lines < s->avctx->height; lines++) {

                pixel_ptr = y_ptr;

                /* disregard the line packets; instead, iterate through all

                 * pixels on a row */

                stream_ptr++;

                pixel_countdown = s->avctx->width;

                while (pixel_countdown > 0) {

                    byte_run = buf[stream_ptr++];

                    if (byte_run > 0) {

                        palette_idx1 = buf[stream_ptr++];

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

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    } else {  /* copy bytes if byte_run < 0 */

                        byte_run = -byte_run;

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

                            palette_idx1 = buf[stream_ptr++];

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    }

                }

                y_ptr += s->frame.linesize[0];

            }

            break;

        case FLI_COPY:

            /* copy the chunk (uncompressed frame) */

            if (chunk_size - 6 > s->avctx->width * s->avctx->height) {

                av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \

                       "bigger than image, skipping chunk\n", chunk_size - 6);

                stream_ptr += chunk_size - 6;

            } else {

                for (y_ptr = 0; y_ptr < s->frame.linesize[0] * s->avctx->height;

                     y_ptr += s->frame.linesize[0]) {

                    memcpy(&pixels[y_ptr], &buf[stream_ptr],

                        s->avctx->width);

                    stream_ptr += s->avctx->width;

                }

            }

            break;

        case FLI_MINI:

            /* some sort of a thumbnail? disregard this chunk... */

            stream_ptr += chunk_size - 6;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type);

            break;

        }

        frame_size -= chunk_size;

        num_chunks--;

    }

    /* by the end of the chunk, the stream ptr should equal the frame

     * size (minus 1, possibly); if it doesn't, issue a warning */

    if ((stream_ptr != buf_size) && (stream_ptr != buf_size - 1))

        av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \

               "and final chunk ptr = %d\n", buf_size, stream_ptr);

    /* make the palette available on the way out */

//    if (s->new_palette) {

    if (1) {

        memcpy(s->frame.data[1], s->palette, AVPALETTE_SIZE);

        s->frame.palette_has_changed = 1;

        s->new_palette = 0;

    }

    *data_size=sizeof(AVFrame);

    *(AVFrame*)data = s->frame;

    return buf_size;

}


static int encode_superframe(AVCodecContext *avctx,
                            unsigned char *buf, int buf_size, void *data){
    WMACodecContext *s = avctx->priv_data;
    const short *samples = data;
    int i, total_gain;
    s->block_len_bits= s->frame_len_bits; //required by non variable block len
    s->block_len = 1 << s->block_len_bits;
    apply_window_and_mdct(avctx, samples, avctx->frame_size);
    if (s->ms_stereo) {
        float a, b;
        int i;
        for(i = 0; i < s->block_len; i++) {
            a = s->coefs[0][i]*0.5;
            b = s->coefs[1][i]*0.5;
            s->coefs[0][i] = a + b;
            s->coefs[1][i] = a - b;
#if 1
    total_gain= 128;
    for(i=64; i; i>>=1){
        int error= encode_frame(s, s->coefs, buf, buf_size, total_gain-i);
        if(error<0)
            total_gain-= i;
#else
    total_gain= 90;
    best= encode_frame(s, s->coefs, buf, buf_size, total_gain);
    for(i=32; i; i>>=1){
        int scoreL= encode_frame(s, s->coefs, buf, buf_size, total_gain-i);
        int scoreR= encode_frame(s, s->coefs, buf, buf_size, total_gain+i);
        av_log(NULL, AV_LOG_ERROR, "%d %d %d (%d)\n", scoreL, best, scoreR, total_gain);
        if(scoreL < FFMIN(best, scoreR)){
            best = scoreL;
            total_gain -= i;
        }else if(scoreR < best){
            best = scoreR;
            total_gain += i;
#endif
    encode_frame(s, s->coefs, buf, buf_size, total_gain);
    assert((put_bits_count(&s->pb) & 7) == 0);
    i= s->block_align - (put_bits_count(&s->pb)+7)/8;
    assert(i>=0);
    while(i--)
        put_bits(&s->pb, 8, 'N');
    flush_put_bits(&s->pb);
    return put_bits_ptr(&s->pb) - s->pb.buf;


int kvm_on_sigbus(int code, void *addr)

{

#if defined(KVM_CAP_MCE)

    if ((first_cpu->mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {

        uint64_t status;

        void *vaddr;

        ram_addr_t ram_addr;

        target_phys_addr_t paddr;

        /* Hope we are lucky for AO MCE */

        vaddr = addr;

        if (qemu_ram_addr_from_host(vaddr, &ram_addr) ||

            !kvm_physical_memory_addr_from_ram(first_cpu->kvm_state, ram_addr, &paddr)) {

            fprintf(stderr, "Hardware memory error for memory used by "

                    "QEMU itself instead of guest system!: %p\n", addr);

            return 0;

        }

        status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN

            | MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S

            | 0xc0;

        kvm_inject_x86_mce(first_cpu, 9, status,

                           MCG_STATUS_MCIP | MCG_STATUS_RIPV, paddr,

                           (MCM_ADDR_PHYS << 6) | 0xc, 1);

        kvm_mce_broadcast_rest(first_cpu);

    } else

#endif

    {

        if (code == BUS_MCEERR_AO) {

            return 0;

        } else if (code == BUS_MCEERR_AR) {

            hardware_memory_error();

        } else {

            return 1;

        }

    }

    return 0;

}


static int ogg_save(AVFormatContext *s)

{

    struct ogg *ogg = s->priv_data;

    struct ogg_state *ost =

        av_malloc(sizeof (*ost) + (ogg->nstreams-1) * sizeof (*ogg->streams));

    int i;

    ost->pos = avio_tell (s->pb);

    ost->curidx = ogg->curidx;

    ost->next = ogg->state;

    ost->nstreams = ogg->nstreams;

    memcpy(ost->streams, ogg->streams, ogg->nstreams * sizeof(*ogg->streams));

    for (i = 0; i < ogg->nstreams; i++){

        struct ogg_stream *os = ogg->streams + i;

        os->buf = av_malloc (os->bufsize);

        memset (os->buf, 0, os->bufsize);

        memcpy (os->buf, ost->streams[i].buf, os->bufpos);

    }

    ogg->state = ost;

    return 0;

}


static int dxtory_decode_v1_444(AVCodecContext *avctx, AVFrame *pic,

                                const uint8_t *src, int src_size)

{

    int h, w;

    uint8_t *Y, *U, *V;

    int ret;

    if (src_size < avctx->width * avctx->height * 3) {

        av_log(avctx, AV_LOG_ERROR, "packet too small\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV444P;

    if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)

        return ret;

    Y = pic->data[0];

    U = pic->data[1];

    V = pic->data[2];

    for (h = 0; h < avctx->height; h++) {

        for (w = 0; w < avctx->width; w++) {

            Y[w] = *src++;

            U[w] = *src++ ^ 0x80;

            V[w] = *src++ ^ 0x80;

        }

        Y += pic->linesize[0];

        U += pic->linesize[1];

        V += pic->linesize[2];

    }

    return 0;

}


static size_t buffered_set_rate_limit(void *opaque, size_t new_rate)

{

    QEMUFileBuffered *s = opaque;

    if (s->has_error)

        goto out;

    s->xfer_limit = new_rate / 10;

out:

    return s->xfer_limit;

}


static void ccw_init(MachineState *machine)

{

    int ret;

    VirtualCssBus *css_bus;

    DeviceState *dev;

    s390_sclp_init();

    s390_memory_init(machine->ram_size);

    /* get a BUS */

    css_bus = virtual_css_bus_init();

    s390_init_ipl_dev(machine->kernel_filename, machine->kernel_cmdline,

                      machine->initrd_filename, "s390-ccw.img", true);

    s390_flic_init();

    dev = qdev_create(NULL, TYPE_S390_PCI_HOST_BRIDGE);

    object_property_add_child(qdev_get_machine(), TYPE_S390_PCI_HOST_BRIDGE,

                              OBJECT(dev), NULL);

    qdev_init_nofail(dev);

    /* register hypercalls */

    virtio_ccw_register_hcalls();

    /* init CPUs */

    s390_init_cpus(machine->cpu_model);

    if (kvm_enabled()) {

        kvm_s390_enable_css_support(s390_cpu_addr2state(0));

    }

    /*

     * Create virtual css and set it as default so that non mcss-e

     * enabled guests only see virtio devices.

     */

    ret = css_create_css_image(VIRTUAL_CSSID, true);

    assert(ret == 0);

    /* Create VirtIO network adapters */

    s390_create_virtio_net(BUS(css_bus), "virtio-net-ccw");

    /* Register savevm handler for guest TOD clock */

    register_savevm(NULL, "todclock", 0, 1,

                    gtod_save, gtod_load, kvm_state);

}


int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,

                      int64_t pos, int size)

{

    BlockDriver *drv = bs->drv;

    if (!drv)

        return -ENOMEDIUM;

    if (drv->bdrv_load_vmstate)

        return drv->bdrv_load_vmstate(bs, buf, pos, size);

    if (bs->file)

        return bdrv_load_vmstate(bs->file, buf, pos, size);

    return -ENOTSUP;

}


static av_cold int vaapi_encode_h265_init(AVCodecContext *avctx)

{

    return ff_vaapi_encode_init(avctx, &vaapi_encode_type_h265);

}


static void versatile_init(ram_addr_t ram_size, int vga_ram_size,

                     const char *boot_device, DisplayState *ds,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename, const char *cpu_model,

                     int board_id)

{

    CPUState *env;

    qemu_irq *pic;

    qemu_irq *sic;

    void *scsi_hba;

    PCIBus *pci_bus;

    NICInfo *nd;

    int n;

    int done_smc = 0;

    int index;

    if (!cpu_model)

        cpu_model = "arm926";

    env = cpu_init(cpu_model);

    if (!env) {

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

        exit(1);

    }

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

    /* SDRAM at address zero.  */

    cpu_register_physical_memory(0, ram_size, IO_MEM_RAM);

    arm_sysctl_init(0x10000000, 0x41007004);

    pic = arm_pic_init_cpu(env);

    pic = pl190_init(0x10140000, pic[0], pic[1]);

    sic = vpb_sic_init(0x10003000, pic, 31);

    pl050_init(0x10006000, sic[3], 0);

    pl050_init(0x10007000, sic[4], 1);

    pci_bus = pci_vpb_init(sic, 27, 0);

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

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

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

        nd = &nd_table[n];

        if (!nd->model)

            nd->model = done_smc ? "rtl8139" : "smc91c111";

        if (strcmp(nd->model, "smc91c111") == 0) {

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

        } else {

            pci_nic_init(pci_bus, nd, -1);

        }

    }

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, 3, -1);

    }

    if (drive_get_max_bus(IF_SCSI) > 0) {

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

        exit(1);

    }

    scsi_hba = lsi_scsi_init(pci_bus, -1);

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

        index = drive_get_index(IF_SCSI, 0, n);

        if (index == -1)

            continue;

        lsi_scsi_attach(scsi_hba, drives_table[index].bdrv, n);

    }

    pl011_init(0x101f1000, pic[12], serial_hds[0], PL011_ARM);

    pl011_init(0x101f2000, pic[13], serial_hds[1], PL011_ARM);

    pl011_init(0x101f3000, pic[14], serial_hds[2], PL011_ARM);

    pl011_init(0x10009000, sic[6], serial_hds[3], PL011_ARM);

    pl080_init(0x10130000, pic[17], 8);

    sp804_init(0x101e2000, pic[4]);

    sp804_init(0x101e3000, pic[5]);

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

       that includes hardware cursor support from the PL111.  */

    pl110_init(ds, 0x10120000, pic[16], 1);

    index = drive_get_index(IF_SD, 0, 0);

    if (index == -1) {

        fprintf(stderr, "qemu: missing SecureDigital card\n");

        exit(1);

    }

    pl181_init(0x10005000, drives_table[index].bdrv, sic[22], sic[1]);

#if 0

    /* Disabled because there's no way of specifying a block device.  */

    pl181_init(0x1000b000, NULL, sic, 23, 2);

#endif

    /* Add PL031 Real Time Clock. */

    pl031_init(0x101e8000,pic[10]);

    /* Memory map for Versatile/PB:  */

    /* 0x10000000 System registers.  */

    /* 0x10001000 PCI controller config registers.  */

    /* 0x10002000 Serial bus interface.  */

    /*  0x10003000 Secondary interrupt controller.  */

    /* 0x10004000 AACI (audio).  */

    /*  0x10005000 MMCI0.  */

    /*  0x10006000 KMI0 (keyboard).  */

    /*  0x10007000 KMI1 (mouse).  */

    /* 0x10008000 Character LCD Interface.  */

    /*  0x10009000 UART3.  */

    /* 0x1000a000 Smart card 1.  */

    /*  0x1000b000 MMCI1.  */

    /*  0x10010000 Ethernet.  */

    /* 0x10020000 USB.  */

    /* 0x10100000 SSMC.  */

    /* 0x10110000 MPMC.  */

    /*  0x10120000 CLCD Controller.  */

    /*  0x10130000 DMA Controller.  */

    /*  0x10140000 Vectored interrupt controller.  */

    /* 0x101d0000 AHB Monitor Interface.  */

    /* 0x101e0000 System Controller.  */

    /* 0x101e1000 Watchdog Interface.  */

    /* 0x101e2000 Timer 0/1.  */

    /* 0x101e3000 Timer 2/3.  */

    /* 0x101e4000 GPIO port 0.  */

    /* 0x101e5000 GPIO port 1.  */

    /* 0x101e6000 GPIO port 2.  */

    /* 0x101e7000 GPIO port 3.  */

    /* 0x101e8000 RTC.  */

    /* 0x101f0000 Smart card 0.  */

    /*  0x101f1000 UART0.  */

    /*  0x101f2000 UART1.  */

    /*  0x101f3000 UART2.  */

    /* 0x101f4000 SSPI.  */

    versatile_binfo.ram_size = ram_size;

    versatile_binfo.kernel_filename = kernel_filename;

    versatile_binfo.kernel_cmdline = kernel_cmdline;

    versatile_binfo.initrd_filename = initrd_filename;

    versatile_binfo.board_id = board_id;

    arm_load_kernel(env, &versatile_binfo);

}


static void detach(sPAPRDRConnector *drc, DeviceState *d,

                   spapr_drc_detach_cb *detach_cb,

                   void *detach_cb_opaque, Error **errp)

{

    trace_spapr_drc_detach(get_index(drc));

    drc->detach_cb = detach_cb;

    drc->detach_cb_opaque = detach_cb_opaque;

    /* if we've signalled device presence to the guest, or if the guest

     * has gone ahead and configured the device (via manually-executed

     * device add via drmgr in guest, namely), we need to wait

     * for the guest to quiesce the device before completing detach.

     * Otherwise, we can assume the guest hasn't seen it and complete the

     * detach immediately. Note that there is a small race window

     * just before, or during, configuration, which is this context

     * refers mainly to fetching the device tree via RTAS.

     * During this window the device access will be arbitrated by

     * associated DRC, which will simply fail the RTAS calls as invalid.

     * This is recoverable within guest and current implementations of

     * drmgr should be able to cope.

     */

    if (!drc->signalled && !drc->configured) {

        /* if the guest hasn't seen the device we can't rely on it to

         * set it back to an isolated state via RTAS, so do it here manually

         */

        drc->isolation_state = SPAPR_DR_ISOLATION_STATE_ISOLATED;

    }

    if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {

        trace_spapr_drc_awaiting_isolated(get_index(drc));

        drc->awaiting_release = true;

        return;

    }

    if (drc->type != SPAPR_DR_CONNECTOR_TYPE_PCI &&

        drc->allocation_state != SPAPR_DR_ALLOCATION_STATE_UNUSABLE) {

        trace_spapr_drc_awaiting_unusable(get_index(drc));

        drc->awaiting_release = true;

        return;

    }

    if (drc->awaiting_allocation) {

        if (!drc->awaiting_allocation_skippable) {

            drc->awaiting_release = true;

            trace_spapr_drc_awaiting_allocation(get_index(drc));

            return;

        }

    }

    drc->indicator_state = SPAPR_DR_INDICATOR_STATE_INACTIVE;

    if (drc->detach_cb) {

        drc->detach_cb(drc->dev, drc->detach_cb_opaque);

    }

    drc->awaiting_release = false;

    drc->awaiting_allocation_skippable = false;

    g_free(drc->fdt);

    drc->fdt = NULL;

    drc->fdt_start_offset = 0;

    object_property_del(OBJECT(drc), "device", NULL);

    drc->dev = NULL;

    drc->detach_cb = NULL;

    drc->detach_cb_opaque = NULL;

}


char **breakline(char *input, int *count)

{

    int c = 0;

    char *p;

    char **rval = calloc(sizeof(char *), 1);

    while (rval && (p = qemu_strsep(&input, " ")) != NULL) {

        if (!*p) {

            continue;

        }

        c++;

        rval = realloc(rval, sizeof(*rval) * (c + 1));

        if (!rval) {

            c = 0;

            break;

        }

        rval[c - 1] = p;

        rval[c] = NULL;

    }

    *count = c;

    return rval;

}


static av_noinline void FUNC(hl_decode_mb)(H264Context *h)

{

    const int mb_x    = h->mb_x;

    const int mb_y    = h->mb_y;

    const int mb_xy   = h->mb_xy;

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

    uint8_t *dest_y, *dest_cb, *dest_cr;

    int linesize, uvlinesize /*dct_offset*/;

    int i, j;

    int *block_offset = &h->block_offset[0];

    const int transform_bypass = !SIMPLE && (h->qscale == 0 && h->sps.transform_bypass);

    /* is_h264 should always be true if SVQ3 is disabled. */

    const int is_h264 = !CONFIG_SVQ3_DECODER || SIMPLE || h->avctx->codec_id == AV_CODEC_ID_H264;

    void (*idct_add)(uint8_t *dst, int16_t *block, int stride);

    const int block_h   = 16 >> h->chroma_y_shift;

    const int chroma422 = CHROMA422;

    dest_y  = h->cur_pic.f.data[0] + ((mb_x << PIXEL_SHIFT)     + mb_y * h->linesize)  * 16;

    dest_cb = h->cur_pic.f.data[1] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * h->uvlinesize * block_h;

    dest_cr = h->cur_pic.f.data[2] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * h->uvlinesize * block_h;

    h->vdsp.prefetch(dest_y  + (h->mb_x & 3) * 4 * h->linesize   + (64 << PIXEL_SHIFT), h->linesize,       4);

    h->vdsp.prefetch(dest_cb + (h->mb_x & 7)     * h->uvlinesize + (64 << PIXEL_SHIFT), dest_cr - dest_cb, 2);

    h->list_counts[mb_xy] = h->list_count;

    if (!SIMPLE && MB_FIELD) {

        linesize     = h->mb_linesize = h->linesize * 2;

        uvlinesize   = h->mb_uvlinesize = h->uvlinesize * 2;

        block_offset = &h->block_offset[48];

        if (mb_y & 1) { // FIXME move out of this function?

            dest_y  -= h->linesize * 15;

            dest_cb -= h->uvlinesize * (block_h - 1);

            dest_cr -= h->uvlinesize * (block_h - 1);

        }

        if (FRAME_MBAFF) {

            int list;

            for (list = 0; list < h->list_count; list++) {

                if (!USES_LIST(mb_type, list))

                    continue;

                if (IS_16X16(mb_type)) {

                    int8_t *ref = &h->ref_cache[list][scan8[0]];

                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (h->mb_y & 1), 1);

                } else {

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

                        int ref = h->ref_cache[list][scan8[i]];

                        if (ref >= 0)

                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,

                                           8, (16 + ref) ^ (h->mb_y & 1), 1);

                    }

                }

            }

        }

    } else {

        linesize   = h->mb_linesize   = h->linesize;

        uvlinesize = h->mb_uvlinesize = h->uvlinesize;

        // dct_offset = s->linesize * 16;

    }

    if (!SIMPLE && IS_INTRA_PCM(mb_type)) {

        const int bit_depth = h->sps.bit_depth_luma;

        if (PIXEL_SHIFT) {

            int j;

            GetBitContext gb;

            init_get_bits(&gb, (uint8_t *)h->intra_pcm_ptr,

                          ff_h264_mb_sizes[h->sps.chroma_format_idc] * bit_depth);

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

                uint16_t *tmp_y = (uint16_t *)(dest_y + i * linesize);

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

                    tmp_y[j] = get_bits(&gb, bit_depth);

            }

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {

                if (!h->sps.chroma_format_idc) {

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

                        uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);

                        uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);

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

                            tmp_cb[j] = tmp_cr[j] = 1 << (bit_depth - 1);

                        }

                    }

                } else {

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

                        uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);

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

                            tmp_cb[j] = get_bits(&gb, bit_depth);

                    }

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

                        uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);

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

                            tmp_cr[j] = get_bits(&gb, bit_depth);

                    }

                }

            }

        } else {

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

                memcpy(dest_y + i * linesize, (uint8_t *)h->intra_pcm_ptr + i * 16, 16);

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {

                if (!h->sps.chroma_format_idc) {

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

                        memset(dest_cb + i*uvlinesize, 1 << (bit_depth - 1), 8);

                        memset(dest_cr + i*uvlinesize, 1 << (bit_depth - 1), 8);

                    }

                } else {

                    uint8_t *src_cb = (uint8_t *)h->intra_pcm_ptr + 256;

                    uint8_t *src_cr = (uint8_t *)h->intra_pcm_ptr + 256 + block_h * 8;

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

                        memcpy(dest_cb + i * uvlinesize, src_cb + i * 8, 8);

                        memcpy(dest_cr + i * uvlinesize, src_cr + i * 8, 8);

                    }

                }

            }

        }

    } else {

        if (IS_INTRA(mb_type)) {

            if (h->deblocking_filter)

                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,

                               uvlinesize, 1, 0, SIMPLE, PIXEL_SHIFT);

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {

                h->hpc.pred8x8[h->chroma_pred_mode](dest_cb, uvlinesize);

                h->hpc.pred8x8[h->chroma_pred_mode](dest_cr, uvlinesize);

            }

            hl_decode_mb_predict_luma(h, mb_type, is_h264, SIMPLE,

                                      transform_bypass, PIXEL_SHIFT,

                                      block_offset, linesize, dest_y, 0);

            if (h->deblocking_filter)

                xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize,

                               uvlinesize, 0, 0, SIMPLE, PIXEL_SHIFT);

        } else if (is_h264) {

            if (chroma422) {

                FUNC(hl_motion_422)(h, dest_y, dest_cb, dest_cr,

                              h->me.qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                              h->me.qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                              h->h264dsp.weight_h264_pixels_tab,

                              h->h264dsp.biweight_h264_pixels_tab);

            } else {

                FUNC(hl_motion_420)(h, dest_y, dest_cb, dest_cr,

                              h->me.qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                              h->me.qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                              h->h264dsp.weight_h264_pixels_tab,

                              h->h264dsp.biweight_h264_pixels_tab);

            }

        }

        hl_decode_mb_idct_luma(h, mb_type, is_h264, SIMPLE, transform_bypass,

                               PIXEL_SHIFT, block_offset, linesize, dest_y, 0);

        if ((SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) &&

            (h->cbp & 0x30)) {

            uint8_t *dest[2] = { dest_cb, dest_cr };

            if (transform_bypass) {

                if (IS_INTRA(mb_type) && h->sps.profile_idc == 244 &&

                    (h->chroma_pred_mode == VERT_PRED8x8 ||

                     h->chroma_pred_mode == HOR_PRED8x8)) {

                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0],

                                                            block_offset + 16,

                                                            h->mb + (16 * 16 * 1 << PIXEL_SHIFT),

                                                            uvlinesize);

                    h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1],

                                                            block_offset + 32,

                                                            h->mb + (16 * 16 * 2 << PIXEL_SHIFT),

                                                            uvlinesize);

                } else {

                    idct_add = h->h264dsp.h264_add_pixels4;

                    for (j = 1; j < 3; j++) {

                        for (i = j * 16; i < j * 16 + 4; i++)

                            if (h->non_zero_count_cache[scan8[i]] ||

                                dctcoef_get(h->mb, PIXEL_SHIFT, i * 16))

                                idct_add(dest[j - 1] + block_offset[i],

                                         h->mb + (i * 16 << PIXEL_SHIFT),

                                         uvlinesize);

                        if (chroma422) {

                            for (i = j * 16 + 4; i < j * 16 + 8; i++)

                                if (h->non_zero_count_cache[scan8[i + 4]] ||

                                    dctcoef_get(h->mb, PIXEL_SHIFT, i * 16))

                                    idct_add(dest[j - 1] + block_offset[i + 4],

                                             h->mb + (i * 16 << PIXEL_SHIFT),

                                             uvlinesize);

                        }

                    }

                }

            } else {

                if (is_h264) {

                    int qp[2];

                    if (chroma422) {

                        qp[0] = h->chroma_qp[0] + 3;

                        qp[1] = h->chroma_qp[1] + 3;

                    } else {

                        qp[0] = h->chroma_qp[0];

                        qp[1] = h->chroma_qp[1];

                    }

                    if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 0]])

                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 1 << PIXEL_SHIFT),

                                                               h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][qp[0]][0]);

                    if (h->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 1]])

                        h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16 * 16 * 2 << PIXEL_SHIFT),

                                                               h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][qp[1]][0]);

                    h->h264dsp.h264_idct_add8(dest, block_offset,

                                              h->mb, uvlinesize,

                                              h->non_zero_count_cache);

                } else if (CONFIG_SVQ3_DECODER) {

                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 1,

                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][h->chroma_qp[0]][0]);

                    h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16 * 16 * 2,

                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][h->chroma_qp[1]][0]);

                    for (j = 1; j < 3; j++) {

                        for (i = j * 16; i < j * 16 + 4; i++)

                            if (h->non_zero_count_cache[scan8[i]] || h->mb[i * 16]) {

                                uint8_t *const ptr = dest[j - 1] + block_offset[i];

                                ff_svq3_add_idct_c(ptr, h->mb + i * 16,

                                                   uvlinesize,

                                                   ff_h264_chroma_qp[0][h->qscale + 12] - 12, 2);

                            }

                    }

                }

            }

        }

        if (h->cbp || IS_INTRA(mb_type)) {

            h->dsp.clear_blocks(h->mb);

            h->dsp.clear_blocks(h->mb + (24 * 16 << PIXEL_SHIFT));

        }

    }

}


static gsize calc_float_string_storage(double value)

{

    int whole_value = value;

    gsize i = 0;

    do {

        i++;

    } while (whole_value /= 10);

    return i + 2 + FLOAT_STRING_PRECISION;

}


static void virtio_net_vmstate_change(void *opaque, int running, int reason)

{

    VirtIONet *n = opaque;

    if (!running) {

        return;

    }

    /* This is called when vm is started, it will start vhost backend if

     * appropriate e.g. after migration. */

    virtio_net_set_status(&n->vdev, n->vdev.status);

}


static int coroutine_fn raw_co_pdiscard(BlockDriverState *bs,

                                        int64_t offset, int count)

{

    BDRVRawState *s = bs->opaque;

    if (offset > UINT64_MAX - s->offset) {

        return -EINVAL;

    }

    offset += s->offset;

    return bdrv_co_pdiscard(bs->file->bs, offset, count);

}


static av_cold int mp3lame_encode_init(AVCodecContext *avctx)

{

    LAMEContext *s = avctx->priv_data;

    int ret;

    s->avctx = avctx;

    /* initialize LAME and get defaults */

    if (!(s->gfp = lame_init()))

        return AVERROR(ENOMEM);

    lame_set_num_channels(s->gfp, avctx->channels);

    lame_set_mode(s->gfp, avctx->channels > 1 ? s->joint_stereo ? JOINT_STEREO : STEREO : MONO);

    /* sample rate */

    lame_set_in_samplerate (s->gfp, avctx->sample_rate);

    lame_set_out_samplerate(s->gfp, avctx->sample_rate);

    /* algorithmic quality */

    if (avctx->compression_level == FF_COMPRESSION_DEFAULT)

        lame_set_quality(s->gfp, 5);

    else

        lame_set_quality(s->gfp, avctx->compression_level);

    /* rate control */

    if (avctx->flags & CODEC_FLAG_QSCALE) { // VBR

        lame_set_VBR(s->gfp, vbr_default);

        lame_set_VBR_quality(s->gfp, avctx->global_quality / (float)FF_QP2LAMBDA);

    } else {

        if (avctx->bit_rate) {

            if (s->abr) {                   // ABR

                lame_set_VBR(s->gfp, vbr_abr);

                lame_set_VBR_mean_bitrate_kbps(s->gfp, avctx->bit_rate / 1000);

            } else                          // CBR

                lame_set_brate(s->gfp, avctx->bit_rate / 1000);

        }

    }

    /* do not get a Xing VBR header frame from LAME */

    lame_set_bWriteVbrTag(s->gfp,0);

    /* bit reservoir usage */

    lame_set_disable_reservoir(s->gfp, !s->reservoir);

    /* set specified parameters */

    if (lame_init_params(s->gfp) < 0) {

        ret = -1;

        goto error;

    }

    /* get encoder delay */

    avctx->delay = lame_get_encoder_delay(s->gfp) + 528 + 1;

    ff_af_queue_init(avctx, &s->afq);

    avctx->frame_size  = lame_get_framesize(s->gfp);

    /* allocate float sample buffers */

    if (avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {

        int ch;

        for (ch = 0; ch < avctx->channels; ch++) {

            s->samples_flt[ch] = av_malloc(avctx->frame_size *

                                           sizeof(*s->samples_flt[ch]));

            if (!s->samples_flt[ch]) {

                ret = AVERROR(ENOMEM);

                goto error;

            }

        }

    }

    ret = realloc_buffer(s);

    if (ret < 0)

        goto error;

    avpriv_float_dsp_init(&s->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);

    return 0;

error:

    mp3lame_encode_close(avctx);

    return ret;

}


static int scsi_write_data(SCSIDevice *d, uint32_t tag)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);

    SCSIDiskReq *r;

    DPRINTF("Write data tag=0x%x\n", tag);

    r = scsi_find_request(s, tag);

    if (!r) {

        BADF("Bad write tag 0x%x\n", tag);

        scsi_command_complete(r, CHECK_CONDITION, HARDWARE_ERROR);

        return 1;

    }

    /* No data transfer may already be in progress */

    assert(r->req.aiocb == NULL);

    scsi_write_request(r);

    return 0;

}


void replay_account_executed_instructions(void)

{

    if (replay_mode == REPLAY_MODE_PLAY) {

        replay_mutex_lock();

        if (replay_state.instructions_count > 0) {

            int count = (int)(replay_get_current_step()

                              - replay_state.current_step);

            replay_state.instructions_count -= count;

            replay_state.current_step += count;

            if (replay_state.instructions_count == 0) {

                assert(replay_data_kind == EVENT_INSTRUCTION);

                replay_finish_event();

                /* Wake up iothread. This is required because

                   timers will not expire until clock counters

                   will be read from the log. */

                qemu_notify_event();

            }

        }

        replay_mutex_unlock();

    }

}


void qemu_co_rwlock_unlock(CoRwlock *lock)

{

    assert(qemu_in_coroutine());

    if (lock->writer) {

        lock->writer = false;

        while (!qemu_co_queue_empty(&lock->queue)) {

            /*

             * Wakeup every body. This will include some

             * writers too.

             */

            qemu_co_queue_next(&lock->queue);

        }

    } else {

        lock->reader--;

        assert(lock->reader >= 0);

        /* Wakeup only one waiting writer */

        if (!lock->reader) {

            qemu_co_queue_next(&lock->queue);

        }

    }

}


float32 HELPER(ucf64_sf2si)(float32 x, CPUUniCore32State *env)

{

    return ucf64_itos(float32_to_int32(x, &env->ucf64.fp_status));

}


static int pl061_init(SysBusDevice *dev, const unsigned char *id)

{

    int iomemtype;

    pl061_state *s = FROM_SYSBUS(pl061_state, dev);

    s->id = id;

    iomemtype = cpu_register_io_memory(pl061_readfn,

                                       pl061_writefn, s,

                                       DEVICE_NATIVE_ENDIAN);

    sysbus_init_mmio(dev, 0x1000, iomemtype);

    sysbus_init_irq(dev, &s->irq);

    qdev_init_gpio_in(&dev->qdev, pl061_set_irq, 8);

    qdev_init_gpio_out(&dev->qdev, s->out, 8);

    pl061_reset(s);

    register_savevm(&dev->qdev, "pl061_gpio", -1, 1, pl061_save, pl061_load, s);

    return 0;

}


void qemu_chr_reset(CharDriverState *s)

{

    if (s->bh == NULL && initial_reset_issued) {

	s->bh = qemu_bh_new(qemu_chr_reset_bh, s);

	qemu_bh_schedule(s->bh);

    }

}


static void omap_i2c_set_slave_addr(OMAPI2C *s, uint8_t addr)

{

    uint16_t data = addr;

    memwrite(s->addr + OMAP_I2C_SA, &data, 2);

    memread(s->addr + OMAP_I2C_SA, &data, 2);

    g_assert_cmphex(data, ==, addr);

}


static int read_packet(AVFormatContext *s,

                           AVPacket *pkt)

{

    MmDemuxContext *mm = s->priv_data;

    AVIOContext *pb = s->pb;

    unsigned char preamble[MM_PREAMBLE_SIZE];

    unsigned int type, length;

    while(1) {

        if (avio_read(pb, preamble, MM_PREAMBLE_SIZE) != MM_PREAMBLE_SIZE) {

            return AVERROR(EIO);

        type = AV_RL16(&preamble[0]);

        length = AV_RL16(&preamble[2]);

        switch(type) {

        case MM_TYPE_PALETTE :

        case MM_TYPE_INTER :

        case MM_TYPE_INTRA :

        case MM_TYPE_INTRA_HH :

        case MM_TYPE_INTER_HH :

        case MM_TYPE_INTRA_HHV :

        case MM_TYPE_INTER_HHV :

            /* output preamble + data */

            if (av_new_packet(pkt, length + MM_PREAMBLE_SIZE))

                return AVERROR(ENOMEM);

            memcpy(pkt->data, preamble, MM_PREAMBLE_SIZE);

            if (avio_read(pb, pkt->data + MM_PREAMBLE_SIZE, length) != length)

                return AVERROR(EIO);

            pkt->size = length + MM_PREAMBLE_SIZE;

            pkt->stream_index = 0;

            pkt->pts = mm->video_pts;

            if (type!=MM_TYPE_PALETTE)

                mm->video_pts++;

            return 0;

        case MM_TYPE_AUDIO :

            if (av_get_packet(s->pb, pkt, length)<0)

                return AVERROR(ENOMEM);

            pkt->size = length;

            pkt->stream_index = 1;

            pkt->pts = mm->audio_pts++;

            return 0;

        default :

            av_log(s, AV_LOG_INFO, "unknown chunk type 0x%x\n", type);


static int coroutine_fn qed_aio_write_cow(QEDAIOCB *acb)

{

    BDRVQEDState *s = acb_to_s(acb);

    uint64_t start, len, offset;

    int ret;

    /* Populate front untouched region of new data cluster */

    start = qed_start_of_cluster(s, acb->cur_pos);

    len = qed_offset_into_cluster(s, acb->cur_pos);

    trace_qed_aio_write_prefill(s, acb, start, len, acb->cur_cluster);

    ret = qed_copy_from_backing_file(s, start, len, acb->cur_cluster);

    if (ret < 0) {

        return ret;

    }

    /* Populate back untouched region of new data cluster */

    start = acb->cur_pos + acb->cur_qiov.size;

    len = qed_start_of_cluster(s, start + s->header.cluster_size - 1) - start;

    offset = acb->cur_cluster +

             qed_offset_into_cluster(s, acb->cur_pos) +

             acb->cur_qiov.size;

    trace_qed_aio_write_postfill(s, acb, start, len, offset);

    ret = qed_copy_from_backing_file(s, start, len, offset);

    if (ret < 0) {

        return ret;

    }

    ret = qed_aio_write_main(acb);

    if (ret < 0) {

        return ret;

    }

    if (s->bs->backing) {

        /*

         * Flush new data clusters before updating the L2 table

         *

         * This flush is necessary when a backing file is in use.  A crash

         * during an allocating write could result in empty clusters in the

         * image.  If the write only touched a subregion of the cluster,

         * then backing image sectors have been lost in the untouched

         * region.  The solution is to flush after writing a new data

         * cluster and before updating the L2 table.

         */

        ret = bdrv_co_flush(s->bs->file->bs);

        if (ret < 0) {

            return ret;

        }

    }

    return 0;

}


static void end_list(Visitor *v)

{

    StringInputVisitor *siv = to_siv(v);

    siv->head = true;

}


static void * attribute_align_arg worker(void *v){

    AVCodecContext *avctx = v;

    ThreadContext *c = avctx->internal->frame_thread_encoder;

    AVPacket *pkt = NULL;

    while(!c->exit){

        int got_packet, ret;

        AVFrame *frame;

        Task task;

        if(!pkt) pkt= av_mallocz(sizeof(*pkt));

        if(!pkt) continue;

        av_init_packet(pkt);

        pthread_mutex_lock(&c->task_fifo_mutex);

        while (av_fifo_size(c->task_fifo) <= 0 || c->exit) {

            if(c->exit){

                pthread_mutex_unlock(&c->task_fifo_mutex);

                goto end;

            }

            pthread_cond_wait(&c->task_fifo_cond, &c->task_fifo_mutex);

        }

        av_fifo_generic_read(c->task_fifo, &task, sizeof(task), NULL);

        pthread_mutex_unlock(&c->task_fifo_mutex);

        frame = task.indata;

        ret = avcodec_encode_video2(avctx, pkt, frame, &got_packet);

        pthread_mutex_lock(&c->buffer_mutex);

        av_frame_unref(frame);

        pthread_mutex_unlock(&c->buffer_mutex);

        av_frame_free(&frame);

        if(got_packet) {

            av_dup_packet(pkt);

        } else {

            pkt->data = NULL;

            pkt->size = 0;

        }

        pthread_mutex_lock(&c->finished_task_mutex);

        c->finished_tasks[task.index].outdata = pkt; pkt = NULL;

        c->finished_tasks[task.index].return_code = ret;

        pthread_cond_signal(&c->finished_task_cond);

        pthread_mutex_unlock(&c->finished_task_mutex);

    }

end:

    av_free(pkt);

    pthread_mutex_lock(&c->buffer_mutex);

    avcodec_close(avctx);

    pthread_mutex_unlock(&c->buffer_mutex);

    av_freep(&avctx);

    return NULL;

}


static void do_cont(void)

{

    vm_start();

}


void AUD_remove_card (QEMUSoundCard *card)

{

    LIST_REMOVE (card, entries);

    qemu_free (card->name);

}


static void phys_page_set_level(PhysPageEntry *lp, target_phys_addr_t *index,

                                target_phys_addr_t *nb, uint16_t leaf,

                                int level)

{

    PhysPageEntry *p;

    int i;

    target_phys_addr_t step = (target_phys_addr_t)1 << (level * L2_BITS);

    if (!lp->is_leaf && lp->ptr == PHYS_MAP_NODE_NIL) {

        lp->ptr = phys_map_node_alloc();

        p = phys_map_nodes[lp->ptr];

        if (level == 0) {

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

                p[i].is_leaf = 1;

                p[i].ptr = phys_section_unassigned;

            }

        }

    } else {

        p = phys_map_nodes[lp->ptr];

    }

    lp = &p[(*index >> (level * L2_BITS)) & (L2_SIZE - 1)];

    while (*nb && lp < &p[L2_SIZE]) {

        if ((*index & (step - 1)) == 0 && *nb >= step) {

            lp->is_leaf = true;

            lp->ptr = leaf;

            *index += step;

            *nb -= step;

        } else {

            phys_page_set_level(lp, index, nb, leaf, level - 1);

        }

        ++lp;

    }

}


static void tcx24_screen_dump(void *opaque, const char *filename, bool cswitch,

                              Error **errp)

{

    TCXState *s = opaque;

    FILE *f;

    uint8_t *d, *d1, v;

    uint32_t *s24, *cptr, dval;

    int ret, y, x;

    f = fopen(filename, "wb");

    if (!f) {

        error_setg(errp, "failed to open file '%s': %s", filename,

                   strerror(errno));

        return;

    }

    ret = fprintf(f, "P6\n%d %d\n%d\n", s->width, s->height, 255);

    if (ret < 0) {

        goto write_err;

    }

    d1 = s->vram;

    s24 = s->vram24;

    cptr = s->cplane;

    for(y = 0; y < s->height; y++) {

        d = d1;

        for(x = 0; x < s->width; x++, d++, s24++) {

            if ((*cptr++ & 0xff000000) == 0x03000000) { // 24-bit direct

                dval = *s24 & 0x00ffffff;

                ret = fputc((dval >> 16) & 0xff, f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc((dval >> 8) & 0xff, f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc(dval & 0xff, f);

                if (ret == EOF) {

                    goto write_err;

                }

            } else {

                v = *d;

                ret = fputc(s->r[v], f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc(s->g[v], f);

                if (ret == EOF) {

                    goto write_err;

                }

                ret = fputc(s->b[v], f);

                if (ret == EOF) {

                    goto write_err;

                }

            }

        }

        d1 += MAXX;

    }

out:

    fclose(f);

    return;

write_err:

    error_setg(errp, "failed to write to file '%s': %s", filename,

               strerror(errno));

    unlink(filename);

    goto out;

}


static int qcow2_open(BlockDriverState *bs, int flags)

{

    BDRVQcowState *s = bs->opaque;

    int len, i, ret = 0;

    QCowHeader header;

    uint64_t ext_end;

    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));

    if (ret < 0) {

        goto fail;

    }

    be32_to_cpus(&header.magic);

    be32_to_cpus(&header.version);

    be64_to_cpus(&header.backing_file_offset);

    be32_to_cpus(&header.backing_file_size);

    be64_to_cpus(&header.size);

    be32_to_cpus(&header.cluster_bits);

    be32_to_cpus(&header.crypt_method);

    be64_to_cpus(&header.l1_table_offset);

    be32_to_cpus(&header.l1_size);

    be64_to_cpus(&header.refcount_table_offset);

    be32_to_cpus(&header.refcount_table_clusters);

    be64_to_cpus(&header.snapshots_offset);

    be32_to_cpus(&header.nb_snapshots);

    if (header.magic != QCOW_MAGIC) {

        ret = -EINVAL;

        goto fail;

    }

    if (header.version < 2 || header.version > 3) {

        report_unsupported(bs, "QCOW version %d", header.version);

        ret = -ENOTSUP;

        goto fail;

    }

    s->qcow_version = header.version;

    /* Initialise version 3 header fields */

    if (header.version == 2) {

        header.incompatible_features    = 0;

        header.compatible_features      = 0;

        header.autoclear_features       = 0;

        header.refcount_order           = 4;

        header.header_length            = 72;

    } else {

        be64_to_cpus(&header.incompatible_features);

        be64_to_cpus(&header.compatible_features);

        be64_to_cpus(&header.autoclear_features);

        be32_to_cpus(&header.refcount_order);

        be32_to_cpus(&header.header_length);

    }

    if (header.header_length > sizeof(header)) {

        s->unknown_header_fields_size = header.header_length - sizeof(header);

        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);

        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,

                         s->unknown_header_fields_size);

        if (ret < 0) {

            goto fail;

        }

    }

    if (header.backing_file_offset) {

        ext_end = header.backing_file_offset;

    } else {

        ext_end = 1 << header.cluster_bits;

    }

    /* Handle feature bits */

    s->incompatible_features    = header.incompatible_features;

    s->compatible_features      = header.compatible_features;

    s->autoclear_features       = header.autoclear_features;

    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {

        void *feature_table = NULL;

        qcow2_read_extensions(bs, header.header_length, ext_end,

                              &feature_table);

        report_unsupported_feature(bs, feature_table,

                                   s->incompatible_features &

                                   ~QCOW2_INCOMPAT_MASK);

        ret = -ENOTSUP;

        goto fail;

    }

    /* Check support for various header values */

    if (header.refcount_order != 4) {

        report_unsupported(bs, "%d bit reference counts",

                           1 << header.refcount_order);

        ret = -ENOTSUP;

        goto fail;

    }

    if (header.cluster_bits < MIN_CLUSTER_BITS ||

        header.cluster_bits > MAX_CLUSTER_BITS) {

        ret = -EINVAL;

        goto fail;

    }

    if (header.crypt_method > QCOW_CRYPT_AES) {

        ret = -EINVAL;

        goto fail;

    }

    s->crypt_method_header = header.crypt_method;

    if (s->crypt_method_header) {

        bs->encrypted = 1;

    }

    s->cluster_bits = header.cluster_bits;

    s->cluster_size = 1 << s->cluster_bits;

    s->cluster_sectors = 1 << (s->cluster_bits - 9);

    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */

    s->l2_size = 1 << s->l2_bits;

    bs->total_sectors = header.size / 512;

    s->csize_shift = (62 - (s->cluster_bits - 8));

    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;

    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;

    s->refcount_table_offset = header.refcount_table_offset;

    s->refcount_table_size =

        header.refcount_table_clusters << (s->cluster_bits - 3);

    s->snapshots_offset = header.snapshots_offset;

    s->nb_snapshots = header.nb_snapshots;

    /* read the level 1 table */

    s->l1_size = header.l1_size;

    s->l1_vm_state_index = size_to_l1(s, header.size);

    /* the L1 table must contain at least enough entries to put

       header.size bytes */

    if (s->l1_size < s->l1_vm_state_index) {

        ret = -EINVAL;

        goto fail;

    }

    s->l1_table_offset = header.l1_table_offset;

    if (s->l1_size > 0) {

        s->l1_table = g_malloc0(

            align_offset(s->l1_size * sizeof(uint64_t), 512));

        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,

                         s->l1_size * sizeof(uint64_t));

        if (ret < 0) {

            goto fail;

        }

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

            be64_to_cpus(&s->l1_table[i]);

        }

    }

    /* alloc L2 table/refcount block cache */

    s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);

    s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);

    s->cluster_cache = g_malloc(s->cluster_size);

    /* one more sector for decompressed data alignment */

    s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size

                                  + 512);

    s->cluster_cache_offset = -1;

    s->flags = flags;

    ret = qcow2_refcount_init(bs);

    if (ret != 0) {

        goto fail;

    }

    QLIST_INIT(&s->cluster_allocs);

    /* read qcow2 extensions */

    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {

        ret = -EINVAL;

        goto fail;

    }

    /* read the backing file name */

    if (header.backing_file_offset != 0) {

        len = header.backing_file_size;

        if (len > 1023) {

            len = 1023;

        }

        ret = bdrv_pread(bs->file, header.backing_file_offset,

                         bs->backing_file, len);

        if (ret < 0) {

            goto fail;

        }

        bs->backing_file[len] = '\0';

    }

    ret = qcow2_read_snapshots(bs);

    if (ret < 0) {

        goto fail;

    }

    /* Clear unknown autoclear feature bits */

    if (!bs->read_only && s->autoclear_features != 0) {

        s->autoclear_features = 0;

        ret = qcow2_update_header(bs);

        if (ret < 0) {

            goto fail;

        }

    }

    /* Initialise locks */

    qemu_co_mutex_init(&s->lock);

    /* Repair image if dirty */

    if ((s->incompatible_features & QCOW2_INCOMPAT_DIRTY) &&

        !bs->read_only) {

        BdrvCheckResult result = {0};

        ret = qcow2_check_refcounts(bs, &result, BDRV_FIX_ERRORS);

        if (ret < 0) {

            goto fail;

        }

        ret = qcow2_mark_clean(bs);

        if (ret < 0) {

            goto fail;

        }

    }

#ifdef DEBUG_ALLOC

    {

        BdrvCheckResult result = {0};

        qcow2_check_refcounts(bs, &result, 0);

    }

#endif

    return ret;

 fail:

    g_free(s->unknown_header_fields);

    cleanup_unknown_header_ext(bs);

    qcow2_free_snapshots(bs);

    qcow2_refcount_close(bs);

    g_free(s->l1_table);

    if (s->l2_table_cache) {

        qcow2_cache_destroy(bs, s->l2_table_cache);

    }

    g_free(s->cluster_cache);

    qemu_vfree(s->cluster_data);

    return ret;

}


int ff_audio_mix_set_matrix(AudioMix *am, const double *matrix, int stride)

{

    int i, o;

    if ( am->in_channels <= 0 ||  am->in_channels > AVRESAMPLE_MAX_CHANNELS ||

        am->out_channels <= 0 || am->out_channels > AVRESAMPLE_MAX_CHANNELS) {

        av_log(am, AV_LOG_ERROR, "Invalid channel counts\n");

        return AVERROR(EINVAL);

    }

    if (am->matrix) {

        av_free(am->matrix[0]);

        am->matrix = NULL;

    }

#define CONVERT_MATRIX(type, expr)                                          \

    am->matrix_## type[0] = av_mallocz(am->out_channels * am->in_channels * \

                                       sizeof(*am->matrix_## type[0]));     \

    if (!am->matrix_## type[0])                                             \

        return AVERROR(ENOMEM);                                             \

    for (o = 0; o < am->out_channels; o++) {                                \

        if (o > 0)                                                          \

            am->matrix_## type[o] = am->matrix_## type[o - 1] +             \

                                    am->in_channels;                        \

        for (i = 0; i < am->in_channels; i++) {                             \

            double v = matrix[o * stride + i];                              \

            am->matrix_## type[o][i] = expr;                                \

        }                                                                   \

    }                                                                       \

    am->matrix = (void **)am->matrix_## type;

    switch (am->coeff_type) {

    case AV_MIX_COEFF_TYPE_Q8:

        CONVERT_MATRIX(q8, av_clip_int16(lrint(256.0 * v)))

        break;

    case AV_MIX_COEFF_TYPE_Q15:

        CONVERT_MATRIX(q15, av_clipl_int32(llrint(32768.0 * v)))

        break;

    case AV_MIX_COEFF_TYPE_FLT:

        CONVERT_MATRIX(flt, v)

        break;

    default:

        av_log(am, AV_LOG_ERROR, "Invalid mix coeff type\n");

        return AVERROR(EINVAL);

    }

    /* TODO: detect situations where we can just swap around pointers

             instead of doing matrix multiplications with 0.0 and 1.0 */

    return 0;

}


static int queue_attached_pictures(AVFormatContext *s)

{

    int i;

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

        if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&

            s->streams[i]->discard < AVDISCARD_ALL) {

            AVPacket copy = s->streams[i]->attached_pic;

            copy.buf = av_buffer_ref(copy.buf);

            if (!copy.buf)

                return AVERROR(ENOMEM);

            add_to_pktbuf(&s->internal->raw_packet_buffer, &copy,

                          &s->internal->raw_packet_buffer_end);

        }

    return 0;

}


AioContext *aio_context_new(Error **errp)

{

    int ret;

    AioContext *ctx;

    ctx = (AioContext *) g_source_new(&aio_source_funcs, sizeof(AioContext));

    aio_context_setup(ctx);

    ret = event_notifier_init(&ctx->notifier, false);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Failed to initialize event notifier");

        goto fail;

    }

    g_source_set_can_recurse(&ctx->source, true);

    aio_set_event_notifier(ctx, &ctx->notifier,

                           false,

                           (EventNotifierHandler *)

                           event_notifier_dummy_cb,

                           event_notifier_poll);

#ifdef CONFIG_LINUX_AIO

    ctx->linux_aio = NULL;

#endif

    ctx->thread_pool = NULL;

    qemu_mutex_init(&ctx->bh_lock);

    qemu_rec_mutex_init(&ctx->lock);

    timerlistgroup_init(&ctx->tlg, aio_timerlist_notify, ctx);

    ctx->poll_max_ns = 0;

    return ctx;

fail:

    g_source_destroy(&ctx->source);

    return NULL;

}


static void opt_frame_pad_top(const char *arg)

{

    frame_padtop = atoi(arg);

    if (frame_padtop < 0) {

        fprintf(stderr, "Incorrect top pad size\n");

        av_exit(1);

    }

}


static void chr_event(void *opaque, int event)

{

    Terminal3270 *t = opaque;

    CcwDevice *ccw_dev = CCW_DEVICE(t);

    SubchDev *sch = ccw_dev->sch;

    /* Ensure the initial status correct, always reset them. */

    t->in_len = 0;

    t->out_len = 0;

    t->handshake_done = false;

    if (t->timer_tag) {

        g_source_remove(t->timer_tag);

        t->timer_tag = 0;

    }

    switch (event) {

    case CHR_EVENT_OPENED:

        /*

         * 3270 does handshake firstly by the negotiate options in

         * char-socket.c. Once qemu receives the terminal-type of the

         * client, mark handshake done and trigger everything rolling again.

         */

        t->timer_tag = g_timeout_add_seconds(600, send_timing_mark_cb, t);

        break;

    case CHR_EVENT_CLOSED:

        sch->curr_status.scsw.dstat = SCSW_DSTAT_DEVICE_END;

        css_conditional_io_interrupt(sch);

        break;

    }

}


static void tgen_ext8u(TCGContext *s, TCGType type, TCGReg dest, TCGReg src)

{

    if (facilities & FACILITY_EXT_IMM) {

        tcg_out_insn(s, RRE, LLGCR, dest, src);

        return;

    }

    if (dest == src) {

        tcg_out_movi(s, type, TCG_TMP0, 0xff);

        src = TCG_TMP0;

    } else {

        tcg_out_movi(s, type, dest, 0xff);

    }

    if (type == TCG_TYPE_I32) {

        tcg_out_insn(s, RR, NR, dest, src);

    } else {

        tcg_out_insn(s, RRE, NGR, dest, src);

    }

}


static bool esp_mem_accepts(void *opaque, target_phys_addr_t addr,

                            unsigned size, bool is_write)

{

    return (size == 1) || (is_write && size == 4);

}


SDState *sd_init(BlockBackend *blk, bool is_spi)

{

    SDState *sd;

    if (blk && blk_is_read_only(blk)) {

        fprintf(stderr, "sd_init: Cannot use read-only drive\n");

        return NULL;

    }

    sd = (SDState *) g_malloc0(sizeof(SDState));

    sd->buf = blk_blockalign(blk, 512);

    sd->spi = is_spi;

    sd->enable = true;

    sd_reset(sd, blk);

    if (sd->blk) {

        blk_attach_dev_nofail(sd->blk, sd);

        blk_set_dev_ops(sd->blk, &sd_block_ops, sd);

    }

    vmstate_register(NULL, -1, &sd_vmstate, sd);

    return sd;

}


static uint64_t *store_bitmap_data(BlockDriverState *bs,

                                   BdrvDirtyBitmap *bitmap,

                                   uint32_t *bitmap_table_size, Error **errp)

{

    int ret;

    BDRVQcow2State *s = bs->opaque;

    int64_t sector;

    uint64_t limit, sbc;

    uint64_t bm_size = bdrv_dirty_bitmap_size(bitmap);

    uint64_t bm_sectors = DIV_ROUND_UP(bm_size, BDRV_SECTOR_SIZE);

    const char *bm_name = bdrv_dirty_bitmap_name(bitmap);

    uint8_t *buf = NULL;

    BdrvDirtyBitmapIter *dbi;

    uint64_t *tb;

    uint64_t tb_size =

            size_to_clusters(s,

                bdrv_dirty_bitmap_serialization_size(bitmap, 0, bm_size));

    if (tb_size > BME_MAX_TABLE_SIZE ||

        tb_size * s->cluster_size > BME_MAX_PHYS_SIZE)

    {

        error_setg(errp, "Bitmap '%s' is too big", bm_name);

        return NULL;

    }

    tb = g_try_new0(uint64_t, tb_size);

    if (tb == NULL) {

        error_setg(errp, "No memory");

        return NULL;

    }

    dbi = bdrv_dirty_iter_new(bitmap);

    buf = g_malloc(s->cluster_size);

    limit = bytes_covered_by_bitmap_cluster(s, bitmap);

    sbc = limit >> BDRV_SECTOR_BITS;

    assert(DIV_ROUND_UP(bm_size, limit) == tb_size);

    while ((sector = bdrv_dirty_iter_next(dbi) >> BDRV_SECTOR_BITS) >= 0) {

        uint64_t cluster = sector / sbc;

        uint64_t end, write_size;

        int64_t off;

        sector = cluster * sbc;

        end = MIN(bm_sectors, sector + sbc);

        write_size = bdrv_dirty_bitmap_serialization_size(bitmap,

            sector * BDRV_SECTOR_SIZE, (end - sector) * BDRV_SECTOR_SIZE);

        assert(write_size <= s->cluster_size);

        off = qcow2_alloc_clusters(bs, s->cluster_size);

        if (off < 0) {

            error_setg_errno(errp, -off,

                             "Failed to allocate clusters for bitmap '%s'",

                             bm_name);

            goto fail;

        }

        tb[cluster] = off;

        bdrv_dirty_bitmap_serialize_part(bitmap, buf,

                                         sector * BDRV_SECTOR_SIZE,

                                         (end - sector) * BDRV_SECTOR_SIZE);

        if (write_size < s->cluster_size) {

            memset(buf + write_size, 0, s->cluster_size - write_size);

        }

        ret = qcow2_pre_write_overlap_check(bs, 0, off, s->cluster_size);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Qcow2 overlap check failed");

            goto fail;

        }

        ret = bdrv_pwrite(bs->file, off, buf, s->cluster_size);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Failed to write bitmap '%s' to file",

                             bm_name);

            goto fail;

        }

        if (end >= bm_sectors) {

            break;

        }

        bdrv_set_dirty_iter(dbi, end * BDRV_SECTOR_SIZE);

    }

    *bitmap_table_size = tb_size;

    g_free(buf);

    bdrv_dirty_iter_free(dbi);

    return tb;

fail:

    clear_bitmap_table(bs, tb, tb_size);

    g_free(buf);

    bdrv_dirty_iter_free(dbi);

    g_free(tb);

    return NULL;

}


iscsi_synccache10_cb(struct iscsi_context *iscsi, int status,

                     void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    if (acb->canceled != 0) {

        return;

    }

    acb->status = 0;

    if (status != 0) {

        if (status == SCSI_STATUS_CHECK_CONDITION

            && acb->task->sense.key == SCSI_SENSE_UNIT_ATTENTION

            && acb->retries-- > 0) {

            if (acb->task != NULL) {

                scsi_free_scsi_task(acb->task);

                acb->task = NULL;

            }

            if (iscsi_aio_flush_acb(acb) == 0) {

                iscsi_set_events(acb->iscsilun);

                return;

            }

        }

        error_report("Failed to sync10 data on iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    iscsi_schedule_bh(acb);

}


static void virtio_net_set_config(VirtIODevice *vdev, const uint8_t *config)

{

    VirtIONet *n = VIRTIO_NET(vdev);

    struct virtio_net_config netcfg = {};

    memcpy(&netcfg, config, n->config_size);

    if (!(vdev->guest_features >> VIRTIO_NET_F_CTRL_MAC_ADDR & 1) &&

        memcmp(netcfg.mac, n->mac, ETH_ALEN)) {

        memcpy(n->mac, netcfg.mac, ETH_ALEN);

        qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);

    }

}


static void set_frame_data(MIContext *mi_ctx, int alpha, AVFrame *avf_out)

{

    int x, y, plane;

    for (plane = 0; plane < mi_ctx->nb_planes; plane++) {

        int width = avf_out->width;

        int height = avf_out->height;

        int chroma = plane == 1 || plane == 2;

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

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

                int x_mv, y_mv;

                int weight_sum = 0;

                int i, val = 0;

                Pixel *pixel = &mi_ctx->pixels[x + y * avf_out->width];

                for (i = 0; i < pixel->nb; i++)

                    weight_sum += pixel->weights[i];

                if (!weight_sum || !pixel->nb) {

                    pixel->weights[0] = ALPHA_MAX - alpha;

                    pixel->refs[0] = 1;

                    pixel->mvs[0][0] = 0;

                    pixel->mvs[0][1] = 0;

                    pixel->weights[1] = alpha;

                    pixel->refs[1] = 2;

                    pixel->mvs[1][0] = 0;

                    pixel->mvs[1][1] = 0;

                    pixel->nb = 2;

                    weight_sum = ALPHA_MAX;

                }

                for (i = 0; i < pixel->nb; i++) {

                    Frame *frame = &mi_ctx->frames[pixel->refs[i]];

                    if (chroma) {

                        x_mv = (x >> mi_ctx->chroma_h_shift) + (pixel->mvs[i][0] >> mi_ctx->chroma_h_shift);

                        y_mv = (y >> mi_ctx->chroma_v_shift) + (pixel->mvs[i][1] >> mi_ctx->chroma_v_shift);

                    } else {

                        x_mv = x + pixel->mvs[i][0];

                        y_mv = y + pixel->mvs[i][1];

                    }

                    val += pixel->weights[i] * frame->avf->data[plane][x_mv + y_mv * frame->avf->linesize[plane]];

                }

                val = ROUNDED_DIV(val, weight_sum);

                if (chroma)

                    avf_out->data[plane][(x >> mi_ctx->chroma_h_shift) + (y >> mi_ctx->chroma_v_shift) * avf_out->linesize[plane]] = val;

                else

                    avf_out->data[plane][x + y * avf_out->linesize[plane]] = val;

            }

    }

}


void trace_init_vcpu_events(void)

{

    TraceEvent *ev = NULL;

    while ((ev = trace_event_pattern("*", ev)) != NULL) {

        if (trace_event_is_vcpu(ev) &&

            trace_event_get_state_static(ev) &&

            trace_event_get_state_dynamic(ev)) {

            TraceEventID id = trace_event_get_id(ev);

            /* check preconditions */

            assert(trace_events_dstate[id] == 1);

            /* disable early-init state ... */

            trace_events_dstate[id] = 0;

            trace_events_enabled_count--;

            /* ... and properly re-enable */

            trace_event_set_state_dynamic(ev, true);

        }

    }

}